Compare commits

..
224 Commits
Author SHA1 Message Date
sk89q ca95ae04a5 [maven-release-plugin] prepare release 5.5.3 2012-07-07 10:55:45 -07:00
sk89q 1ab9f85ca6 Updated CHANGELOG. 2012-07-07 10:39:37 -07:00
sk89q 01ff1b2f8f Added host key check. 2012-07-07 10:33:18 -07:00
Zak Ford 9b17fe68e7 Added configuration option to allow plugin creature spawns 2012-07-01 16:02:24 -04:00
zml2008 0fed35a80f Add bypass handling to the gamemode flag
Set a player's previous gamemode when exiting a gamemode region to the server's default gamemode if there is not a previous gamemode already set
2012-06-15 14:14:13 -07:00
TomyLobo 25280c9fa9 Set Bukkit dependency to R2.1.
That's the current CraftBukkit++ version.
2012-06-11 03:31:50 +02:00
TomyLobo a98ebfdb21 Updated dependencies and added support for fireball item blocking (id 385). 2012-06-07 13:26:28 +02:00
TomyLobo 18b5a4e106 Added @Ignore to TestPlayer.
Stupid old mavens...
2012-04-23 11:07:05 +02:00
md_5 bab420a359 Add item drop pickup flag for regions.
Closes #200
2012-04-20 20:25:25 -07:00
zml2008 4f14f1f736 Correctly convert \n to a newline for String flags 2012-04-16 17:00:41 -07:00
zml2008 166831447c Split the region greeting with \n
Improve input handling of EnumFlag
Don't block gamemode changing after the gamemode flag is no longer in
effect but while the move event is still firing
2012-04-15 21:19:02 -07:00
zml2008 f2bd5961d0 Add GameMode flag 2012-04-15 21:19:02 -07:00
zml2008 2cc990a530 Prevent commands in the allow commands list from being blocked and vice versa 2012-04-15 21:19:02 -07:00
TomyLobo f0e6008563 Updated bukkit dependency to 1.2.5-R1.2-SNAPSHOT. 2012-04-15 19:36:15 +02:00
zml2008 93f19cca0a [maven-release-plugin] prepare for next development iteration 2012-04-10 18:30:42 -07:00
zml2008 1cbe508f82 [maven-release-plugin] prepare release 5.5.2 2012-04-10 18:30:36 -07:00
zml2008 0c178c3155 Added recent commits to the changelog 2012-04-10 18:20:57 -07:00
zml2008 e67304389d Added send-chat and receive-chat flags 2012-04-07 14:43:51 -07:00
zml2008 ad5b1cdcba Make sure to update CommandBook installed status in onEnable 2012-04-07 13:46:25 -07:00
zml2008 fe1e09289f Add entity-painting-destroy flag to prevent entities from destroying paintings 2012-04-07 13:45:46 -07:00
zml2008 583ea76e4b Added potion splash flag to prevent splash potions from affecting entities 2012-04-07 12:11:00 -07:00
zml2008 a7d198893e Revert "Added allow-flight boolean flag for regions"
This conflicted with plugins maually setting a player's allow flight setting
This reverts commit 16ce56c1ad.
2012-03-31 07:53:42 -07:00
Nicholas Steicke fe62c8d0c5 Fixed regions with same name in different worlds not behaving correctly
Fixed database connection timing out

Added an error to be thrown explictly when the DB needs updating

Added a generic exception for Fatal errors when loading configuration

Exit the server when we encounter a fatal configuration exception
2012-03-27 17:18:39 -07:00
Deaygo 16ce56c1ad Added allow-flight boolean flag for regions
Closes #198
2012-03-24 18:45:56 -07:00
zml2008 15f0bfb9db Update changelog for release 2012-03-23 21:47:34 -07:00
TomyLobo 22db589742 Restructured /rg list.
- When used with a player name to filter things down, it displays indexes that can be used as "#index" in place of region names now.
- No longer displayer "+-regionname" for regions the target player is the owner of.
2012-03-23 15:13:46 +01:00
TomyLobo 69119e6db7 Added ProtectedRegion.isOwner/Member(String playerName). 2012-03-23 15:13:45 +01:00
TomyLobo 690da2332b Added Domain.contains(String playerName). 2012-03-23 15:13:45 +01:00
sk89q f2fead1444 Changed broadcastNotification() to also check if the player has permission via superperms, in addition to being in the Permissible set. 2012-03-18 13:13:13 -07:00
TomyLobo c4f6267921 A cancellable event is now fired if WorldGuard disallows PvP. 2012-03-17 09:16:03 +01:00
TomyLobo 0dc65d083f Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
Same with worldguard.region.setparent.<id>
2012-03-12 15:08:35 +01:00
TomyLobo 40c1d93f02 Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
/region claim/remove/redefine are exempt from this and require exact matches.
2012-03-12 15:05:59 +01:00
TomyLobo 2024a93126 Fixed an error that occured when clearing a non-existant region's parent. 2012-03-12 15:05:32 +01:00
TomyLobo 88d79a42e6 Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region. 2012-03-12 10:40:03 +01:00
TomyLobo b01b2cce9b Added region/role-based permissions to /region teleport. 2012-03-12 10:39:23 +01:00
TomyLobo c5b1089c96 Changed source and target java version to 1.6 and set the WE dependency to 5.3-SNAPSHOT. 2012-03-12 08:04:08 +01:00
TomyLobo 679e43758b BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
This means all teleport and spawn flags are cleared.
This also means that world, yaw and pitch are now saved with these flags.
2012-03-12 06:52:36 +01:00
TomyLobo 90e6e5a96c /region info -s now selects the region being queried. 2012-03-12 05:53:58 +01:00
TomyLobo 4fb003c4df Added /region teleport <id>. 2012-03-11 19:31:02 +01:00
TomyLobo 9d5f349a04 Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z. 2012-03-11 19:08:25 +01:00
TomyLobo f4f4a47a7f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:08:24 +01:00
TomyLobo 6a3e987668 /region info changes
- Fixed /region info <world> <id> checking the wrong permission
- Condensed /region info output a bit
- Cleaned up the source a bit
2012-03-11 19:07:25 +01:00
TomyLobo 83f943965f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:07:25 +01:00
zml2008 c9fdff169f Prevent block ignition from lightning strikes if lightning is blocked in region.
Fixes #1175
2012-03-10 21:33:24 -08:00
zml2008 5454832918 Fix trailing whitespace and correctly check both permisions systems in WorldGurdPlugin.broadcastNotification() 2012-03-10 17:56:02 -08:00
zml2008 3d6d774b17 Use ignoreCancelled for event cancelled checking 2012-03-08 19:29:53 -08:00
zml2008 1463547af4 Destroy fire blocks when fire-spread is disallowed 2012-03-08 19:03:05 -08:00
TomyLobo 0bcf4b3597 Added a "none" category to region group flags (aliases noone and deny). 2012-03-08 10:30:57 +01:00
TomyLobo 824e8dcb4b Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles. 2012-03-08 10:18:27 +01:00
TomyLobo 4b2f0c8020 Let's not confuse certain highlighters. 2012-03-08 02:05:33 +01:00
Wizjany 7fd424cf65 Added FallingSand to list of intensive entities to be removed with /halt-activiy. 2012-03-03 21:27:35 -05:00
zml2008 5ff2855eb0 Fix entry and exit group flags not working, fix vehicle destroy flag not being allowed with canBuild 2012-03-03 16:46:06 -08:00
TomyLobo 8c8c162a54 Replaced all usage of CreatureType by EntityType. 2012-03-02 20:21:04 +01:00
TomyLobo 37d52f3688 Commented an unused local variable. 2012-03-02 20:10:51 +01:00
TomyLobo f361cbfa71 Removed unused imports. 2012-03-02 20:03:18 +01:00
sk89q ddefbfe2cf Fixed NPE with null ItemStack for pumpkin scuba in EntityDamageEvent. 2012-03-02 10:33:14 -08:00
sk89q 10296cb736 Made auto-god-mode disabled by default again. 2012-03-01 20:57:34 -08:00
zml2008 49dc0599c9 Remove leftover 128 value, fix RegionGroup.ALL handling 2012-03-01 20:49:01 -08:00
zml2008 14348e170b Revert a few of the region flag changes. This should fix issues people have been having at least for now. 2012-03-01 20:11:51 -08:00
zml2008 59d1f0d817 5.5.1 release, bump to 5.5.2-SNAPSHOT to fix stuff 2012-03-01 20:11:50 -08:00
sk89q e024f134a4 Fixed another NPE with the infinite stack remover. 2012-03-01 20:06:02 -08:00
sk89q cf5a5b5b47 Fixed NPE in PlayerInteractEvent regarding infinite stack removal. 2012-03-01 19:52:53 -08:00
sk89q e957f92496 Added sign protection check disable. 2012-03-01 18:51:44 -08:00
TomyLobo 9484bb9941 Fixed some more warnings. 2012-02-25 18:58:22 +01:00
TomyLobo d781f9822f Removed some unused imports. 2012-02-25 18:54:46 +01:00
Wizjany 7845ef2de4 Revert b918b2914.
That breaks it, look at the other use flags before making changes.
2012-02-22 11:36:30 -05:00
zml2008 a9d4ecf33d Improved some group flag defaults to match pre-change behavior 2012-02-20 15:17:34 -08:00
zml2008 6f4a62c7a3 Cleaned up javadoc, deprecated duplicate methods, other cleanup 2012-02-20 15:14:55 -08:00
zml2008 6b4f872742 Added a RegionGroupFlag to evey region flag
Using the /region flag command with -g, the region group that the region flag applies to can be set
Many canBuild checks that occurred with other flag checks have been
replced with this. Some flag checks may be incorrect, and other parts of
this system may need improvement.
2012-02-19 23:31:55 -08:00
zml2008 ef4f00f8f5 Add region information to CommandBook's /whois if CommandBook is eanbled 2012-02-19 21:26:45 -08:00
zml2008 a27deb3936 Removed suppress-tick-sync-warnings setting
This setting often didn't work for people, and has been replaced in CraftBukkit's bukkit.yml with settings.warn-on-overload
2012-02-19 21:24:53 -08:00
TomyLobo 18814c7373 Set WorldGuardPlayerListener.PlayerMoveHandler to default visibility, to fix a warning about unused methods. 2012-02-14 02:32:35 +01:00
TomyLobo 1d9908e1f6 Merged the handlers for EndermanPickup/PlaceEvent into a EntityChangeBlockEvent handler. 2012-02-14 02:32:24 +01:00
TomyLobo 29529e4a06 Removed unused imports. 2012-02-14 02:23:35 +01:00
TomyLobo 74b1003c4c Upped dependency versions for bukkit and worldedit. 2012-02-14 02:21:54 +01:00
NolanSyKinsley 27ffdec323 Fixes shooting onto pvp areas from nopvp areas 2012-02-13 13:54:44 -08:00
zml2008 d9e5fc2b60 [maven-release-plugin] prepare for next development iteration 2012-02-11 16:22:22 -08:00
zml2008 646b3e3064 [maven-release-plugin] prepare release 5.5 2012-02-11 16:22:17 -08:00
zml2008 d3475208ef Add correct git tag defaults to the release plugin config 2012-02-11 16:16:47 -08:00
zml2008 7246da472d Added changelog for 5.5 2012-02-11 16:11:42 -08:00
zml2008 e1f917894a Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader 2012-02-11 12:20:56 -08:00
zml2008 c14d25f860 Now using Bukkit's tagged logging 2012-02-11 12:20:56 -08:00
TomyLobo 57ed91cd28 Updated to new event system 2012-02-11 12:20:56 -08:00
MonsieurApple 47c84beb43 Merge pull request #190 from skeight/master
Fix for bug #728 (Multiverse + Worldguard region with exit flag set)
2012-02-10 11:40:34 -08:00
skeight 1e3032bdce More whitespace fixes... 2012-02-10 11:30:43 -08:00
skeight ed69684843 Fixing up whitespace 2012-02-10 11:29:48 -08:00
skeight 2eea5c7bf7 Fix for bug #728. Multiverse + WorldGuard region exit flag. 2012-02-10 09:06:05 -08:00
zml2008 16da53ae4e Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0 2012-02-06 20:41:39 -08:00
Nicholas Steicke f45464b0d9 Added MySQL region storage method.
Also added ProtectionDatabaseException, and made use of it across the project
Closes #180
2012-02-07 00:11:55 +01:00
Wesley Wolfe 2351ade6fe Fix inconsistent permission check
Closes #188
2012-02-07 00:11:54 +01:00
Turtle9598 c19ccf9278 Made explosions display their animations even when the event was blocked.
Closes #184
2012-02-07 00:11:54 +01:00
zml2008 5c92762ba9 Configuration should be fixed for real. Finally. 2012-02-07 00:11:54 +01:00
zml2008 e665f966e6 These checks may not work correctly, so reverted 2012-02-07 00:11:53 +01:00
zml2008 7dcca7e505 Fixed default entries not appearing in the global configuration 2012-02-07 00:11:53 +01:00
zml2008 e25049b1d6 Added fallback support for those who don't have a version of CommandBook with GodComponent 2012-02-07 00:11:50 +01:00
zml2008 da9bc4a138 Added LIGHTNING flag to DefaultFlag's flagsList
Fixes #1026
2012-02-06 23:06:12 +01:00
zml2008 1224d3b443 Corrected formatting of configuration files
Fixes #1025
2012-02-06 23:05:39 +01:00
zml2008 d33be37694 Removed /god, /heal, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded. 2012-02-06 23:05:30 +01:00
zml2008 551ff26a65 Removed remaining usages of org.bukkit.util.config.Configuration 2012-01-23 16:46:13 -08:00
zml2008 74082f9c68 Updated Bukkit repo 2012-01-20 23:45:39 -08:00
zml2008 b93331e184 Removed some unused configuration options 2012-01-11 18:04:14 -08:00
zml2008 d5d26168b3 Added permission worldguard.region.wand to the region wand
Closes #930
2012-01-10 21:15:00 -08:00
TomyLobo 9d848e222b Fixed ProtectedRegion.compareTo.
It properly implements the Comparable interface now.
In particular, it now fulfills the criterion "sgn(x.compareTo(y)) == -sgn(y.compareTo(x))".
2012-01-09 14:47:59 +01:00
TomyLobo 46a2510e85 Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
Thanks FearThe1337 for noticing.
2012-01-09 14:10:23 +01:00
TomyLobo 0789a453a2 Added a .gitattributes file
This will make your diffs show method names instead of class names on the hunk headers.
2012-01-03 14:47:46 +01:00
zml2008 b30f7fe9c7 Removed usage of Material. 2011-12-31 17:57:09 -08:00
zml2008 525bd199b2 Added exp-drops flag to disable experience drops per-region. 2011-12-31 13:50:43 -08:00
TomyLobo dffd8b59f5 Fixed some warnings. 2011-12-26 11:02:38 +01:00
TomyLobo df206724bd Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
This fixes a warning about raw types.
2011-12-26 10:57:52 +01:00
zml2008 41f31250a9 Added support for fireballs shot by players being blocked by the PVP flag. 2011-12-24 22:49:37 -08:00
zml2008 b29007275f Added dynamic command registration and updated for WE 5.0 API 2011-12-24 22:49:37 -08:00
TomyLobo 35f268319e Split off ender dragon block damage from creeper block damage. 2011-12-18 23:16:12 +01:00
zml2008 6e8a185b63 [maven-release-plugin] prepare for next development iteration 2011-12-17 20:16:48 -08:00
zml2008 120fff1fc4 [maven-release-plugin] prepare release 5.4 2011-12-17 20:16:41 -08:00
zml2008 f879bd5e3a Updated changelog for release 2011-12-17 19:37:24 -08:00
Turtle9598 01f9fd561d Made WorldGuard check to see if both the attacker & defender are in a pvp area. 2011-12-14 20:15:42 -05:00
DerFlash 6802a7d747 Raised the priority of WorldGuard's respawn event listener. 2011-12-11 08:34:14 -08:00
DerFlash b918b29014 Fixed not being able to fill milk buckets in build deny regions
Though added a check for use flag here
2011-12-11 08:29:42 -08:00
zml2008 4895a3313b Forgot to update /slay, /wg report, and /stoplag to new commands system 2011-12-10 12:52:32 -08:00
zml2008 59673c9e66 Simplified autogod config check 2011-12-09 17:57:40 -08:00
Turtle9598 b126255be7 Fixed god mode being assigned to ops if auto enable is false and there is no permissions system
This fixes Bug #873
2011-12-10 01:15:14 +01:00
TomyLobo 606c9f3fd8 Revert "Readded the legacy console sender."
This reverts commit b1256eedcf.
Reason: this breaks if someone modifies CommandSender
The only advantage of having this class is to keep WorldGuard working with old 1.8 builds and pre-1.8 builds.
2011-12-08 14:38:05 +01:00
zml2008 aa306a8df7 Added additional worldguard.stack.damaged permissions to allow stacking of tools with a different damage value 2011-12-07 22:27:00 -08:00
zml2008 b1256eedcf Readded the legacy console sender. 2011-12-07 22:25:41 -08:00
zml2008 4454df341f Commented ProtectedPolygonalRegion.volume() out until someone can fix it. 2011-12-07 21:33:47 -08:00
TomyLobo 5bcac17f1c Fixed compilation with Bukkit >= CB1564.
Sorry, this breaks compatibility with builds < CB1193.
2011-12-08 02:34:26 +01:00
TomyLobo 875b9f326c Removed deprecation of RegionManager.getApplicableRegions.
The underlying functionality has since been implemented.
Also: woo, no more warnings
2011-12-05 06:03:52 +01:00
zml2008 a0d27c6f86 Added WorldEdit as a softdepend. This may fix some issues where WorldEdit's classes cannot be found. 2011-12-04 21:02:39 +01:00
zml2008 1d47d12189 Hopefully fixed WorldConfiguration.getKeys 2011-12-04 10:02:07 -08:00
zml2008 67f78ae8b5 Added per-group region claim maximums 2011-12-04 00:54:33 -08:00
zml2008 5948855da7 Added some more 1.0.0 blocks I forgot 2011-12-02 18:55:29 -08:00
zml2008 f6ec46cdf6 Now actually registering world events 2011-11-30 20:18:03 -08:00
zml2008 ebd2755eb2 Wrong this. 2011-11-30 19:24:53 -08:00
zml2008 78f5827d3d Always the imports... 2011-11-30 19:04:50 -08:00
zml2008 0829070c67 Added some OSX filesystem dust to gitignore and fixed pom.xml comment 2011-11-30 19:01:05 -08:00
zml2008 8b4332e842 Updated for new commands format 2011-11-30 18:59:02 -08:00
zml2008 f904c91443 Updated for Bukkit 1.0 and handling new 1.0 block types in USE flag 2011-11-30 18:59:02 -08:00
Eric Puidokas 944539453e Fixed feed-delay flag 2011-11-29 19:40:08 -08:00
TomyLobo 5856b002df Added .gitignore 2011-11-28 04:39:03 +01:00
TomyLobo 12f68bc227 Fixed a warning 2011-11-28 04:37:30 +01:00
TomyLobo de6e20d60a Improved error messages for group and state flags. 2011-10-30 04:07:37 +01:00
Eric Puidokas 35e6ef5cd8 Implemented edge intersection checking 2011-10-19 23:48:02 +02:00
Eric Puidokas 27251dda2e Refactored and fixed getIntersectingRegions 2011-10-19 23:47:13 +02:00
Eric Puidokas 4bb967ab4a Added Cuboid -> Polygonal intersect tests 2011-10-19 16:21:14 +02:00
Eric Puidokas 7c1f878610 Fixed ProtectedCuboidRegion->ProtectedCuboidRegion intersection checking 2011-10-19 16:21:14 +02:00
Wizjany e8c4c9b218 Fixed sticky pistons not being blocked by the flag in some cases 2011-10-18 17:49:05 -04:00
Eric Puidokas bc37d365ab Added unit tests for ProtectedCuboidRegion.getIntersectingRegions 2011-10-18 02:43:00 +02:00
TomyLobo d9ae1bbd9f Made LegacyConsoleSender compatible with patched Bukkit versions that add methods to CommandSender again.
Don't remove this again, wizjany.
2011-10-16 12:26:22 +02:00
zml2008 e492b30178 Added food level support to godmode and /heal 2011-10-15 23:51:28 -07:00
TomyLobo 920860c298 Fixed some warnings 2011-10-13 15:39:52 -04:00
Wizjany 5f8a6e3423 Workaround for tnt activating as soon as it was placed, regardless of cancellation. 2011-10-11 20:11:07 -04:00
Wizjany 3e7a5056d5 Fixed changelog not getting packaged with the release. 2011-10-09 11:51:43 -04:00
Wizjany 2ec6f04763 Implement non-economy 'buying' of regions via addowner 2011-10-09 11:51:43 -04:00
Wizjany ecef9c9792 Hopefully fix region managers not being created correctly. 2011-10-04 17:43:27 -04:00
Wizjany 810501a508 Added the missing timer to the food flags. 2011-10-04 16:26:54 -04:00
Wizjany 6285a66d76 Fixed allowed/blocked commands not being checked early enough. 2011-10-02 13:36:09 -04:00
zml2008 72e4922e8e Fixed config generation for Windows users 2011-10-02 01:30:10 -07:00
sk89q c1f1885633 [maven-release-plugin] prepare for next development iteration 2011-10-01 20:52:04 -07:00
sk89q 56e514a500 [maven-release-plugin] prepare release 5.3 2011-10-01 20:51:49 -07:00
sk89q 5ede100d56 Changed WorldGuard to use WE 4.7 in the pom.xml. 2011-10-01 20:50:35 -07:00
sk89q f1456b8101 Updated CHANGELOG.txt for 5.3. 2011-10-01 20:26:07 -07:00
Eric Puidokas ef8eb76b16 Added protection.disable-obsidian-generators option 2011-10-01 17:16:45 -04:00
Wizjany b4f2188f72 Added vehicle destroy flag and made players in vehicles subject to movement flags. 2011-10-01 17:16:37 -04:00
zml2008 38c30f5ecd Should fix broken config generation some people have been getting 2011-10-01 16:17:16 -04:00
Wizjany 94c794de6f Trailing whitespace removal 2011-09-27 06:13:19 -04:00
Wizjany fb535e620c Use per-world permissions if supported. 2011-09-26 01:32:48 -04:00
Wizjany 5a42980d78 Fix hunger flags and death messages. 2011-09-26 00:19:57 -04:00
Wizjany 299d2a1f01 That should probably be there 2011-09-25 23:42:50 -04:00
Wizjany 164ff5ea9a Added missing dependency 2011-09-25 23:37:25 -04:00
Wizjany 6c89ef908a Clean up and preparation for release. 2011-09-25 23:31:21 -04:00
Wizjany 3441ae11f2 Added legacy console sender (à la CommandBook). 2011-09-25 22:27:21 -04:00
Wizjany c028331ef9 Added config option and flag to prevent spread of grass. 2011-09-24 22:51:36 -04:00
Wizjany 9343c300cd Added command to flush state manager in case of emergency. 2011-09-24 22:01:07 -04:00
zml2008 63693cc529 Updated for Bukkit changes 2011-09-24 15:57:41 -07:00
Wizjany e6de06aae8 Apply weather settings on world load. 2011-09-22 20:34:38 -04:00
Wizjany 89ce7312d1 Added config options to disable xp drops (even though they should no longer lag) and death messages. 2011-09-21 16:48:56 -04:00
Wizjany b884787377 Fixed 1.8 chests not being blocked and future-proofed some other things. 2011-09-21 15:29:45 -04:00
Wizjany a1427e7743 - Added flags for hunger that do the same that the health ones do (but with hunger)
- Added a config option and a flag to prevent endermen from picking up or placing blocks."
2011-09-20 15:44:54 -04:00
Wizjany 0c02190e19 Added fence gates to USE flag. 2011-09-19 00:58:48 -04:00
zml2008 1f7cce9535 Added experience orbs to the intensive entities list 2011-09-16 20:02:46 -07:00
Wizjany 9fea677b60 Fixed being able to eat protected cake. 2011-09-16 19:18:08 -04:00
Wizjany 6b9a3aff58 Made priming TNT by punching it with flint and steel throw a block break blacklist event. 2011-08-27 16:00:42 -04:00
Wizjany b938271b4d Punching fire in a region without build permissions should no longer douse the fire. 2011-08-27 13:44:40 -04:00
Wizjany 297e06ba71 Fix infinite sign bug. 2011-08-26 22:35:28 -04:00
Wizjany a521ab76a5 Fixed interact and use blacklist events being grouped together incorrectly when right clicking a container. 2011-08-26 20:03:38 -04:00
Wizjany b1c8fc82c4 Fixed piston events being cancelled when they shouldn't be 2011-08-25 18:48:17 -04:00
Wizjany d4ba90c21d Sort /region info player list alphabetically. 2011-08-24 23:48:09 -04:00
Wizjany 14dc868d45 Fixed polygon region edges being unprotected on certain edges. Thanks Droolio. 2011-08-24 17:50:25 -04:00
Wizjany 61a60ecdd6 Fallback to the global region for flags other than StateFlags. Thanks imjake9. 2011-08-24 17:40:01 -04:00
Wizjany 2b56247e21 Allow '/region info' for existing but now illegally-named regions. Thanks Moo0. 2011-08-20 02:22:45 -04:00
Wizjany e0066e6173 Disallowed overwriting regions without specifying redefine. 2011-08-20 02:17:39 -04:00
Wizjany b5b92f91dc Added flag for pistons and fixed a typo in config. 2011-08-20 01:58:46 -04:00
Wizjany 7b12510182 Made sleep flag proactive enough to keep them from blowing the nether up. 2011-08-16 19:24:13 -04:00
TomyLobo e2fc6a3ff0 Fixed heal/damage regions being shifted by half a block towards northeast. 2011-08-15 10:13:39 +02:00
TomyLobo 5acd3a7f6c Fixed warnings. 2011-08-15 09:08:33 +02:00
EduardBaer ce49ca0998 Fix BlockInteractBlacklistEvent 2011-08-11 22:52:20 -04:00
Wizjany eacce487ed Ignore NPE onCreatureSpawn and attempt to get more information about it instead. 2011-08-11 22:52:19 -04:00
Wizjany 602b1d8a27 Bugfixes. Allowed/blocked commands should now respect global flags. Region invincibility/godmode compatibility should now work instead of throwing NPEs. 2011-08-11 22:05:31 -04:00
Wizjany dec469caef Added worldguard.region.flag.regions permissions and flags.<flag>.own for consistency. The old ones will probably be deprecated at some point. Also cleaned up /wg report output slightly. 2011-08-10 20:16:05 -04:00
Wizjany 4194b2ca86 Added the option to disable the use of player move events. Note that this also disables features which use it such as the region entry/exit and greeting/farewell flags. 2011-08-10 20:16:05 -04:00
Wizjany 17741822c1 Allow invincibility flag to disable god mode (when set to deny) unless the player has the worldguard.god.override-regions permission. 2011-08-10 17:43:46 -04:00
Wizjany 3757056e46 Fixed up explosion handling. 2011-08-09 21:02:26 -04:00
Wizjany 0eb68ef864 Added min and max health flags to go along with the other healing flags. Also organized the flag list for readability. 2011-08-09 19:48:10 -04:00
Wizjany 3f77a9b721 Made /stack respect max stack sizes unless the user has worldguard.stack.illegitimate which will stack normally unstackable items. 2011-08-08 12:46:18 -04:00
Wizjany 321b3acf0a Buckets now check the region that the water will end up in, not the block that was clicked 2011-08-08 09:12:10 -04:00
Wizjany dfbbeeb473 Moved around projectile damage events in accordance to Bukkit 2011-08-07 18:42:32 -04:00
Wizjany 31d3f2e7c6 Cancel scheduled tasks on disable 2011-08-07 17:08:18 -04:00
Wizjany 40a66b9be4 Updated snow fall and added flags for snow/ice forming/melting and mushroom growth 2011-08-06 11:29:14 -04:00
sk89q 049a1fb2ed Merge pull request #134 from halvors/cleanup
Cleanup, commented out some unused fields.
2011-07-17 10:50:36 -07:00
halvors 3fc68af05f More imports cleanup. 2011-07-16 23:07:29 +02:00
halvors c3f0c8a7a1 Oops, missed some changes. 2011-07-16 22:39:30 +02:00
halvors cba1a95838 Cleanup, commented out some unused fields. 2011-07-16 22:26:10 +02:00
sk89q 345f4a2e0e Removed some debugging messages. 2011-06-29 17:00:58 -07:00
sk89q 162d53b66e Made TNT blocking more aggressive. Also fixed explosion event. 2011-06-29 16:59:31 -07:00
sk89q bed6782a00 Made /stoplag handle TNT removal better. 2011-06-29 16:17:36 -07:00
Wizjany d90b960597 Moved fireball handling to somewhere that actually gets called by it... 2011-06-29 15:43:01 -04:00
Wizjany 3325feb1cb Re-enable god mode on a reload for those who need it. 2011-06-28 01:05:51 -04:00
Wizjany 62d181eb81 Made it easier for plugins to access the API without using WorldEdit vectors 2011-06-28 00:59:16 -04:00
Wizjany 1e24e9c128 Added config option to block fireball world damage only. Thanks Qalthos 2011-06-28 00:58:13 -04:00
sk89q cfffba25cf Added regions.invincibility-removes-mobs so you can turn on invincibility without creating the possibility about farming. 2011-06-27 13:41:27 -07:00
sk89q 671b4fe2db Added region invincibility flag. 2011-06-27 13:36:43 -07:00
sk89q 5b300bc5d1 Changed the per-world configuration loader to also put configuration entries in the main configuration. 2011-06-27 13:13:31 -07:00
sk89q a5332c2166 Added player-damage.disable-tnt-damage. 2011-06-27 12:57:33 -07:00
sk89q 141d5ccd25 [maven-release-plugin] prepare for next development iteration 2011-06-27 12:09:57 -07:00
108 changed files with 6968 additions and 4580 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
*.java diff=java
+6
View File
@@ -0,0 +1,6 @@
.classpath
.project
.settings
target
.DS_Store
+138
View File
@@ -1,3 +1,141 @@
5.5.3:
- Added game mode flag.
- Added item drop pickup flag to regions.
- Added support for fireball item blocking (385).
- Added configuration option to allow creature spawns from plugins.
- Added host key check.
- Added a new line split feature to region greetings.
- Prevented commands in the allow commands list from being blocked and
vice versa.
5.5.2:
- Added potion-splash flag to block splash potions
- Add entity-painting-destroy which can be used to prevent entities from destroying paintings (skeletons firing arrows)
- Added send-chat and receive-chat flags
- Fixed having regions in multiple worlds with the same name not working with MySQL
- A cancellable event is now fired if WorldGuard disallows PvP. (for developers!)
- Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
- Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
- Fixed an error that occured when clearing a non-existant region's parent.
- Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region.
- Added region/role-based permissions to /region teleport.
- BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
- /region info -s now selects the region being queried.
- Added /region teleport <id>.
- Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z.
- Made /region info show the region you're in if you don't specify an id explicitly.
- Prevent block ignition from lightning strikes if lightning is blocked in region. Fixes #1175
- Correctly check both WEPIF and superperms in WorldGurdPlugin.broadcastNotification()
- Destroy fire blocks when fire-spread is disallowed
- Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles.
- Added FallingSand to list of intensive entities to be removed with /halt-activiy.
- Replaced all usage of CreatureType by EntityType.
- Updated to support Bukkit 1.2-R0.3 and newer
- Made auto-god-mode disabled by default again.
- Added sign protection check disable.
- Cleaned up javadoc, deprecated duplicate methods, other cleanup
- Added a RegionGroupFlag to evey region flag Using the /region flag command with -g, the region group that the region flag applies to can be set.
5.5.1:
- Fixed attacking with arrows from non-PVP to PVP areas
- Compatibility with Bukkit 1.1-R5
- Removed broken suppress-tick-sync-warnings config option. See bukkit.yml's setings.warn-on-overload option instead.
- Add region and 'can build' information to CommandBook's /whois
Contributions thanks to: NolanSyKinsley
5.5:
- Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
- Now using Bukkit's tagged logging
- Updated to new event system
- Flush player flag state cache on world change
- Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0
- Added MySQL region storage method.
- Made explosions display their animations even when the event was blocked.
- Added fallback support for those who don't have a version of CommandBook with GodComponent
- Added LIGHTNING flag to DefaultFlag's flagsList Fixes #1026
- Removed /god, /heal, /locate, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded.
- Removed remaining usages of org.bukkit.util.config.Configuration
- Removed some unused configuration options
- Added permission worldguard.region.wand to the region wand
- Fixed ProtectedRegion.compareTo.
- Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
- Added exp-drops flag to disable experience drops per-region.
- Fixed some warnings.
- Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
- Added support for fireballs shot by players being blocked by the PVP flag.
- Now using dynamic command registration
- Split off ender dragon block damage from creeper block damage.
Contributions thanks to: narthollis, DarkArc, Wolvereness, and skeight
5.4:
- Fixed configuration generation on Windows
- Fixed intersection calculation for regions
- Fixed timer and feeding delay for food flags
- Fixed region managers not being created properly (This caused errors related to CREATURE_SPAWN)
- Added support for Minecraft 1.0.1 blocks
- Added support for enchantments and tool damage (worldguard.stack.damaged is the node) with /stack
- Made being in the wg-invincible group respect the configuration's auto-invincible setting
- Added per-group region claim limit maximum
- Added worldguard.region.addowner.unclaimed.* permission for non-economy region 'buying'
- Checking allowed/blocked commands now occurs earlier to override more plugins
- Made PVP flag check whether either player is in a pvp deny region for blocking
Contributions thanks to: epuidokas, wizjany, Turtle9598, and DerFlash
5.3:
- Added new config options and flags to better handle explosions of all types
- Added config options and flags for snow, ice, mushroom spread, grass spread,
and leaf decay
- Added min and max health flags to clamp the values for the existing healing
flags
- Added hunger flags similar to the existing healing flags
- Added an option to disable the use of the move event. This can boost
performance on large servers but will disable the greeting/farewell
and entry/exit flags
- Added flag to prevent pistons (including those that are outside the
region, but would affect blocks inside the region)
- Added a /wg flushstates [player] command to free players stuck in a
region that was exit-deny but no longer exists or the flag was removed
- Added a config option to disable xp orb dropping
- Added config option to disable redstone wire obsidian generators
- Added a vehicle-destroy flag
- Added enderman protection config and flag
- Allowed and blocked command flags will now fall back to the global region
- The worldguard.region.flag.own/member permissions are now
worldguard.region.flag.regions.own/member! Please change your permissions
accordingly.
- Made //stack respect max stack sizes unless the player has the
worldguard.stack.illegitimate permission
- Setting invincibility flag to deny will override god mode unless the player
has worldguard.god.override-regions
- The sleep flag will now prevent beds in the nether from
exploding if set to deny
- Existing regions can no longer be accidentally overwritten.
Use /region redefine to move an existing region.
- The info command will now sort players alphabetically
- Priming TNT by punching it with flint and steal should throw a blacklist
event (consistent with old Minecraft versions)
- The /stoplag command will now remove xp orbs
- Permissions system will use per-world permissions if the provider supports it
- Players in vehicles are now subject to entry/exit and greeting/farewell flags
- Fixed interact blacklist event not logging correctly
- Fixed heal flag taking effect half a block northeast of the region
- Fixed a infinite sign dropping bug
- Fixed players being able to douse fire by punching it in regions they
couldn't build it
- Fixed players being able to eat protected cake
- Fence gate usage can be blocked with the use flag
- Fixed chests being unprotected when they should be in 1.8
- Fixed weather config settings not applying when a world was loaded
- Fixed explosion handling in certain cases
- Fixed arrows working in non-pvp zones
- Fixed buckets working on the border of protected regions in certain cases
Contributions thanks to:
wizjany, zml2008, imjake9, Droolio, epuidokas,
EduardBaer, TomyLobo, and halvors
5.2.2:
- Changed configuration saving so empty lists will be added to
the configuration files.
+209 -186
View File
@@ -1,186 +1,209 @@
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
CommandBook is available under the GNU General Public License v3
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.2.2</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<repositories>
<!-- Repository for other dependencies of SK's -->
<repository>
<id>sk89q-mvn2</id>
<url>http://mvn2.sk89q.com/repo</url>
</repository>
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/artifactory/repo</url>
</repository>
</repositories>
<dependencies>
<!-- Required component -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>4.4.2</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldEdit.jar WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
<!-- TODO: Get Doclava working -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
WorldGuard is available under the GNU General Public License v3
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.5.3</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<repositories>
<!-- Repository for zml's stuff -->
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<!-- Repository for other dependencies of SK's -->
<repository>
<id>sk89q-mvn2</id>
<url>http://mvn2.sk89q.com/repo</url>
</repository>
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<!-- Required component -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4-SNAPSHOT</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.2.5-R4.0</version>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
<!-- TODO: Get Doclava working -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
+217
View File
@@ -0,0 +1,217 @@
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
-- -----------------------------------------------------
-- Table `group`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `group` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `world`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `world` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 9
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region` (
`id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`type` ENUM('cuboid','poly2d','global') CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`priority` SMALLINT(6) NOT NULL DEFAULT '0' ,
`parent` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NULL DEFAULT NULL ,
PRIMARY KEY (`id`, `world_id`) ,
INDEX `fk_region_world` (`world_id` ASC) ,
INDEX `parent` (`parent` ASC) ,
CONSTRAINT `fk_region_world1`
FOREIGN KEY (`world_id` )
REFERENCES `world` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `parent`
FOREIGN KEY (`parent` )
REFERENCES `region` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_cuboid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_cuboid` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`min_x` BIGINT(20) NOT NULL ,
`min_y` BIGINT(20) NOT NULL ,
`min_z` BIGINT(20) NOT NULL ,
`max_x` BIGINT(20) NOT NULL ,
`max_y` BIGINT(20) NOT NULL ,
`max_z` BIGINT(20) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`) ,
INDEX `fk_region_cuboid_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_flag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_flag` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`flag` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`value` VARCHAR(256) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_flags_region` (`region_id` ASC, `world_id` ASC) ,
CONSTRAINT `fk_flags_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
AUTO_INCREMENT = 3246
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_groups` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`group_id` INT(10) UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`, `group_id`) ,
INDEX `fk_region_groups_region` (`region_id` ASC) ,
INDEX `fk_region_groups_group` (`group_id` ASC) ,
CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 82
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_players`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_players` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`user_id` INT(10) UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`, `user_id`) ,
INDEX `fk_region_players_region` (`region_id` ASC) ,
INDEX `fk_region_users_user` (`user_id` ASC) ,
CONSTRAINT `fk_region_users_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_users_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_poly2d`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`min_y` INT(11) NOT NULL ,
`max_y` INT(11) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`) ,
INDEX `fk_region_poly2d_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_poly2d_point`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d_point` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`x` BIGINT(20) NOT NULL ,
`z` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC, `world_id` ASC) ,
CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region_poly2d` (`region_id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
AUTO_INCREMENT = 15
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+106
View File
@@ -0,0 +1,106 @@
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
ALTER TABLE `region_cuboid` DROP FOREIGN KEY `fk_region_cuboid_region` ;
ALTER TABLE `region_flag` DROP FOREIGN KEY `fk_flags_region1` ;
ALTER TABLE `region_groups` DROP FOREIGN KEY `fk_region_groups_region` ;
ALTER TABLE `region_players` DROP FOREIGN KEY `fk_region_players_user` , DROP FOREIGN KEY `fk_region_players_region` ;
ALTER TABLE `region_poly2d` DROP FOREIGN KEY `fk_region_poly2d_region` ;
ALTER TABLE `region_poly2d_point` DROP FOREIGN KEY `fk_region_poly2d_point_region_poly2d` ;
ALTER TABLE `group` COLLATE = utf8_bin ;
ALTER TABLE `region_cuboid` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `min_x` `min_x` BIGINT(20) NOT NULL AFTER `world_id` , CHANGE COLUMN `min_y` `min_y` BIGINT(20) NOT NULL AFTER `min_x` , CHANGE COLUMN `max_x` `max_x` BIGINT(20) NOT NULL AFTER `min_z` , CHANGE COLUMN `max_y` `max_y` BIGINT(20) NOT NULL AFTER `max_x` ,
ADD CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`) ;
ALTER TABLE `region_flag` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `flag` `flag` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
ADD CONSTRAINT `fk_flags_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP INDEX `fk_flags_region`
, ADD INDEX `fk_flags_region` (`region_id` ASC, `world_id` ASC) ;
ALTER TABLE `region_groups` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , DROP FOREIGN KEY `fk_region_groups_group` ;
ALTER TABLE `region_groups`
ADD CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`, `group_id`) ;
ALTER TABLE `region_players` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` ,
ADD CONSTRAINT `fk_region_users_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT `fk_region_users_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`, `user_id`)
, ADD INDEX `fk_region_users_user` (`user_id` ASC)
, DROP INDEX `fk_region_players_user` ;
ALTER TABLE `region_poly2d` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `min_y` `min_y` INT(11) NOT NULL AFTER `world_id` ,
ADD CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`) ;
ALTER TABLE `region_poly2d_point` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `x` `x` BIGINT(20) NOT NULL AFTER `world_id` ,
ADD CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region_poly2d` (`region_id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP INDEX `fk_region_poly2d_point_region_poly2d`
, ADD INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC, `world_id` ASC) ;
ALTER TABLE `user` COLLATE = utf8_bin ;
ALTER TABLE `world` COLLATE = utf8_bin ;
UPDATE `region_cuboid` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_flag` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_groups` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_players` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_poly2d` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_poly2d_point` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+2 -1
View File
@@ -3,7 +3,6 @@
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>default</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
@@ -28,7 +27,9 @@
<includes>
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>blacklist_table.sql</include>
<include>region_storage.sql</include>
</includes>
</fileSet>
</fileSets>
@@ -25,58 +25,58 @@ public abstract class LocalPlayer {
/**
* Get a player's name.
*
* @return
* @return The player's name
*/
public abstract String getName();
/**
* Returns true if the player is inside a group.
*
* @param group
* @return
* @param group The group to check
* @return Whether this player is in {@code group}
*/
public abstract boolean hasGroup(String group);
/**
* Get the player's position.
*
* @return
* @return The player's position
*/
public abstract Vector getPosition();
/**
* Kick the player.
*
* @param msg
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban the player.
*
* @param msg
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
/**
* Send the player a message;
*
* @param msg
* @param msg The message to send to the player
*/
public abstract void printRaw(String msg);
/**
* Get the player's list of groups.
*
* @return
* @return The groups this player is in
*/
public abstract String[] getGroups();
/**
* Returns whether a player has permission.
*
* @param perm
* @return
* @param perm The permission to check
* @return Whether this player has {@code perm}
*/
public abstract boolean hasPermission(String perm);
@@ -19,14 +19,19 @@
package com.sk89q.worldguard.blacklist;
import java.util.Map;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.Map;
import java.util.logging.Level;
import java.io.*;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
@@ -36,11 +41,7 @@ import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
* @author sk89q
*/
public abstract class Blacklist {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* List of entries by block ID.
*/
@@ -60,18 +61,19 @@ public abstract class Blacklist {
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
private boolean useAsWhitelist;
public Blacklist(Boolean useAsWhitelist)
{
private final Logger logger;
public Blacklist(Boolean useAsWhitelist, Logger logger) {
this.useAsWhitelist = useAsWhitelist;
this.logger = logger;
}
/**
* Returns whether the list is empty.
*
* @return
*
* @return whether the blacklist is empty
*/
public boolean isEmpty() {
return blacklist.isEmpty();
@@ -79,36 +81,36 @@ public abstract class Blacklist {
/**
* Get the entries for an item or list.
*
* @param id
* @return
*
* @param id The item id to get blacklist information for
* @return The blacklist entries for {@code id}
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
}
/**
* Get the number of individual items that have blacklist entries.
*
* @return
*
* @return The number of items in the blacklist
*/
public int getItemCount() {
return blacklist.size();
}
/**
* Returns whether the blacklist is used as a whitelist.
*
* @return
*
* @return whether the blacklist is be used as a whitelist
*/
public boolean isWhitelist() {
return useAsWhitelist;
}
/**
* Get the logger.
*
* @return
*
* @return The logger used in this blacklist
*/
public BlacklistLogger getLogger() {
return blacklistLogger;
@@ -116,11 +118,11 @@ public abstract class Blacklist {
/**
* Method to handle the event.
*
* @param event
* @param forceRepeat
* @param silent
* @return
*
* @param event The event to check
* @param forceRepeat Whether to force quickly repeating notifications
* @param silent Whether to force-deny notifications
* @return Whether the event is allowed
*/
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
List<BlacklistEntry> entries = getEntries(event.getType());
@@ -139,8 +141,8 @@ public abstract class Blacklist {
/**
* Load the blacklist.
*
* @param file
* @throws IOException
* @param file The file to load from
* @throws IOException if an error occurred reading from the file
*/
public void load(File file) throws IOException {
FileReader input = null;
@@ -168,14 +170,14 @@ public abstract class Blacklist {
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
int id;
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
logger.log(Level.WARNING, "Unknown block name: "
+ item);
break;
}
@@ -246,48 +248,48 @@ public abstract class Blacklist {
if (input != null) {
input.close();
}
} catch (IOException e2) {
} catch (IOException ignore) {
}
}
}
/**
* Get the last event.
*
* @return
*
* @return The last event
*/
public BlacklistEvent getLastEvent() {
return lastEvent;
}
/**
* Notify administrators.
*
* @param event
* @param comment
*
* @param event The event to notify about
* @param comment The comment to notify with
*/
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
broadcastNotification(ChatColor.GRAY + "WG: "
broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + event.getPlayer().getName()
+ ChatColor.GOLD + " (" + event.getDescription() + ") "
+ ChatColor.WHITE
+ getFriendlyItemName(event.getType())
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
/**
* Sends a notification to all subscribing users.
*
* @param msg
*
* @param msg The message to broadcast
*/
public abstract void broadcastNotification(String msg);
/**
* Forget a player.
*
* @param player
* @param player The player to forget
*/
public void forgetPlayer(LocalPlayer player) {
lastAffected.remove(player.getName());
@@ -302,8 +304,9 @@ public abstract class Blacklist {
/**
* Get an item's ID from its name.
*
* @param name
*
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
@@ -316,8 +319,9 @@ public abstract class Blacklist {
/**
* Get an item's friendly name with its ID.
*
* @param id
*
* @param id The id to look up
* @return The item's friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -19,9 +19,11 @@
package com.sk89q.worldguard.blacklist;
import java.util.Set;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
@@ -52,7 +54,7 @@ public class BlacklistEntry {
* List of permissions to not affect.
*/
private Set<String> ignorePermissions;
private String[] breakActions;
private String[] destroyWithActions;
private String[] placeActions;
@@ -60,14 +62,14 @@ public class BlacklistEntry {
private String[] useActions;
private String[] dropActions;
private String[] acquireActions;
private String message;
private String comment;
/**
* Construct the object.
*
* @param blacklist
*
* @param blacklist The blacklist that contains this entry
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
@@ -110,98 +112,98 @@ public class BlacklistEntry {
}
/**
* @return
* @return The actions that occur when breaking
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions
* @param actions The actions to occur when breaking
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return
* @return The actions that occur when destroying with a specific item
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param actions
* @param actions The actions to occur when destroying with an item
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return
* @return The actions that will occur when placing
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions
* @param actions The actions to occur when placing
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return
* @return The actions that will occur when interacting
*/
public String[] getInteractActions() {
return interactActions;
}
/**
* @param actions
* @param actions The actions to occur when interacting
*/
public void setInteractActions(String[] actions) {
this.interactActions = actions;
}
/**
* @return
* @return The actions that will occur when using
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions
* @param actions The actions to occur when using
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return
* @return The actions that will occur when dropping
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions
* @param actions The actions to occur when dropping
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return
* @return The actions that will occur when acquiring
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions
* @param actions The actions to occur when acquiring
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
@@ -238,8 +240,8 @@ public class BlacklistEntry {
/**
* Returns true if this player should be ignored.
*
* @param player
* @return
* @param player The player to check
* @return whether this player should be ignored for blacklist blocking
*/
public boolean shouldIgnore(LocalPlayer player) {
if (ignoreGroups != null) {
@@ -260,35 +262,35 @@ public class BlacklistEntry {
return false;
}
/**
* Get the associated actions with an event.
*
* @param event
* @return
*
* @param event The event to check
* @return The actions for the given event
*/
private String[] getActions(BlacklistEvent event) {
if (event instanceof BlockBreakBlacklistEvent) {
return breakActions;
} else if (event instanceof BlockPlaceBlacklistEvent) {
return placeActions;
} else if (event instanceof BlockInteractBlacklistEvent) {
return interactActions;
} else if (event instanceof DestroyWithBlacklistEvent) {
return destroyWithActions;
} else if (event instanceof ItemAcquireBlacklistEvent) {
return acquireActions;
} else if (event instanceof ItemDropBlacklistEvent) {
return dropActions;
} else if (event instanceof ItemUseBlacklistEvent) {
return useActions;
} else {
return null;
}
@@ -296,16 +298,16 @@ public class BlacklistEntry {
/**
* Method to handle the event.
*
* @param useAsWhitelist
* @param event
* @param forceRepeat
* @param silent
* @return
*
* @param useAsWhitelist Whether this entry is buing used in a whitelist
* @param event The event to check
* @param forceRepeat Whether to force repeating notifications even within the delay limit
* @param silent Whether to prevent notifications from happening
* @return Whether the action was allowed
*/
public boolean check(boolean useAsWhitelist, BlacklistEvent event, boolean forceRepeat, boolean silent) {
LocalPlayer player = event.getPlayer();
if (shouldIgnore(player)) {
return true;
}
@@ -326,21 +328,21 @@ public class BlacklistEntry {
String actions[] = getActions(event);
boolean ret = useAsWhitelist ? false : true;
boolean ret = !useAsWhitelist;
// Nothing to do
if (actions == null) {
return useAsWhitelist ? false : true;
return ret;
}
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Allow
@@ -356,7 +358,7 @@ public class BlacklistEntry {
if (silent) {
continue;
}
if (this.message != null) {
player.kick(String.format(this.message,
getFriendlyItemName(event.getType())));
@@ -370,7 +372,7 @@ public class BlacklistEntry {
if (silent) {
continue;
}
if (this.message != null) {
player.ban("Banned: " + String.format(this.message,
getFriendlyItemName(event.getType())));
@@ -379,12 +381,12 @@ public class BlacklistEntry {
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
} else if (!silent && (!repeating || forceRepeat)) {
// Notify
if (action.equalsIgnoreCase("notify")) {
blacklist.notify(event, comment);
// Log
} else if (action.equalsIgnoreCase("log")) {
blacklist.getLogger().logEvent(event, comment);
@@ -409,8 +411,8 @@ public class BlacklistEntry {
/**
* Get an item's friendly name with its ID.
*
* @param id
*
* @param id The id to get a name for
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -19,8 +19,9 @@
package com.sk89q.worldguard.blacklist;
import java.util.Set;
import java.util.HashSet;
import java.util.Set;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.loggers.BlacklistLoggerHandler;
@@ -38,16 +39,16 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Add a handler.
*
* @param handler
* @param handler The handler to add
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Add a handler.
* Remove a handler.
*
* @param handler
* @param handler The handler to remove
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
@@ -59,11 +60,11 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
public void clearHandlers() {
handlers.clear();
}
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
@@ -31,9 +31,9 @@ public class BlacklistTrackedEvent {
/**
* Construct the object.
*
* @param event
* @param time
*
* @param event The event tracked
* @param time The time at which the event occurred
*/
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
@@ -39,9 +39,9 @@ public abstract class BlacklistEvent {
/**
* Construct the object.
*
* @param player
* @param pos
* @param type
* @param player The player associated with this event
* @param pos The position the event occurred at
* @param type The type of item used
*/
public BlacklistEvent(LocalPlayer player, Vector pos, int type) {
this.player = player;
@@ -51,8 +51,8 @@ public abstract class BlacklistEvent {
/**
* Get the player.
*
* @return
*
* @return The player associated with this event
*/
public LocalPlayer getPlayer() {
return player;
@@ -61,16 +61,16 @@ public abstract class BlacklistEvent {
/**
* Get the position.
*
* @return
* @return The position of this event
*/
public Vector getPosition() {
return pos;
}
/**
* Get the type.
* Get the item type.
*
* @return
* @return The type associated with this event
*/
public int getType() {
return type;
@@ -79,7 +79,7 @@ public abstract class BlacklistEvent {
/**
* Get a short description such as "break" or "destroy with."
*
* @return
* @return The event description
*/
public abstract String getDescription();
}
@@ -26,12 +26,7 @@ public class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
public BlockBreakBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "break";
@@ -26,12 +26,7 @@ public class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
public BlockInteractBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "interact with";
@@ -26,12 +26,7 @@ public class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
public BlockPlaceBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "place";
@@ -26,12 +26,7 @@ public class DestroyWithBlacklistEvent extends BlacklistEvent {
public DestroyWithBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "destroy with";
@@ -26,12 +26,7 @@ public class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
public ItemAcquireBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "acquire";
@@ -26,12 +26,7 @@ public class ItemDropBlacklistEvent extends ItemBlacklistEvent {
public ItemDropBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "drop";
@@ -26,12 +26,7 @@ public class ItemUseBlacklistEvent extends ItemBlacklistEvent {
public ItemUseBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "use";
@@ -34,7 +34,7 @@ public interface BlacklistLoggerHandler {
* @param comment
*/
public void logEvent(BlacklistEvent event, String comment);
/**
* Close the logger.
*/
@@ -19,102 +19,104 @@
package com.sk89q.worldguard.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private String worldName;
public ConsoleLoggerHandler(String worldName)
{
this.worldName = worldName;
private final Logger logger;
public ConsoleLoggerHandler(String worldName, Logger logger) {
this.worldName = worldName;
this.logger = logger;
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
return "#" + id;
}
}
@@ -19,17 +19,19 @@
package com.sk89q.worldguard.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
@@ -40,58 +42,58 @@ import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* DSN.
*/
private String dsn;
private final String dsn;
/**
* Username.
*/
private String user;
private final String user;
/**
* Password.
*/
private String pass;
private final String pass;
/**
* Table.
*/
private String table;
private final String table;
/**
* World name.
*/
private String worldName;
private final String worldName;
/**
* Database connection.
*/
private Connection conn;
private final Logger logger;
/**
* Construct the object.
*
* @param dsn
* @param user
* @param pass
* @param table
* @param worldName
*
* @param dsn The DSN for the connection
* @param user The username to connect with
* @param pass The password to connect with
* @param table The table to log to
* @param worldName The name of the world to log
* @param logger The logger to log errors to
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName) {
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
this.logger = logger;
}
/**
* Gets the database connection.
*
* @return
* @throws SQLException
*
* @return The database connection
* @throws SQLException when the connection cannot be created
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
@@ -102,14 +104,12 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event to the database.
*
* @param event
* @param name
* @param x
* @param y
* @param z
* @param item
* @param comment
*
* @param event The event to log
* @param player The player associated with the event
* @param pos The location of the event
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(String event, LocalPlayer player, Vector pos, int item,
String comment) {
@@ -134,11 +134,11 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
+ e.getMessage());
}
}
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
@@ -146,43 +146,43 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent("BREAK", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent("PLACE", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block interact
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent("INTERACT", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent("DESTROY_WITH", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent("ACQUIRE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent("DROP", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent("USE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Unknown
} else {
logEvent("UNKNOWN", event.getPlayer(), event.getPlayer().getPosition(),
@@ -198,8 +198,8 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
} catch (SQLException ignore) {
}
}
}
@@ -19,26 +19,32 @@
package com.sk89q.worldguard.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.*;
import java.util.regex.*;
import java.util.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Regex for patterns in the path.
*/
@@ -66,38 +72,45 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
*/
private TreeMap<String,FileLoggerWriter> writers =
new TreeMap<String,FileLoggerWriter>();
private final Logger logger;
/**
* Construct the object.
*
* @param pathPattern
* @param worldName
* @param pathPattern The pattern for the logflie path
* @param worldName The name of the world
* @param logger The logger used to log errors
*/
public FileLoggerHandler(String pathPattern, String worldName) {
public FileLoggerHandler(String pathPattern, String worldName, Logger logger) {
this.pathPattern = pathPattern;
this.worldName = worldName;
this.logger = logger;
}
/**
* Construct the object.
*
* @param pathPattern
* @param cacheSize
* @param worldName
* @param pathPattern The pattern for logfile paths
* @param cacheSize The size of the file cache
* @param worldName The name of the associated world
* @param logger The logger to log errors with
*/
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName) {
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
this.pathPattern = pathPattern;
this.cacheSize = cacheSize;
this.worldName = worldName;
this.logger = logger;
}
/**
* Build the path.
*
* @return
*
* @param playerName The name of the playername
* @return The path for the logfile
*/
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
@@ -142,20 +155,21 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
} else if (group.matches("%s")) {
rep = String.format("%02d", calendar.get(Calendar.SECOND));
}
m.appendReplacement(buffer, rep);
}
m.appendTail(buffer);
return buffer.toString();
}
/**
* Log a message.
*
* @param player
* @param message
*
* @param player The player to log
* @param message The message to log
* @param comment The comment associated with the logged event
*/
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
@@ -163,7 +177,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
String date = dateFormat.format(new Date());
String line = "[" + date + "] " + player.getName() + ": " + message
+ (comment != null ? " (" + comment + ")" : "") + "\r\n";
FileLoggerWriter writer = writers.get(path);
// Writer already exists!
@@ -185,7 +199,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
FileWriter stream = new FileWriter(path, true);
BufferedWriter out = new BufferedWriter(stream);
out.write(line);
@@ -203,7 +217,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
Map.Entry<String,FileLoggerWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
it.remove();
@@ -222,71 +236,33 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Gets the coordinates in text form for the log.
*
* @param pos
* @return
*
* @param pos The position to get coordinates for
* @return The position's coordinates in human-readable form
*/
private String getCoordinates(Vector pos) {
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
private void logEvent(BlacklistEvent event, String text, int id, Vector pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + getFriendlyItemName(id)
+ " " + getCoordinates(pos), comment);
}
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent(event, "break", evt.getType(), evt.getPosition(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent(event, "place", evt.getType(), evt.getPosition(), comment);
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent(event, "interact with", evt.getType(), evt.getPosition(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent(event, "destroy with", evt.getType(), evt.getPosition(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent(event, "acquire", evt.getType(), evt.getPosition(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent(event, "drop", evt.getType(), evt.getPosition(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent(event, "use", evt.getType(), evt.getPosition(), comment);
// Unknown
} else {
log(event.getPlayer(), "Unknown event: "
+ event.getClass().getCanonicalName(), comment);
}
logEvent(event, event.getDescription(), event.getType(), event.getPosition(), comment);
}
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The id to get a friendly name for
* @return The friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -304,7 +280,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
for (Map.Entry<String,FileLoggerWriter> entry : writers.entrySet()) {
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
@@ -19,7 +19,7 @@
package com.sk89q.worldguard.blacklist.loggers;
import java.io.*;
import java.io.BufferedWriter;
/**
*
@@ -41,9 +41,9 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Construct the object.
*
* @param path
* @param writer
*
* @param path The path to write to
* @param writer The writer for the file
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
this.path = path;
@@ -53,15 +53,15 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* File path.
*
* @return
*
* @return The path the logger is logging to
*/
public String getPath() {
return path;
}
/**
* @return the writer
* @return the writer being logged to
*/
public BufferedWriter getWriter() {
return writer;
@@ -73,7 +73,7 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
public long getLastUse() {
return lastUse;
}
/**
* Update last use time.
*/
@@ -81,12 +81,6 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
lastUse = System.currentTimeMillis();
}
/**
* Comparison function.
*
* @param other
* @return
*/
public int compareTo(FileLoggerWriter other) {
if (lastUse > other.lastUse) {
return 1;
@@ -25,7 +25,7 @@ public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist);
super(useAsWhitelist, plugin.getLogger());
this.plugin = plugin;
}
@@ -33,5 +33,4 @@ public class BukkitBlacklist extends Blacklist {
public void broadcastNotification(String msg) {
plugin.broadcastNotification(msg);
}
}
@@ -21,6 +21,7 @@ package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
@@ -56,6 +57,7 @@ public class BukkitPlayer extends LocalPlayer {
@Override
public void ban(String msg) {
player.setBanned(true);
player.kickPlayer(msg);
}
@@ -73,5 +75,4 @@ public class BukkitPlayer extends LocalPlayer {
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
}
@@ -21,45 +21,59 @@ package com.sk89q.worldguard.bukkit;
import java.util.List;
import com.sk89q.worldedit.blocks.BlockType;
import org.bukkit.*;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.FallingSand;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
public class BukkitUtil {
private BukkitUtil() {
}
/**
* Converts the location of a Bukkit block to a WorldEdit vector.
*
* @param block
* @return
*
* @param block The block to convert
* @return The block's location as a BlockVector
*/
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
/**
* Converts a Bukkit location to a WorldEdit vector.
*
* @param loc
* @return
*
* @param loc A Bukkit Location
* @return A Vector with the location's x, y, and z values
*/
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
/**
* Converts a Bukkit vector to a WorldEdit vector.
*
* @param vector
* @return
*
* @param vector The Bukkit vector
* @return A WorldEdit vector with the same values as the Bukkit vector.
*/
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
@@ -67,22 +81,24 @@ public class BukkitUtil {
/**
* Converts a WorldEdit vector to a Bukkit location.
*
* @param world
* @param vec
* @return
*
* @param world The World to create the new Location with
* @param vec The vector to use for coordinates
* @return The Vector as a location with a World of world
*/
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Matches one player based on name.
*
* @param server
* @param name
* @return
*
* @param server The server to check
* @param name The name to attempt to match
* @deprecated see {@link WorldGuardPlugin#matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @return The matched player if any, otherwise null
*/
@Deprecated
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
@@ -90,22 +106,24 @@ public class BukkitUtil {
}
return players.get(0);
}
/**
* Drops a sign item and removes a sign.
*
* @param block
*
* @param block The block
* @deprecated see {@link org.bukkit.block.Block#breakNaturally()}
*/
@Deprecated
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(Material.SIGN));
new ItemStack(ItemID.SIGN, 1));
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
*
* @param world
* @param ox
* @param oy
@@ -121,12 +139,12 @@ public class BukkitUtil {
/**
* Checks if the given block is water
*
*
* @param world
* @param ox
* @param oy
* @param oz
* @return
* @return
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
@@ -156,7 +174,7 @@ public class BukkitUtil {
byte free = 0;
while (y <= 129) {
while (y <= world.getMaxHeight() + 1) {
if (BlockType.canPassThrough(world.getBlockTypeIdAt(x, y, z))) {
free++;
} else {
@@ -168,7 +186,7 @@ public class BukkitUtil {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
if (y <= 2 && world.getBlockAt(x,0,z).getType() == Material.AIR) {
if (y <= 2 && world.getBlockAt(x,0,z).getTypeId() == BlockID.AIR) {
world.getBlockAt(x,0,z).setTypeId(20);
loc.setY(2);
}
@@ -219,4 +237,20 @@ public class BukkitUtil {
return str;
}
/**
* Returns whether an entity should be removed for the halt activity mode.
*
* @param entity
* @return
*/
public static boolean isIntensiveEntity(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingSand
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
}
@@ -18,32 +18,38 @@
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*
*
* @author sk89q
* @author Michael
*/
public class ConfigurationManager {
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace any setting in here for that world only.\r\n" +
"# file to allow you to replace most settings in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
@@ -63,31 +69,48 @@ public class ConfigurationManager {
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Holds configurations for different worlds.
*/
private Map<String, WorldConfiguration> worlds;
/**
* The global configuration for use when loading worlds
*/
private YAMLProcessor config;
/**
* List of people with god mode.
*/
@Deprecated
private Set<String> hasGodMode = new HashSet<String>();
/**
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
public boolean suppressTickSyncWarnings;
private boolean hasCommandBookGodMode = false;
public boolean useRegionsScheduler;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
public boolean useSqlDatabase = false;
public String sqlDsn;
public String sqlUsername;
public String sqlPassword;
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -97,32 +120,58 @@ public class ConfigurationManager {
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
WorldGuardPlugin.createDefaultConfiguration(
plugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
Configuration config = plugin.getConfiguration();
config.load();
suppressTickSyncWarnings = config.getBoolean(
"suppress-tick-sync-warnings", false);
config = new YAMLProcessor(new File(plugin.getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for global config: ");
e.printStackTrace();
}
config.removeProperty("suppress-tick-sync-warnings");
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
autoGodMode = config.getBoolean(
"auto-invincible-permission", false);
"auto-invincible", config.getBoolean("auto-invincible-permission", false));
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
hostKeys = new HashMap<String, String>();
Object hostKeysRaw = config.getProperty("host-keys");
if (hostKeysRaw == null || !(hostKeysRaw instanceof Map)) {
config.setProperty("host-keys", new HashMap<String, String>());
} else {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
hostKeys.put(key.toLowerCase(), value);
}
}
useSqlDatabase = config.getBoolean(
"regions.sql.use", false);
sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
sqlUsername = config.getString("regions.sql.username", "worldguard");
sqlPassword = config.getString("regions.sql.password", "worldguard");
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
config.save();
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
}
}
/**
@@ -134,16 +183,16 @@ public class ConfigurationManager {
/**
* Get the configuration for a world.
*
* @param world
* @return
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
public WorldConfiguration get(World world) {
String worldName = world.getName();
WorldConfiguration config = worlds.get(worldName);
if (config == null) {
config = new WorldConfiguration(plugin, worldName);
config = new WorldConfiguration(plugin, worldName, this.config);
worlds.put(worldName, config);
}
@@ -152,77 +201,101 @@ public class ConfigurationManager {
/**
* Forget a player.
*
* @param player
*
* @param player The player to forget about
*/
public void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
// The blacklist needs to forget players
Blacklist bl = entry.getValue().getBlacklist();
if (bl != null) {
bl.forgetPlayer(player);
}
}
hasGodMode.remove(player.getName());
hasAmphibious.remove(player.getName());
}
/**
* Enable god mode for a player.
*
* @param player
*
* @param player The player to enable god mode for.
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
/**
* Disable god mode for a player.
*
* @param player
*
* @param player The player to disable godmode for
*/
@Deprecated
public void disableGodMode(Player player) {
hasGodMode.remove(player.getName());
}
/**
* Check to see if god mode is enabled for a player.
*
* @param player
* @return
*
* @param player The player to check
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(Player player) {
if (hasCommandBookGodMode) {
GodComponent god = CommandBook.inst().getComponentManager().getComponent(GodComponent.class);
if (god != null) {
return god.hasGodMode(player);
}
}
return hasGodMode.contains(player.getName());
}
/**
* Enable amphibious mode for a player.
*
* @param player
*
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(Player player) {
hasAmphibious.add(player.getName());
}
/**
* Disable amphibious mode for a player.
*
* @param player
*
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(Player player) {
hasAmphibious.remove(player.getName());
}
/**
* Check to see if amphibious mode is enabled for a player.
*
* @param player
* @return
* Check to see if amphibious mode is enabled for a player.
*
* @param player The player to check
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
}
public void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
hasCommandBookGodMode = true;
return;
}
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -19,37 +19,41 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
/**
* This processes per-player state information and is also meant to be used
* as a scheduled task.
*
*
* @author sk89q
*/
public class FlagStateManager implements Runnable {
public static final int RUN_DELAY = 20;
private WorldGuardPlugin plugin;
private Map<String, PlayerFlagState> states;
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public FlagStateManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
states = new HashMap<String, PlayerFlagState>();
}
@@ -62,16 +66,16 @@ public class FlagStateManager implements Runnable {
for (Player player : players) {
WorldConfiguration worldConfig = config.get(player.getWorld());
if (!worldConfig.useRegions) {
continue;
}
PlayerFlagState state;
synchronized (this) {
state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
@@ -83,87 +87,150 @@ public class FlagStateManager implements Runnable {
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
processHeal(applicable, player, state);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
&& !(player.getGameMode() == GameMode.CREATIVE)) {
processHeal(applicable, player, state);
processFeed(applicable, player, state);
}
}
}
/**
* Process healing for a player.
*
* @param applicable
* @param player
* @param state
*
* @param applicable The set of applicable regions
* @param player The player to process healing flags on
* @param state The player's state
*/
private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (minHealth == null) minHealth = 0;
if (maxHealth == null) maxHealth = 20;
if (player.getHealth() >= 20 && healAmount > 0) {
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0 && healAmount > 0) {
player.setHealth(20);
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
player.setHealth(Math.min(20, Math.max(0, player.getHealth() + healAmount)));
// clamp health between minimum and maximum
player.setHealth(Math.min(maxHealth, Math.max(minHealth, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
/**
* Process restoring hunger for a player.
*
* @param applicable The set of applicable regions
* @param player The player to process hunger flags on
* @param state The player's state
*/
private void processFeed(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
long now = System.currentTimeMillis();
Integer feedAmount = applicable.getFlag(DefaultFlag.FEED_AMOUNT);
Integer feedDelay = applicable.getFlag(DefaultFlag.FEED_DELAY);
Integer minHunger = applicable.getFlag(DefaultFlag.MIN_FOOD);
Integer maxHunger = applicable.getFlag(DefaultFlag.MAX_FOOD);
if (feedAmount == null || feedDelay == null || feedAmount == 0 || feedDelay < 0) {
return;
}
if (minHunger == null) minHunger = 0;
if (maxHunger == null) maxHunger = 20;
if (player.getFoodLevel() >= maxHunger && feedAmount > 0) {
return;
}
if (feedDelay <= 0) {
player.setFoodLevel(feedAmount > 0 ? maxHunger : minHunger);
state.lastFeed = now;
} else if (now - state.lastFeed > feedDelay * 1000) {
// clamp health between minimum and maximum
player.setFoodLevel(Math.min(maxHunger, Math.max(minHunger, player.getFoodLevel() + feedAmount)));
state.lastFeed = now;
}
}
/**
* Forget a player.
*
* @param player
*
* @param player The player to forget
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
}
/**
* Get a player's flag state.
*
* @param player
* @return
* Forget all managed players. Use with caution.
*/
public synchronized void forgetAll() {
states.clear();
}
/**
* Get a player's flag state. A new state will be created if there is no existing
* state for the player.
*
* @param player The player to get a state for
* @return The {@code player}'s state
*/
public synchronized PlayerFlagState getState(Player player) {
PlayerFlagState state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
return state;
}
/**
* Keeps state per player.
*/
public static class PlayerFlagState {
public long lastHeal;
public long lastFeed;
public String lastGreeting;
public String lastFarewell;
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public GameMode lastGameMode;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
public int lastBlockZ;
}
/* Used to cache invincibility status */
public World lastInvincibleWorld;
public int lastInvincibleX;
public int lastInvincibleY;
public int lastInvincibleZ;
public boolean wasInvincible;
}
}
@@ -19,9 +19,16 @@
package com.sk89q.worldguard.bukkit;
import java.io.*;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.CSVDatabase;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -31,15 +38,11 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
* @author sk89q
*/
public class LegacyWorldGuardMigration {
/**
* Logger for messages.
*/
protected static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Port over the blacklist.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateBlacklist(WorldGuardPlugin plugin) {
World mainWorld = plugin.getServer().getWorlds().get(0);
@@ -50,7 +53,7 @@ public class LegacyWorldGuardMigration {
File newFile = new File(plugin.getDataFolder(), newPath);
if (!newFile.exists() && oldFile.exists()) {
logger.warning("WorldGuard: WorldGuard will now update your blacklist "
plugin.getLogger().warning("WorldGuard will now update your blacklist "
+ "from an older version of WorldGuard.");
// Need to make root directories
@@ -60,9 +63,9 @@ public class LegacyWorldGuardMigration {
oldFile.renameTo(new File(plugin.getDataFolder(),
"blacklist.txt.old"));
} else {
logger.warning("WorldGuard: blacklist.txt has been converted " +
plugin.getLogger().warning("blacklist.txt has been converted " +
"for the main world at " + newPath + "");
logger.warning("WorldGuard: Your other worlds currently have no " +
plugin.getLogger().warning("Your other worlds currently have no " +
"blacklist defined!");
}
@@ -72,22 +75,22 @@ public class LegacyWorldGuardMigration {
/**
* Migrate region settings.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateRegions(WorldGuardPlugin plugin) {
try {
File oldDatabase = new File(plugin.getDataFolder(), "regions.txt");
if (!oldDatabase.exists()) return;
logger.info("WorldGuard: The regions database has changed in 4.x. "
plugin.getLogger().info("The regions database has changed in 5.x. "
+ "Your old regions database will be converted to the new format "
+ "and set as your primarily world's database.");
+ "and set as your primary world's database.");
World w = plugin.getServer().getWorlds().get(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
// First load up the old database using the CSV loader
CSVDatabase db = new CSVDatabase(oldDatabase);
CSVDatabase db = new CSVDatabase(oldDatabase, plugin.getLogger());
db.load();
// Then save the new database
@@ -96,10 +99,9 @@ public class LegacyWorldGuardMigration {
oldDatabase.renameTo(new File(plugin.getDataFolder(), "regions.txt.old"));
logger.info("WorldGuard: Regions database converted!");
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions: "
plugin.getLogger().info("Regions database converted!");
} catch (ProtectionDatabaseException e) {
plugin.getLogger().warning("Failed to load regions: "
+ e.getMessage());
}
}
@@ -107,8 +109,8 @@ public class LegacyWorldGuardMigration {
/**
* Copies a file.
*
* @param from
* @param to
* @param from The source file
* @param to The destination file
* @return true if successful
*/
private static boolean copyFile(File from, File to) {
@@ -129,20 +131,20 @@ public class LegacyWorldGuardMigration {
out.close();
return true;
} catch (FileNotFoundException ex) {
} catch (IOException e) {
} catch (FileNotFoundException ignore) {
} catch (IOException ignore) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
@@ -21,6 +21,7 @@ package com.sk89q.worldguard.bukkit;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@@ -37,7 +38,7 @@ public class LoggerToChatHandler extends Handler {
/**
* Construct the object.
*
*
* @param player
*/
public LoggerToChatHandler(CommandSender player) {
@@ -0,0 +1,83 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
public class RegionQueryUtil {
public static boolean isInvincible(WorldGuardPlugin plugin, Player player) {
return isInvincible(plugin, player, null);
}
public static boolean isInvincible(WorldGuardPlugin plugin, Player player,
ApplicableRegionSet set) {
Location loc = player.getLocation();
World world = player.getWorld();
FlagStateManager.PlayerFlagState state = plugin.getFlagStateManager().getState(player);
if (state.lastInvincibleWorld == null ||
!state.lastInvincibleWorld.equals(world) ||
state.lastInvincibleX != loc.getBlockX() ||
state.lastInvincibleY != loc.getBlockY() ||
state.lastInvincibleZ != loc.getBlockZ()) {
state.lastInvincibleX = loc.getBlockX();
state.lastInvincibleY = loc.getBlockY();
state.lastInvincibleZ = loc.getBlockZ();
state.lastInvincibleWorld = world;
if (set == null) {
Vector vec = new Vector(state.lastInvincibleX,
state.lastInvincibleY, state.lastInvincibleZ);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
set = mgr.getApplicableRegions(vec);
}
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
}
return state.wasInvincible;
}
public static Boolean isAllowedInvinciblity(WorldGuardPlugin plugin, Player player) {
World world = player.getWorld();
FlagStateManager.PlayerFlagState state = plugin.getFlagStateManager().getState(player);
Vector vec = new Vector(state.lastInvincibleX, state.lastInvincibleY, state.lastInvincibleZ);
StateFlag.State regionState = plugin.getGlobalRegionManager().get(world).
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
if (regionState == StateFlag.State.ALLOW) {
return Boolean.TRUE;
} else if (regionState == StateFlag.State.DENY) {
return Boolean.FALSE;
} else {
return null;
}
}
}
@@ -23,16 +23,18 @@ import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
@@ -120,11 +122,12 @@ public class ReportWriter {
Class<? extends ConfigurationManager> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
if (field.getName().equalsIgnoreCase("CONFIG_HEADER")) continue;
Object val = field.get(config);
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -202,7 +205,7 @@ public class ReportWriter {
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock entitiesLog = worldLog.putChild("Entities");
infoLog.put("ID", world.getId());
infoLog.put("Seed", world.getSeed());
infoLog.put("Environment", world.getEnvironment().toString());
infoLog.put("Player count", world.getPlayers().size());
infoLog.put("Entity count", world.getEntities().size());
@@ -271,7 +274,7 @@ public class ReportWriter {
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -321,7 +324,7 @@ public class ReportWriter {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
@@ -331,5 +334,4 @@ public class ReportWriter {
public String toString() {
return output.toString();
}
}
@@ -19,19 +19,21 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
import static com.sk89q.worldguard.bukkit.BukkitUtil.isBlockWater;
import static com.sk89q.worldguard.bukkit.BukkitUtil.setBlockToWater;
import org.bukkit.World;
public class SpongeUtil {
/**
* Remove water around a sponge.
*
* @param plugin
* @param world
* @param ox
* @param oy
* @param oz
*
* @param plugin The plugin instace
* @param world The world the sponge isin
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void clearSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -51,11 +53,11 @@ public class SpongeUtil {
/**
* Add water around a sponge.
*
* @param plugin
* @param world
* @param ox
* @param oy
* @param oz
* @param plugin The plugin instance
* @param world The world the sponge is located in
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void addSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -19,6 +19,22 @@
package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
import com.sk89q.worldguard.blacklist.loggers.ConsoleLoggerHandler;
@@ -26,19 +42,6 @@ import com.sk89q.worldguard.blacklist.loggers.DatabaseLoggerHandler;
import com.sk89q.worldguard.blacklist.loggers.FileLoggerHandler;
import com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.chest.SignChestProtection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
/**
* Holds the configuration for individual worlds.
@@ -59,15 +62,11 @@ public class WorldConfiguration {
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private static final Logger logger = Logger
.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
private String worldName;
private Configuration parentConfig;
private Configuration config;
private File configFile;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File blacklistFile;
private Blacklist blacklist;
@@ -76,30 +75,30 @@ public class WorldConfiguration {
/* Configuration data start */
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean enforceOneSession;
public boolean itemDurability;
public boolean classicWater;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockTNT;
public boolean blockLighter;
public boolean disableFireSpread;
public Set<Integer> disableFireSpreadBlocks;
public boolean preventLavaFire;
public Set<Integer> allowedLavaSpreadOver;
public boolean blockTNTExplosions;
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public int loginProtection;
public int spawnProtection;
public boolean kickOnDeath;
public boolean exactRespawn;
public boolean teleportToHome;
public boolean blockEnderDragonBlockDamage;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockEntityPaintingDestroy;
public boolean blockPluginSpawning;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
@@ -115,15 +114,16 @@ public class WorldConfiguration {
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand = 287;
public Set<CreatureType> blockCreatureSpawn;
public boolean useiConomy;
public boolean buyOnClaim;
public double buyOnClaimPrice;
public Set<EntityType> blockCreatureSpawn;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
public int maxClaimVolume;
public boolean claimOnlyInsideExistingRegions;
public int maxRegionCountPerPlayer;
public boolean antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
@@ -142,94 +142,130 @@ public class WorldConfiguration {
public boolean disableSnowFormation;
public boolean disableIceFormation;
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableEndermanGriefing;
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin
* @param worldName
* @param plugin The WorldGuardPlugin instance
* @param worldName The world name that this WorldConfiguration is for.
* @param parentConfig The parent configuration to read defaults from
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName) {
public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
configFile = new File(baseFolder, "config.yml");
File configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
this.plugin = plugin;
this.worldName = worldName;
this.parentConfig = plugin.getConfiguration();
this.parentConfig = parentConfig;
WorldGuardPlugin.createDefaultConfiguration(configFile, "config_world.yml");
WorldGuardPlugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
config = new Configuration(this.configFile);
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
logger.info("WorldGuard: Loaded configuration for world '" + worldName + '"');
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
}
private boolean getBoolean(String node, boolean def) {
boolean val = parentConfig.getBoolean(node, def);
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return parentConfig.getBoolean(node, def);
return val;
}
}
private String getString(String node, String def) {
String val = parentConfig.getString(node, def);
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return parentConfig.getString(node, def);
return val;
}
}
private int getInt(String node, int def) {
int val = parentConfig.getInt(node, def);
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return parentConfig.getInt(node, def);
return val;
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return parentConfig.getDouble(node, def);
return val;
}
}
private List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res;
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
} else {
res = parentConfig.getIntList(node, def);
}
List<Integer> res = parentConfig.getIntList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
}
return res;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res;
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
} else {
res = parentConfig.getStringList(node, def);
}
List<String> res = parentConfig.getStringList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
}
return res;
}
private List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
private Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
}
@@ -237,21 +273,25 @@ public class WorldConfiguration {
* Load the configuration.
*/
private void loadConfiguration() {
config.load();
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
}
opPermissions = getBoolean("op-permissions", true);
enforceOneSession = getBoolean("protection.enforce-single-session", true);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
classicWater = getBoolean("simulation.classic-water", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
pumpkinScuba = getBoolean("pumpkin-scuba", false);
pumpkinScuba = getBoolean("default.pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
noPhysicsGravel = getBoolean("physics.no-physics-gravel", false);
@@ -259,7 +299,8 @@ public class WorldConfiguration {
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
blockTNT = getBoolean("ignition.block-tnt", false);
blockTNTExplosions = getBoolean("ignition.block-tnt", false);
blockTNTBlockDamage = getBoolean("ignition.block-tnt-block-damage", false);
blockLighter = getBoolean("ignition.block-lighter", false);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", true);
@@ -269,13 +310,13 @@ public class WorldConfiguration {
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
loginProtection = getInt("spawn.login-protection", 3);
spawnProtection = getInt("spawn.spawn-protection", 0);
kickOnDeath = getBoolean("spawn.kick-on-death", false);
exactRespawn = getBoolean("spawn.exact-respawn", false);
teleportToHome = getBoolean("spawn.teleport-to-home-on-death", false);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -289,8 +330,10 @@ public class WorldConfiguration {
teleportOnVoid = getBoolean("player-damage.teleport-on-void-falling", false);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
disableDeathMessages = getBoolean("player-damage.disable-death-messages", false);
signChestProtection = getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", false);
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
@@ -310,24 +353,40 @@ public class WorldConfiguration {
disableSnowFormation = getBoolean("dynamics.disable-snow-formation", false);
disableIceFormation = getBoolean("dynamics.disable-ice-formation", false);
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
regionWand = getInt("regions.wand", 287);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player", 7);
useiConomy = getBoolean("iconomy.enable", false);
buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
blockCreatureSpawn = new HashSet<CreatureType>();
for (String key : getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
if (val != null && val instanceof Number) {
maxRegionCounts.put(key, ((Number) val).intValue());
}
}
}
// useiConomy = getBoolean("iconomy.enable", false);
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<EntityType>();
for (String creatureName : getStringList("mobs.block-creature-spawn", null)) {
CreatureType creature = CreatureType.fromName(creatureName);
EntityType creature = EntityType.fromName(creatureName);
if (creature == null) {
logger.warning("WorldGuard: Unknown mob type '" + creatureName + "'");
plugin.getLogger().warning("Unknown mob type '" + creatureName + "'");
} else if (!creature.isAlive()) {
plugin.getLogger().warning("Entity type '" + creatureName + "' is not a creature");
} else {
blockCreatureSpawn.add(creature);
}
@@ -367,64 +426,58 @@ public class WorldConfiguration {
this.blacklist = null;
} else {
this.blacklist = blist;
logger.log(Level.INFO, "WorldGuard: Blacklist loaded.");
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
BlacklistLogger blacklistLogger = blist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName));
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName, plugin.getLogger()));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName));
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName, plugin.getLogger()));
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName);
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger());
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "WorldGuard blacklist does not exist.");
plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist.");
} catch (IOException e) {
logger.log(Level.WARNING, "Could not load WorldGuard blacklist: "
plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: "
+ e.getMessage());
}
// Print an overview of settings
if (getBoolean("summary-on-start", true)) {
logger.log(Level.INFO, enforceOneSession
? "WorldGuard: (" + worldName + ") Single session is enforced."
: "WorldGuard: (" + worldName + ") Single session is NOT ENFORCED.");
logger.log(Level.INFO, blockTNT
? "WorldGuard: (" + worldName + ") TNT ignition is blocked."
: "WorldGuard: (" + worldName + ") TNT ignition is PERMITTED.");
logger.log(Level.INFO, blockLighter
? "WorldGuard: (" + worldName + ") Lighters are blocked."
: "WorldGuard: (" + worldName + ") Lighters are PERMITTED.");
logger.log(Level.INFO, preventLavaFire
? "WorldGuard: (" + worldName + ") Lava fire is blocked."
: "WorldGuard: (" + worldName + ") Lava fire is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockLighter
? "(" + worldName + ") Lighters are blocked."
: "(" + worldName + ") Lighters are PERMITTED.");
plugin.getLogger().log(Level.INFO, preventLavaFire
? "(" + worldName + ") Lava fire is blocked."
: "(" + worldName + ") Lava fire is PERMITTED.");
if (disableFireSpread) {
logger.log(Level.INFO, "WorldGuard: (" + worldName + ") All fire spread is disabled.");
plugin.getLogger().log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
logger.log(Level.INFO, "WorldGuard: (" + worldName
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
logger.log(Level.INFO, "WorldGuard: (" + worldName
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
config.save();
}
@@ -436,7 +489,7 @@ public class WorldConfiguration {
public String getWorldName() {
return this.worldName;
}
public boolean isChestProtected(Block block, Player player) {
if (!signChestProtection) {
return false;
@@ -447,14 +500,14 @@ public class WorldConfiguration {
}
return chestProtection.isProtected(block, player);
}
public boolean isChestProtected(Block block) {
if (!signChestProtection) {
return false;
}
return chestProtection.isProtected(block, null);
}
public boolean isChestProtectedPlacement(Block block, Player player) {
if (!signChestProtection) {
return false;
@@ -480,5 +533,18 @@ public class WorldConfiguration {
public ChestProtection getChestProtection() {
return chestProtection;
}
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
if (maxRegionCounts.containsKey(group)) {
int groupMax = maxRegionCounts.get(group);
if (max < groupMax) max = groupMax;
}
}
if (max <= -1) {
max = maxRegionCountPerPlayer;
}
return max;
}
}
@@ -18,47 +18,58 @@
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginManager;
import org.bukkit.block.Block;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.event.block.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import java.util.logging.Logger;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* The listener for block events.
*
*
* @author sk89q
*/
public class WorldGuardBlockListener extends BlockListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -68,75 +79,40 @@ public class WorldGuardBlockListener extends BlockListener {
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("BLOCK_DAMAGE", Priority.High);
registerEvent("BLOCK_BREAK", Priority.High);
registerEvent("BLOCK_FROMTO", Priority.Normal);
registerEvent("BLOCK_IGNITE", Priority.High);
registerEvent("BLOCK_PHYSICS", Priority.Normal);
registerEvent("BLOCK_PLACE", Priority.High);
registerEvent("BLOCK_BURN", Priority.High);
registerEvent("SIGN_CHANGE", Priority.High);
registerEvent("REDSTONE_CHANGE", Priority.High);
registerEvent("SNOW_FORM", Priority.High);
registerEvent("LEAVES_DECAY", Priority.High);
registerEvent("BLOCK_FORM", Priority.High);
registerEvent("BLOCK_SPREAD", Priority.High);
registerEvent("BLOCK_FADE", Priority.High);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Get the world configuration given a world.
*
* @param world
* @return
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player
* @return
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return plugin.getGlobalStateManager().get(player.getWorld());
return getWorldConfig(player.getWorld());
}
/**
/*
* Called when a block is damaged.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
// Cake are damaged and not broken when they are eaten, so we must
// handle them a bit separately
if (blockDamaged.getType() == Material.CAKE_BLOCK) {
if (blockDamaged.getTypeId() == BlockID.CAKE_BLOCK) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockDamaged)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
event.setCancelled(true);
@@ -144,16 +120,12 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
}
/**
/*
* Called when a block is broken.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
@@ -167,7 +139,8 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())) {
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())
|| !plugin.getGlobalRegionManager().canConstruct(player, event.getBlock())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
@@ -190,7 +163,7 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
}
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
@@ -198,21 +171,18 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
/*
* Called when fluids flow.
*/
@Override
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
if (event.isCancelled()) {
return;
}
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
boolean isAir = blockFrom.getTypeId() == 0;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -256,8 +226,8 @@ public class WorldGuardBlockListener extends BlockListener {
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
if ((blockFrom.getTypeId() == 0 || isWater) &&
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
return;
@@ -266,7 +236,7 @@ public class WorldGuardBlockListener extends BlockListener {
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
@@ -286,17 +256,19 @@ public class WorldGuardBlockListener extends BlockListener {
event.setCancelled(true);
return;
}
}
/**
* Called when a block gets ignited.
*/
@Override
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& blockTo.getTypeId() == 55) {
blockTo.setTypeId(0);
return;
}
}
/*
* Called when a block gets ignited.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
@@ -308,7 +280,6 @@ public class WorldGuardBlockListener extends BlockListener {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
@@ -326,7 +297,7 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
if (wcfg.blockLighter && cause == IgniteCause.FLINT_AND_STEEL
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
@@ -367,7 +338,7 @@ public class WorldGuardBlockListener extends BlockListener {
event.setCancelled(true);
return;
}
if (!set.allows(DefaultFlag.LIGHTER)
if (!set.allows(DefaultFlag.LIGHTER, localPlayer)
&& !plugin.hasPermission(player, "worldguard.override.lighter")) {
event.setCancelled(true);
return;
@@ -386,20 +357,19 @@ public class WorldGuardBlockListener extends BlockListener {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block is destroyed from burning.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -414,7 +384,9 @@ public class WorldGuardBlockListener extends BlockListener {
}
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
@@ -423,6 +395,7 @@ public class WorldGuardBlockListener extends BlockListener {
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
@@ -431,14 +404,18 @@ public class WorldGuardBlockListener extends BlockListener {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Block block = event.getBlock();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
Vector pt = toVector(block);
RegionManager mgr = plugin.getGlobalRegionManager().get(block.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, BlockID.FIRE);
event.setCancelled(true);
return;
}
@@ -446,16 +423,26 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
private void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
private void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
}
}
/*
* Called when block physics occurs.
*/
@Override
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -482,16 +469,11 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
/*
* Called when a player places a block.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
@@ -500,7 +482,9 @@ public class WorldGuardBlockListener extends BlockListener {
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockPlaced.getLocation())) {
final Location location = blockPlaced.getLocation();
if (!plugin.getGlobalRegionManager().canBuild(player, location)
|| !plugin.getGlobalRegionManager().canConstruct(player, location)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
@@ -515,8 +499,8 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
}
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getType())) {
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getTypeId())) {
if (wcfg.isAdjacentChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
event.setCancelled(true);
@@ -537,12 +521,11 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
/*
* Called when redstone changes.
*/
@Override
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
@@ -573,29 +556,28 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
/*
* Called when a sign is changed.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
if (event.getBlock().getType() != Material.SIGN_POST) {
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
@@ -604,33 +586,33 @@ public class WorldGuardBlockListener extends BlockListener {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
Material below = event.getBlock().getRelative(0, -1, 0).getType();
if (below == Material.TNT || below == Material.SAND
|| below == Material.GRAVEL || below == Material.SIGN_POST) {
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (below == BlockID.TNT || below == BlockID.SAND
|| below == BlockID.GRAVEL || below == BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
event.setLine(0, "[Lock]");
player.sendMessage(ChatColor.YELLOW
+ "A chest or double chest above is now protected.");
}
} else {
} else if (!wcfg.disableSignChestProtectionCheck) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
@@ -642,43 +624,9 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
}
/**
* Called when snow is formed.
*/
@Override
public void onSnowForm(SnowFormEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.SNOW_FALL,
event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
}
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -700,14 +648,11 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -716,27 +661,38 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
Material type = event.getNewState().getType();
int type = event.getNewState().getTypeId();
if (wcfg.disableIceFormation && type == Material.ICE) {
event.setCancelled(true);
return;
if (type == BlockID.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_FORM, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.disableSnowFormation && type == Material.SNOW) {
event.setCancelled(true);
return;
if (type == BlockID.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_FALL, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -745,36 +701,105 @@ public class WorldGuardBlockListener extends BlockListener {
return;
}
Material fromType = event.getSource().getType();
int fromType = event.getSource().getTypeId();
if (wcfg.disableMushroomSpread && (fromType == Material.RED_MUSHROOM
|| fromType == Material.BROWN_MUSHROOM)) {
event.setCancelled(true);
return;
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.MUSHROOMS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.GRASS) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.GRASS_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
Material type = event.getBlock().getType();
int type = event.getBlock().getTypeId();
if (wcfg.disableIceMelting && type == Material.ICE) {
event.setCancelled(true);
return;
if (type == BlockID.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.disableSnowMelting && type == Material.SNOW) {
event.setCancelled(true);
return;
if (type == BlockID.SNOW) {
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
for (Block block : event.getBlocks()) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, block.getLocation())) {
event.setCancelled(true);
return;
}
}
}
}
/*
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.useRegions && event.isSticky()) {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
}
}
}
@@ -0,0 +1,75 @@
/*
* WorldGuard
* Copyright (C) 2012 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.InfoComponent;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
/**
* @author zml2008
*/
public class WorldGuardCommandBookListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardCommandBookListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerWhois(InfoComponent.PlayerWhoisEvent event) {
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (plugin.getGlobalStateManager().get(player.getWorld()).useRegions) {
ApplicableRegionSet regions = plugin.getGlobalRegionManager()
.get(player.getWorld()).getApplicableRegions(player.getLocation());
// Current regions
StringBuilder regionStr = new StringBuilder();
boolean first = true;
for (ProtectedRegion region : regions) {
if (!first) {
regionStr.append(", ");
}
if (region.isOwner(localPlayer)) {
regionStr.append("+");
} else if (region.isMemberOnly(localPlayer)) {
regionStr.append("-");
}
regionStr.append(region.getId());
first = false;
}
if (regions.size() > 0) {
event.addWhoisInformation("Current Regions", regionStr);
}
event.addWhoisInformation("Can build", regions.canBuild(localPlayer));
}
}
}
}
@@ -20,48 +20,76 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import java.util.Set;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.entity.*;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.Set;
import java.util.logging.Logger;
/**
* Listener for entity related events.
*
*
* @author sk89q
*/
public class WorldGuardEntityListener extends EntityListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -71,60 +99,38 @@ public class WorldGuardEntityListener extends EntityListener {
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("ENTITY_DAMAGE", Priority.High);
registerEvent("ENTITY_COMBUST", Priority.High);
registerEvent("ENTITY_EXPLODE", Priority.High);
registerEvent("CREATURE_SPAWN", Priority.High);
registerEvent("ENTITY_INTERACT", Priority.High);
registerEvent("CREEPER_POWER", Priority.High);
registerEvent("PIG_ZAP", Priority.High);
registerEvent("PAINTING_BREAK", Priority.High);
registerEvent("PAINTING_PLACE", Priority.High);
registerEvent("ENTITY_REGAIN_HEALTH", Priority.High);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Called when an entity interacts with another object.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
//bukkit doesn't actually throw this event yet, someone add a ticket to leaky
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (block.getType() == Material.SOIL) {
if (block.getTypeId() == BlockID.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
}
}
/**
* Called on entity damage by a block.
*
* @param event
*/
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
if (wcfg.disableExpDrops || !plugin.getGlobalRegionManager().allows(DefaultFlag.EXP_DROPS,
event.getEntity().getLocation())) {
event.setDroppedExp(0);
}
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
}
}
private void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
@@ -140,14 +146,14 @@ public class WorldGuardEntityListener extends EntityListener {
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (cfg.hasGodMode(player)) {
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
if (cfg.hasGodMode(player)) player.setFireTicks(0);
player.setFireTicks(0);
return;
}
@@ -167,22 +173,22 @@ public class WorldGuardEntityListener extends EntityListener {
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.BLOCK_EXPLOSION) {
if (wcfg.disableExplosionDamage && type == DamageCause.BLOCK_EXPLOSION) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on entity damage by an entity.
*
* @param event
*/
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getCause() == DamageCause.PROJECTILE) {
onEntityDamageByProjectile(event);
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
@@ -190,7 +196,7 @@ public class WorldGuardEntityListener extends EntityListener {
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
@@ -205,11 +211,18 @@ public class WorldGuardEntityListener extends EntityListener {
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
if (isInvincible(player)) {
if (wcfg.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
event.setCancelled(true);
return;
}
@@ -227,16 +240,60 @@ public class WorldGuardEntityListener extends EntityListener {
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof TNTPrimed) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Fireball) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
@@ -254,13 +311,13 @@ public class WorldGuardEntityListener extends EntityListener {
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE)) {
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION)) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -271,22 +328,18 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called on entity damage by a projectile.
*
* @param event
*/
private void onEntityDamageByProjectile(EntityDamageByProjectileEvent event) {
private void onEntityDamageByProjectile(EntityDamageByEntityEvent event) {
Entity defender = event.getEntity();
Entity attacker = event.getDamager();
Entity attacker = ((Projectile) event.getDamager()).getShooter();
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
@@ -294,11 +347,12 @@ public class WorldGuardEntityListener extends EntityListener {
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
@@ -312,7 +366,7 @@ public class WorldGuardEntityListener extends EntityListener {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE)) {
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -322,19 +376,10 @@ public class WorldGuardEntityListener extends EntityListener {
}
/**
* Called on entity damage.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled()) {
return;
}
if (event instanceof EntityDamageByProjectileEvent) {
this.onEntityDamageByProjectile((EntityDamageByProjectileEvent) event);
return;
} else if (event instanceof EntityDamageByEntityEvent) {
if (event instanceof EntityDamageByEntityEvent) {
this.onEntityDamageByEntity((EntityDamageByEntityEvent) event);
return;
} else if (event instanceof EntityDamageByBlockEvent) {
@@ -356,7 +401,7 @@ public class WorldGuardEntityListener extends EntityListener {
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (cfg.hasGodMode(player)) {
if (isInvincible(player)) {
event.setCancelled(true);
player.setFireTicks(0);
return;
@@ -368,9 +413,12 @@ public class WorldGuardEntityListener extends EntityListener {
return;
}
ItemStack helmet = player.getInventory().getHelmet();
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& (player.getInventory().getHelmet().getType() == Material.PUMPKIN
|| player.getInventory().getHelmet().getType() == Material.JACK_O_LANTERN)) {
&& helmet != null
&& (helmet.getTypeId() == BlockID.PUMPKIN
|| helmet.getTypeId() == BlockID.JACKOLANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -406,47 +454,43 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called on entity combust.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
if (event.isCancelled()) {
return;
}
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (entity instanceof Player) {
Player player = (Player) entity;
if (cfg.hasGodMode(player)) {
if (cfg.hasGodMode(player) || (wcfg.useRegions && RegionQueryUtil.isInvincible(plugin, player))) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called on entity explode.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
Entity ent = event.getEntity();
if (ent instanceof LivingEntity) {
if (cfg.activityHaltToggle) {
ent.remove();
event.setCancelled(true);
return;
}
if (ent instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage) {
event.setCancelled(true);
event.blockList().clear();
return;
}
@@ -456,79 +500,108 @@ public class WorldGuardEntityListener extends EntityListener {
}
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof Fireball) {
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
} else if (ent instanceof EnderDragon) {
if (wcfg.blockEnderDragonBlockDamage) {
event.blockList().clear();
return;
}
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
if (wcfg.useRegions) {
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE)) {
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof TNTPrimed) {
if (cfg.activityHaltToggle) {
event.setCancelled(true);
if (wcfg.blockTNTBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockTNT) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
return;
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.TNT)) {
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof Fireball) {
if (wcfg.blockFireballBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.GHAST_FIREBALL)) {
event.blockList().clear();
return;
}
}
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
event.setCancelled(true);
event.blockList().clear();
return;
}
}
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
// Whoo, for each block
for (Block block : event.blockList()) {
Vector pt = toVector(block);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
return;
}
}
}
}
/**
* Called on creature spawn.
/*
* Called on explosion prime
*/
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
ent.remove();
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (cfg.activityHaltToggle) {
@@ -537,18 +610,25 @@ public class WorldGuardEntityListener extends EntityListener {
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
CreatureType creaType = event.getCreatureType();
if (wcfg.blockCreatureSpawn.contains(creaType)) {
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM)
return;
EntityType entityType = event.getEntityType();
if (wcfg.blockCreatureSpawn.contains(entityType)) {
event.setCancelled(true);
return;
}
Location eventLoc = event.getLocation();
if (wcfg.useRegions) {
Vector pt = toVector(eventLoc);
RegionManager mgr = plugin.getGlobalRegionManager().get(eventLoc.getWorld());
// @TODO get victims' stacktraces and find out why it's null anyway
if (mgr == null) return;
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_SPAWNING)) {
@@ -556,23 +636,16 @@ public class WorldGuardEntityListener extends EntityListener {
return;
}
Set<CreatureType> blockTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (blockTypes != null && blockTypes.contains(creaType)) {
Set<EntityType> entityTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (entityTypes != null && entityTypes.contains(entityType)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on pig zap.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
@@ -581,15 +654,8 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called on creeper power.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
@@ -598,53 +664,62 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called when a painting is removed.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (breakEvent.isCancelled()) {
return;
}
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
if (!(event.getRemover() instanceof Player)) {
return;
}
Painting painting= event.getPainting();
Player player = (Player) event.getRemover();
World world = painting.getWorld();
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
if (event.getRemover() instanceof Player) {
Player player = (Player) event.getRemover();
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (event.getRemover() instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.blockEntityPaintingDestroy) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on painting place.
*/
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
@@ -656,7 +731,7 @@ public class WorldGuardEntityListener extends EntityListener {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
@@ -671,10 +746,9 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called on entity health regain.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity ent = event.getEntity();
World world = ent.getWorld();
@@ -687,4 +761,124 @@ public class WorldGuardEntityListener extends EntityListener {
}
}
/**
* Called when an enderman picks up or puts down a block and some other cases.
*
* @param event Relevant event details
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEndermanPickup(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
if (ent instanceof Enderman) {
if (event.getTo() == Material.AIR) {
// pickup
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
} else {
// place
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
GlobalRegionManager global = plugin.getGlobalRegionManager();
int blockedEntities = 0;
for (LivingEntity e : event.getAffectedEntities()) {
if (!global.allows(DefaultFlag.POTION_SPLASH, e.getLocation(), e instanceof Player ? plugin.wrapPlayer((Player) e) : null)) {
event.setIntensity(e, 0);
++blockedEntities;
}
}
if (blockedEntities == event.getAffectedEntities().size()) {
event.setCancelled(true);
}
}
/**
* Check if a player is invincible, via either god mode or region flag. If
* the region denies invincibility, the player must have an extra permission
* to override it. (worldguard.god.override-regions)
*
* @param player The player to check
* @return Whether {@code player} is invincible
*/
private boolean isInvincible(Player player) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
boolean god = cfg.hasGodMode(player);
if (wcfg.useRegions) {
Boolean flag = RegionQueryUtil.isAllowedInvinciblity(plugin, player);
boolean allowed = flag == null || flag;
boolean invincible = RegionQueryUtil.isInvincible(plugin, player);
if (allowed) {
return god || invincible;
} else {
return (god && plugin.hasPermission(player, "worldguard.god.override-regions"))
|| invincible;
}
} else {
return god;
}
}
/**
* Using a DisallowedPVPEvent, notifies other plugins that WorldGuard
* wants to cancel a PvP damage event.<br />
* If this event is not cancelled, the attacking player is notified that
* PvP is disabled and WorldGuard cancels the damage event.
*
* @param attackingPlayer The attacker
* @param defendingPlayer The defender
* @param event The event that caused WorldGuard to act
*/
public void tryCancelPVPEvent(final Player attackingPlayer, final Player defendingPlayer, EntityDamageByEntityEvent event) {
final DisallowedPVPEvent disallowedPVPEvent = new DisallowedPVPEvent(attackingPlayer, defendingPlayer, event);
plugin.getServer().getPluginManager().callEvent(disallowedPVPEvent);
if (!disallowedPVPEvent.isCancelled()) {
attackingPlayer.sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -19,7 +19,22 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.wepif.PermissionsResolverManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
@@ -29,33 +44,26 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.bukkit.migration.*;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.TickSyncDelayLoggerFilter;
import com.sk89q.worldguard.bukkit.commands.GeneralCommands;
import com.sk89q.worldguard.bukkit.commands.ProtectionCommands;
import com.sk89q.worldguard.bukkit.commands.ToggleCommands;
import com.sk89q.worldguard.protection.*;
import java.io.*;
import java.util.*;
import java.util.logging.Filter;
import java.util.logging.Logger;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.util.FatalConfigurationLoadingException;
/**
* The main class for WorldGuard as a Bukkit plugin.
*
*
* @author sk89q
*/
public class WorldGuardPlugin extends JavaPlugin {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Manager for commands. This automatically handles nested commands,
* permissions checking, and a number of other fancy command things.
@@ -67,20 +75,12 @@ public class WorldGuardPlugin extends JavaPlugin {
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Processes queries for permissions information. The permissions manager
* is from WorldEdit and it automatically handles looking up permissions
* systems and picking the right one. WorldGuard just needs to call
* the permission methods.
*/
private PermissionsResolverManager perms;
/**
* Used for scheduling flags.
*/
@@ -93,7 +93,7 @@ public class WorldGuardPlugin extends JavaPlugin {
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new GlobalRegionManager(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@Override
@@ -101,54 +101,56 @@ public class WorldGuardPlugin extends JavaPlugin {
return plugin.hasPermission(player, perm);
}
};
// Register command classes
commands.register(ToggleCommands.class);
commands.register(ProtectionCommands.class);
commands.register(GeneralCommands.class);
}
/**
* Called on plugin enable.
*/
@SuppressWarnings("deprecation")
public void onEnable() {
// Set the proper command injector
commands.setInjector(new SimpleInjector(this));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
if (!getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
}
}, 0L);
// Need to create the plugins/WorldGuard folder
getDataFolder().mkdirs();
// Set up permissions
perms = new PermissionsResolverManager(
getConfiguration(), getServer(), "WorldGuard", logger);
perms.load();
PermissionsResolverManager.initialize(this);
// This must be done before configuration is laoded
// This must be done before configuration is loaded
LegacyWorldGuardMigration.migrateBlacklist(this);
// Load the configuration
configuration.load();
globalRegionManager.preload();
try {
// Load the configuration
configuration.load();
globalRegionManager.preload();
} catch (FatalConfigurationLoadingException e) {
e.printStackTrace();
getServer().shutdown();
}
// Migrate regions after the regions were loaded because
// the migration code reuses the loaded region managers
LegacyWorldGuardMigration.migrateRegions(this);
// Load permissions
(new PermissionsResolverServerListener(perms)).register(this);
flagStateManager = new FlagStateManager(this);
if (configuration.useRegionsScheduler) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this,
flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
if (configuration.suppressTickSyncWarnings) {
Logger.getLogger("Minecraft").setFilter(
new TickSyncDelayLoggerFilter());
} else {
Filter filter = Logger.getLogger("Minecraft").getFilter();
if (filter != null && filter instanceof TickSyncDelayLoggerFilter) {
Logger.getLogger("Minecraft").setFilter(null);
}
if (configuration.useRegionsScheduler) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
// Register events
@@ -156,9 +158,30 @@ public class WorldGuardPlugin extends JavaPlugin {
(new WorldGuardBlockListener(this)).registerEvents();
(new WorldGuardEntityListener(this)).registerEvents();
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardWorldListener(this)).registerEvents();
logger.info("WorldGuard " + this.getDescription().getVersion() + " enabled.");
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
configuration.updateCommandBookGodMode();
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
getServer().getPluginManager().registerEvents(new WorldGuardCommandBookListener(this), this);
}
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
for (World world : getServer().getWorlds()) {
worldListener.initWorld(world);
}
worldListener.registerEvents();
if (!configuration.hasCommandBookGodMode()) {
// Check god mode for existing players, if any
for (Player player : getServer().getOnlinePlayers()) {
if (inGroup(player, "wg-invincible") ||
(configuration.autoGodMode && hasPermission(player, "worldguard.auto-invincible"))) {
configuration.enableGodMode(player);
}
}
}
}
/**
@@ -167,10 +190,9 @@ public class WorldGuardPlugin extends JavaPlugin {
public void onDisable() {
globalRegionManager.unload();
configuration.unload();
logger.info("WorldGuard " + getDescription().getVersion() + " disabled.");
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@@ -178,7 +200,7 @@ public class WorldGuardPlugin extends JavaPlugin {
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
try {
commands.execute(cmd.getName(), args, sender, this, sender);
commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
@@ -196,43 +218,43 @@ public class WorldGuardPlugin extends JavaPlugin {
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
/**
* Get the GlobalRegionManager.
*
* @return
*
* @return The plugin's global region manager
*/
public GlobalRegionManager getGlobalRegionManager() {
return globalRegionManager;
}
/**
* Get the WorldGuardConfiguraton.
* Get the WorldGuard Configuration.
*
* @return
* @return ConfigurationManager
* @deprecated Use {@link #getGlobalStateManager()} instead
*/
@Deprecated
public ConfigurationManager getGlobalConfiguration() {
return getGlobalStateManager();
}
/**
* Gets the flag state manager.
*
* @return
*
* @return The flag state manager
*/
public FlagStateManager getFlagStateManager() {
return flagStateManager;
}
/**
* Get the WorldGuardConfiguraton.
*
* @return
* Get the global ConfigurationManager.
* USe this to access global configuration values and per-world configuration values.
* @return The global ConfigurationManager
*/
public ConfigurationManager getGlobalStateManager() {
return configuration;
@@ -240,14 +262,15 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Check whether a player is in a group.
*
* @param player
* @param group
* @return
* This calls the corresponding method in PermissionsResolverManager
*
* @param player The player to check
* @param group The group
* @return whether {@code player} is in {@code group}
*/
public boolean inGroup(Player player, String group) {
try {
return perms.inGroup(player.getName(), group);
return PermissionsResolverManager.getInstance().inGroup(player, group);
} catch (Throwable t) {
t.printStackTrace();
return false;
@@ -256,54 +279,56 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Get the groups of a player.
*
* @param player
* @return
* This calls the corresponding method in PermissionsResolverManager.
* @param player The player to check
* @return The names of each group the playe is in.
*/
public String[] getGroups(Player player) {
try {
return perms.getGroups(player.getName());
return PermissionsResolverManager.getInstance().getGroups(player);
} catch (Throwable t) {
t.printStackTrace();
return new String[0];
}
}
/**
* Gets the name of a command sender. This is a unique name and this
* method should never return a "display name".
*
* @param sender
* @return
*
* @param sender The sender to get the name of
* @return The unique name of the sender.
*/
public String toUniqueName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else {
return sender.getName();
}
}
/**
* Gets the name of a command sender. This play be a display name.
*
* @param sender
* @return
*
* @param sender The CommandSender to get the name of.
* @return The name of the given sender
*/
public String toName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else if (sender instanceof Player) {
return ((Player) sender).getDisplayName();
} else {
return sender.getName();
}
}
/**
* Checks permissions.
*
* @param sender
* @param perm
* @return
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @return whether {@code sender} has {@code perm}
*/
public boolean hasPermission(CommandSender sender, String perm) {
if (sender.isOp()) {
@@ -316,21 +341,22 @@ public class WorldGuardPlugin extends JavaPlugin {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
return perms.hasPermission(((Player) sender).getName(), perm);
Player player = (Player) sender;
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player.getName(), perm);
}
return false;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param sender
* @param perm
* @throws CommandPermissionsException
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @throws CommandPermissionsException if {@code sender} doesn't have {@code perm}
*/
public void checkPermission(CommandSender sender, String perm)
throws CommandPermissionsException {
@@ -338,13 +364,13 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandPermissionsException();
}
}
/**
* Checks to see if the sender is a player, otherwise throw an exception.
*
* @param sender
* @return
* @throws CommandException
*
* @param sender The {@link CommandSender} to check
* @return {@code sender} casted to a player
* @throws CommandException if {@code sender} isn't a {@link Player}
*/
public Player checkPlayer(CommandSender sender)
throws CommandException {
@@ -354,22 +380,27 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandException("A player is expected.");
}
}
/**
* Match player names.
*
* @param filter
* @return
*
* The filter string uses the following format:
* @[name] looks up all players with the exact {@code name}
* *[name] matches any player whose name contains {@code name}
* [name] matches any player whose name starts with {@code name}
*
* @param filter The filter string to check.
* @return A {@link List} of players who match {@code filter}
*/
public List<Player> matchPlayerNames(String filter) {
Player[] players = getServer().getOnlinePlayers();
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (Player player : players) {
if (player.getName().equalsIgnoreCase(filter)) {
List<Player> list = new ArrayList<Player>();
@@ -377,43 +408,43 @@ public class WorldGuardPlugin extends JavaPlugin {
return list;
}
}
return new ArrayList<Player>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
/**
* Checks if the given list of players is greater than size 0, otherwise
* throw an exception.
*
* @param players
* @return
* @throws CommandException
*
* @param players The {@link List} to check
* @return {@code players} as an {@link Iterable}
* @throws CommandException If {@code players} is empty
*/
protected Iterable<Player> checkPlayerMatch(List<Player> players)
throws CommandException {
@@ -421,25 +452,32 @@ public class WorldGuardPlugin extends JavaPlugin {
if (players.size() == 0) {
throw new CommandException("No players matched query.");
}
return players;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param source
* @param filter
* Matches players based on the specified filter string
*
* The filter string format is as follows:
* * returns all the players currently online
* If {@code sender} is a {@link Player}:
* #world returns all players in the world that {@code sender} is in
* #near reaturns all players within 30 blocks of {@code sender}'s location
* Otherwise, the format is as specified in {@link #matchPlayerNames(String)}
*
* @param source The CommandSender who is trying to find a player
* @param filter The filter string for players
* @return iterator for players
* @throws CommandException no matches found
* @throws CommandException if no matches are found
*/
public Iterable<Player> matchPlayers(CommandSender source, String filter)
throws CommandException {
if (getServer().getOnlinePlayers().length == 0) {
throw new CommandException("No players matched query.");
}
if (filter.equals("*")) {
return checkPlayerMatch(Arrays.asList(getServer().getOnlinePlayers()));
}
@@ -452,7 +490,7 @@ public class WorldGuardPlugin extends JavaPlugin {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
@@ -460,7 +498,7 @@ public class WorldGuardPlugin extends JavaPlugin {
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<Player> players = new ArrayList<Player>();
@@ -468,7 +506,7 @@ public class WorldGuardPlugin extends JavaPlugin {
World sourceWorld = sourcePlayer.getWorld();
org.bukkit.util.Vector sourceVector
= sourcePlayer.getLocation().toVector();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)
&& player.getLocation().toVector().distanceSquared(
@@ -478,32 +516,33 @@ public class WorldGuardPlugin extends JavaPlugin {
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<Player> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
/**
* Match only a single player.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*
* @param sender The {@link CommandSender} who is requesting a player match
* @param filter The filter string.
* @see #matchPlayers(org.bukkit.entity.Player) for filter string syntax
* @return The single player
* @throws CommandException If more than one player match was found
*/
public Player matchSinglePlayer(CommandSender sender, String filter)
throws CommandException {
// This will throw an exception if there are no matches
Iterator<Player> players = matchPlayers(sender, filter).iterator();
Player match = players.next();
// We don't want to match the wrong person, so fail if if multiple
// players were found (we don't want to just pick off the first one,
// as that may be the wrong player)
@@ -511,48 +550,58 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandException("More than one player found! " +
"Use @<name> for exact matching.");
}
return match;
}
/**
* Match only a single player or console.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*
* The filter string syntax is as follows:
* #console, *console, or ! return the server console
* All syntax from {@link #matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @param sender The sender trying to match a CommandSender
* @param filter The filter string
* @return The resulting CommandSender
* @throws CommandException if either zero or more than one player matched.
*/
public CommandSender matchPlayerOrConsole(CommandSender sender, String filter)
throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return new ConsoleCommandSender(getServer());
return getServer().getConsoleSender();
}
return matchSinglePlayer(sender, filter);
}
/**
* Get a single player as an iterator for players.
*
* @param player
* @return iterator for players
*
* @param player The player to return in an Iterable
* @return iterator for player
*/
public Iterable<Player> matchPlayers(Player player) {
return Arrays.asList(new Player[] {player});
return Arrays.asList(player);
}
/**
* Match a world.
* @param sender
*
* @param filter
* @return
* @throws CommandException
*
* The filter string syntax is as follows:
* #main returns the main world
* #normal returns the first world with a normal environment
* #nether return the first world with a nether environment
* #player:[name] returns the world that a player named {@code name} is located in, if the player is online.
* [name] A world with the name {@code name}
*
* @param sender The sender requesting a match
* @param filter The filter string
* @return The resulting world
* @throws CommandException if no world matches
*/
public World matchWorld(CommandSender sender, String filter) throws CommandException {
List<World> worlds = getServer().getWorlds();
@@ -562,7 +611,7 @@ public class WorldGuardPlugin extends JavaPlugin {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
@@ -572,7 +621,7 @@ public class WorldGuardPlugin extends JavaPlugin {
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
@@ -586,65 +635,65 @@ public class WorldGuardPlugin extends JavaPlugin {
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String parts[] = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
/**
* Gets a copy of the WorldEdit plugin.
*
* @return
* @throws CommandException
*
* @return The WorldEditPlugin instance
* @throws CommandException If there is no WorldEditPlugin available
*/
public WorldEditPlugin getWorldEdit() throws CommandException {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
}
if (worldEdit instanceof WorldEditPlugin) {
return (WorldEditPlugin) worldEdit;
} else {
throw new CommandException("WorldEdit detection failed (report error).");
}
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player
* @return
*
* @param player The player to wrap
* @return The wrapped player
*/
public LocalPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, player);
}
/**
* Create a default configuration file from the .jar.
*
* @param actual
* @param defaultName
*
* @param actual The destination file
* @param defaultName The name of the file inside the jar's defaults folder
*/
public static void createDefaultConfiguration(File actual,
public void createDefaultConfiguration(File actual,
String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
@@ -655,9 +704,17 @@ public class WorldGuardPlugin extends JavaPlugin {
return;
}
InputStream input = WorldGuardPlugin.class
.getResourceAsStream("/defaults/" + defaultName);
InputStream input =
null;
try {
JarFile file = new JarFile(getFile());
ZipEntry copy = file.getEntry("defaults/" + defaultName);
if (copy == null) throw new FileNotFoundException();
input = file.getInputStream(copy);
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
@@ -669,7 +726,7 @@ public class WorldGuardPlugin extends JavaPlugin {
output.write(buf, 0, length);
}
logger.info("WorldGuard: Default configuration file written: "
getLogger().info("Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
@@ -678,60 +735,68 @@ public class WorldGuardPlugin extends JavaPlugin {
if (input != null) {
input.close();
}
} catch (IOException e) {
} catch (IOException ignore) {
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
}
/**
* Notifies all with the notify permission.
*
* @param msg
* Notifies all with the worldguard.notify permission.
* This will check both superperms and WEPIF,
* but makes sure WEPIF checks don't result in duplicate notifications
*
* @param msg The notification to broadcast
*/
public void broadcastNotification(String msg) {
getServer().broadcast(msg, "worldguard.notify");
Set<Permissible> subs = getServer().getPluginManager().getPermissionSubscriptions("worldguard.notify");
for (Player player : getServer().getOnlinePlayers()) {
if (hasPermission(player, "worldguard.notify")) {
if (!(subs.contains(player) && player.hasPermission("worldguard.notify")) &&
hasPermission(player, "worldguard.notify")) { // Make sure the player wasn't already broadcasted to.
player.sendMessage(msg);
}
}
getLogger().info(msg);
}
/**
* Forgets a player.
*
* @param player
*
* @param player The player to remove state information for
*/
public void forgetPlayer(Player player) {
flagStateManager.forget(player);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param loc
* @return
*
* @param player The player to check.
* @param loc The location to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.Location)
* @return whether {@code player} can build at {@code loc}
*/
public boolean canBuild(Player player, Location loc) {
return getGlobalRegionManager().canBuild(player, loc);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param block
* @return
*
* @param player The player to check
* @param block The block to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.block.Block)
* @return whether {@code player} can build at {@code block}'s location
*/
public boolean canBuild(Player player, Block block) {
return getGlobalRegionManager().canBuild(player, block);
@@ -754,9 +819,17 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Replace macros in the text.
*
* @param sender
* @param message
* @return
* The macros replaced are as follows:
* %name%: The name of {@code sender}. See {@link #toName(org.bukkit.command.CommandSender)}
* %id%: The unique name of the sender. See {@link #toUniqueName(org.bukkit.command.CommandSender)}
* %online%: The number of players currently online on the server
* If {@code sender} is a Player:
* %world%: The name of the world {@code sender} is located in
* %health%: The health of {@code sender}. See {@link org.bukkit.entity.Player#getHealth()}
*
* @param sender The sender to check
* @param message The message to replace macros in
* @return The message with macros replaced
*/
public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
@@ -0,0 +1,38 @@
package com.sk89q.worldguard.bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* @author zml2008
*/
public class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
}
@@ -0,0 +1,178 @@
// $Id$
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* All rights reserved.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.FlagStateManager.PlayerFlagState;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
Vehicle vehicle = event.getVehicle();
Entity destroyer = event.getAttacker();
if (!(destroyer instanceof Player)) return; // don't care
Player player = (Player) destroyer;
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
Vector pt = toVector(vehicle.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.DESTROY_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to destroy vehicles here.");
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
if (vehicle.getPassenger() == null
|| !(vehicle.getPassenger() instanceof Player)) return;
Player player = (Player) vehicle.getPassenger();
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// unfortunate code duplication
if (wcfg.useRegions) {
// Did we move a block?
if (event.getFrom().getBlockX() != event.getTo().getBlockX()
|| event.getFrom().getBlockY() != event.getTo().getBlockY()
|| event.getFrom().getBlockZ() != event.getTo().getBlockZ()) {
PlayerFlagState state = plugin.getFlagStateManager().getState(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
boolean hasBypass = plugin.getGlobalRegionManager().hasBypass(player, world);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Vector pt = new Vector(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
boolean entryAllowed = set.allows(DefaultFlag.ENTRY, localPlayer);
if (!hasBypass && !entryAllowed) {
vehicle.setVelocity(new org.bukkit.util.Vector(0,0,0));
vehicle.teleport(event.getFrom());
return;
}
// Have to set this state
if (state.lastExitAllowed == null) {
state.lastExitAllowed = mgr.getApplicableRegions(toVector(event.getFrom()))
.allows(DefaultFlag.EXIT, localPlayer);
}
boolean exitAllowed = set.allows(DefaultFlag.EXIT, localPlayer);
if (!hasBypass && exitAllowed && !state.lastExitAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to leave this area.");
vehicle.setVelocity(new org.bukkit.util.Vector(0,0,0));
vehicle.teleport(event.getFrom());
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE, localPlayer);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE, localPlayer);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER, localPlayer);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE, localPlayer);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
}
if ((notifyLeave == null || !notifyLeave)
&& state.notifiedForLeave != null && state.notifiedForLeave) {
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " left NOTIFY region");
}
if (notifyEnter != null && notifyEnter && (state.notifiedForEnter == null
|| !state.notifiedForEnter)) {
StringBuilder regionList = new StringBuilder();
for (ProtectedRegion region : set) {
if (regionList.length() != 0) {
regionList.append(", ");
}
regionList.append(region.getId());
}
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
+ regionList);
}
state.lastGreeting = greeting;
state.lastFarewell = farewell;
state.notifiedForEnter = notifyEnter;
state.notifiedForLeave = notifyLeave;
state.lastExitAllowed = exitAllowed;
state.lastWorld = event.getTo().getWorld();
state.lastBlockX = event.getTo().getBlockX();
state.lastBlockY = event.getTo().getBlockY();
state.lastBlockZ = event.getTo().getBlockZ();
}
}
}
}
@@ -19,27 +19,20 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.Location;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.weather.WeatherListener;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.logging.Logger;
public class WorldGuardWeatherListener extends WeatherListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardWeatherListener implements Listener {
/**
* Plugin.
@@ -49,41 +42,18 @@ public class WorldGuardWeatherListener extends WeatherListener {
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("LIGHTNING_STRIKE", Priority.High);
registerEvent("THUNDER_CHANGE", Priority.High);
registerEvent("WEATHER_CHANGE", Priority.High);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -98,12 +68,8 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -118,12 +84,8 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
}
@Override
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -145,5 +107,4 @@ public class WorldGuardWeatherListener extends WeatherListener {
}
}
}
}
@@ -5,27 +5,21 @@
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.event.world.WorldLoadEvent;
import java.util.logging.Logger;
public class WorldGuardWorldListener extends WorldListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public class WorldGuardWorldListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -35,30 +29,10 @@ public class WorldGuardWorldListener extends WorldListener {
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("CHUNK_LOAD", Event.Priority.Normal);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Event.Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Called when a chunk is loaded.
*/
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -66,19 +40,44 @@ public class WorldGuardWorldListener extends WorldListener {
int removed = 0;
for (Entity entity : event.getChunk().getEntities()) {
if (entity instanceof Item
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player))) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info("WG Halt-Act: " + removed + " entities (>50) auto-removed from "
plugin.getLogger().info("Halt-Act: " + removed + " entities (>50) auto-removed from "
+ event.getChunk().toString());
}
}
}
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
initWorld(event.getWorld());
}
/**
* Initialize the settings for the specified world
* @see WorldConfiguration#alwaysRaining
* @see WorldConfiguration#disableWeather
* @see WorldConfiguration#alwaysThundering
* @see WorldConfiguration#disableThunder
* @param world The specified world
*/
public void initWorld(World world) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
world.setStorm(false);
}
if (wcfg.alwaysThundering && !wcfg.disableThunder) {
world.setThundering(true);
} else if (wcfg.disableThunder && !wcfg.alwaysThundering) {
world.setStorm(false);
}
}
}
@@ -23,22 +23,26 @@ import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldedit.blocks.ItemType;
public class GeneralCommands {
private final WorldGuardPlugin plugin;
public GeneralCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"god"},
usage = "[player]",
desc = "Enable godmode on a player",
flags = "s", min = 0, max = 1)
public static void god(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("deprecation")
@Command(aliases = {"god"}, usage = "[player]",
desc = "Enable godmode on a player", flags = "s", max = 1)
public void god(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
@@ -81,12 +85,10 @@ public class GeneralCommands {
}
}
@Command(aliases = {"ungod"},
usage = "[player]",
desc = "Disable godmode on a player",
flags = "s", min = 0, max = 1)
public static void ungod(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("deprecation")
@Command(aliases = {"ungod"}, usage = "[player]",
desc = "Disable godmode on a player", flags = "s", max = 1)
public void ungod(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
@@ -128,12 +130,8 @@ public class GeneralCommands {
}
}
@Command(aliases = {"heal"},
usage = "[player]",
desc = "Heal a player",
flags = "s", min = 0, max = 1)
public static void heal(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"heal"}, usage = "[player]", desc = "Heal a player", flags = "s", max = 1)
public void heal(CommandContext args,CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
@@ -153,6 +151,7 @@ public class GeneralCommands {
for (Player player : targets) {
player.setHealth(20);
player.setFoodLevel(20);
// Tell the user
if (player.equals(sender)) {
@@ -174,12 +173,8 @@ public class GeneralCommands {
}
}
@Command(aliases = {"slay"},
usage = "[player]",
desc = "Slay a player",
flags = "s", min = 0, max = 1)
public static void slay(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"slay"}, usage = "[player]", desc = "Slay a player", flags = "s", max = 1)
public void slay(CommandContext args, CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
@@ -220,13 +215,9 @@ public class GeneralCommands {
}
}
@Command(aliases = {"locate"},
usage = "[player]",
desc = "Locate a player",
flags = "", min = 0, max = 1)
@Command(aliases = {"locate"}, usage = "[player]", desc = "Locate a player", max = 1)
@CommandPermissions({"worldguard.locate"})
public static void locate(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void locate(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
@@ -242,15 +233,13 @@ public class GeneralCommands {
}
}
@Command(aliases = {"stack"},
usage = "",
desc = "Stack items",
flags = "", min = 0, max = 0)
@Command(aliases = {"stack", ";"}, usage = "", desc = "Stack items", max = 0)
@CommandPermissions({"worldguard.stack"})
public static void stack(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stack(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
boolean ignoreMax = plugin.hasPermission(player, "worldguard.stack.illegitimate");
boolean ignoreDamaged = plugin.hasPermission(player, "worldguard.stack.damaged");
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
@@ -262,17 +251,14 @@ public class GeneralCommands {
// Avoid infinite stacks and stacks with durability
if (item == null || item.getAmount() <= 0
|| ItemType.shouldNotStack(item.getTypeId())) {
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
// Ignore buckets
if (item.getTypeId() >= 325 && item.getTypeId() <= 327) {
continue;
}
int max = ignoreMax ? 64 : item.getMaxStackSize();
if (item.getAmount() < 64) {
int needed = 64 - item.getAmount(); // Number of needed items until 64
if (item.getAmount() < max) {
int needed = max - item.getAmount(); // Number of needed items until max
// Find another stack of the same type
for (int j = i + 1; j < len; j++) {
@@ -280,15 +266,16 @@ public class GeneralCommands {
// Avoid infinite stacks and stacks with durability
if (item2 == null || item2.getAmount() <= 0
|| ItemType.shouldNotStack(item.getTypeId())) {
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
// Same type?
// Blocks store their color in the damage value
if (item2.getTypeId() == item.getTypeId() &&
(!ItemType.usesDamageValue(item.getTypeId())
|| item.getDurability() == item2.getDurability())) {
((!ItemType.usesDamageValue(item.getTypeId()) && ignoreDamaged)
|| item.getDurability() == item2.getDurability()) &&
item.getEnchantments().equals(item2.getEnchantments())) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(64);
@@ -20,21 +20,25 @@
package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ProtectionCommands {
@Command(aliases = {"region"},
desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public static void region(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@SuppressWarnings("unused")
private final WorldGuardPlugin plugin;
public ProtectionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"worldguard"},
desc = "WorldGuard commands")
@Command(aliases = {"region", "regions", "rg"}, desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public void region(CommandContext args, CommandSender sender) {}
@Command(aliases = {"worldguard", "wg"}, desc = "WorldGuard commands")
@NestedCommand({WorldGuardCommands.class})
public static void worldGuard(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
}
public void worldGuard(CommandContext args, CommandSender sender) {}
}
File diff suppressed because it is too large. Load diff
@@ -19,30 +19,35 @@
package com.sk89q.worldguard.bukkit.commands;
import java.io.IOException;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.RegionUtil;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
// @TODO: A lot of code duplication here! Need to fix.
public class RegionMemberCommands {
private final WorldGuardPlugin plugin;
public RegionMemberCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"addmember", "addmember"},
usage = "<id> <members...>",
desc = "Add a member to a region",
flags = "", min = 2, max = -1)
public static void addMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"addmember", "addmember"}, usage = "<id> <members...>",
desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -56,7 +61,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -65,25 +72,22 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
}
RegionUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"},
usage = "<id> <owners...>",
desc = "Add an owner to a region",
flags = "", min = 2, max = -1)
public static void addOwner(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"addowner", "addowner"}, usage = "<id> <owners...>",
desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -97,34 +101,46 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
id = region.getId();
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (flag != null && flag && owners != null && owners.size() == 0) {
if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
if (maxRegionCount >= 0 && mgr.getRegionCountOfPlayer(localPlayer)
>= maxRegionCount) {
throw new CommandException("You already own the maximum allowed amount of regions.");
}
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
}
RegionUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
@@ -138,7 +154,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -147,24 +165,22 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
}
RegionUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeOwner(CommandContext args, WorldGuardPlugin plugin,
@Command(aliases = {"removeowner", "remowner"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeOwner(CommandContext args,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
@@ -179,7 +195,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -188,15 +206,15 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
}
RegionUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@@ -19,23 +19,32 @@
package com.sk89q.worldguard.bukkit.commands;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.entity.*;
public class ToggleCommands {
private final WorldGuardPlugin plugin;
@Command(aliases = {"stopfire"},
usage = "[<world>]", desc = "Disables all fire spread temporarily",
flags = "", min = 0, max = 1)
public ToggleCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"stopfire"}, usage = "[<world>]",
desc = "Disables all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void stopFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stopFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
@@ -61,12 +70,10 @@ public class ToggleCommands {
wcfg.fireSpreadDisableToggle = true;
}
@Command(aliases = {"allowfire"},
usage = "[<world>]", desc = "Allows all fire spread temporarily",
flags = "", min = 0, max = 1)
@Command(aliases = {"allowfire"}, usage = "[<world>]",
desc = "Allows all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void allowFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void allowFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
@@ -90,12 +97,10 @@ public class ToggleCommands {
wcfg.fireSpreadDisableToggle = false;
}
@Command(aliases = {"halt-activity"},
usage = "", desc = "Attempts to cease as much activity in order to stop lag",
flags = "c", min = 0, max = 0)
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "c", max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public static void stopLag(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void stopLag(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager configManager = plugin.getGlobalStateManager();
@@ -115,10 +120,7 @@ public class ToggleCommands {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (entity instanceof Item
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player))) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
@@ -23,9 +23,11 @@ import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
@@ -37,26 +39,23 @@ import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
public class WorldGuardCommands {
private final WorldGuardPlugin plugin;
@Command(aliases = {"version"},
usage = "",
desc = "Get the WorldGuard version",
flags = "", min = 0, max = 0)
public static void version(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public WorldGuardCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"version"}, desc = "Get the WorldGuard version", max = 0)
public void version(CommandContext args, CommandSender sender) throws CommandException {
sender.sendMessage(ChatColor.YELLOW
+ "WorldGuard " + plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "http://www.sk89q.com");
}
@Command(aliases = {"reload"},
usage = "",
desc = "Reload WorldGuard configuration",
flags = "", min = 0, max = 0)
@Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
@CommandPermissions({"worldguard.reload"})
public static void relload(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
public void reload(CommandContext args, CommandSender sender) throws CommandException {
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
@@ -84,13 +83,9 @@ public class WorldGuardCommands {
}
}
@Command(aliases = {"report"},
usage = "",
desc = "Writes a report on WorldGuard",
flags = "p", min = 0, max = 0)
@Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({"worldguard.report"})
public static void report(CommandContext args, WorldGuardPlugin plugin,
final CommandSender sender) throws CommandException {
public void report(CommandContext args, final CommandSender sender) throws CommandException {
File dest = new File(plugin.getDataFolder(), "report.txt");
ReportWriter report = new ReportWriter(plugin);
@@ -122,4 +117,21 @@ public class WorldGuardCommands {
}
}
@Command(aliases = {"flushstates", "clearstates"},
usage = "[player]", desc = "Flush the state manager", max = 1)
@CommandPermissions("worldguard.flushstates")
public void flushStates(CommandContext args, CommandSender sender) throws CommandException {
if (args.argsLength() == 0) {
plugin.getFlagStateManager().forgetAll();
sender.sendMessage("Cleared all states.");
} else {
Player player = plugin.getServer().getPlayer(args.getString(0));
if (player != null) {
plugin.getFlagStateManager().forget(player);
sender.sendMessage("Cleared states for player \"" + player.getName() + "\".");
}
}
}
}
@@ -31,9 +31,9 @@ public interface ChestProtection {
/**
* Returns whether a block is protected.
*
* @param block
* @param player
* @return
* @param block The block to check
* @param player The player to check
* @return Whether the block is protected for player
*/
public boolean isProtected(Block block, Player player);
@@ -41,27 +41,37 @@ public interface ChestProtection {
* Returns whether a location where a chest block is trying to be created
* is protected.
*
* @param block
* @param player
* @return
* @param block The block to check
* @param player The player to check
* @return Whether {@code player} can place a block at the specified block
*/
public boolean isProtectedPlacement(Block block, Player player);
/**
* Returns whether an adjacent chest is protected.
*
* @param searchBlock
* @param player
* @return
* @param searchBlock The block to check
* @param player The player to check
* @return Whether {@code searchBlock} is protected from access by {@code player}
*/
public boolean isAdjacentChestProtected(Block searchBlock, Player player);
/**
* Returns whether a material is a chest.
*
* @param material
* @return
*
* @param material The material to check
* @deprecated see {@link #isChest(int)}
* @return {@link #isChest(int)}
*/
@Deprecated
public boolean isChest(Material material);
/**
* Returns whether a material is a chest.
*
* @param type The type to check
* @return Whether type is a 'chest' (block that can be protected)
*/
public boolean isChest(int type);
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.chest;
import com.sk89q.worldedit.blocks.BlockID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@@ -33,10 +34,10 @@ import org.bukkit.entity.Player;
public class SignChestProtection implements ChestProtection {
public boolean isProtected(Block block, Player player) {
if (isChest(block.getType())) {
if (isChest(block.getTypeId())) {
Block below = block.getRelative(0, -1, 0);
return isProtectedSignAround(below, player);
} else if (block.getType() == Material.SIGN_POST) {
} else if (block.getTypeId() == BlockID.SIGN_POST) {
return isProtectedSignAndChestBinary(block, player);
} else {
Block above = block.getRelative(0, 1, 0);
@@ -56,23 +57,23 @@ public class SignChestProtection implements ChestProtection {
side = searchBlock;
res = isProtectedSign(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
return false;
}
@@ -106,7 +107,7 @@ public class SignChestProtection implements ChestProtection {
}
private Boolean isProtectedSignAndChest(Block block, Player player) {
if (!isChest(block.getRelative(0, 1, 0).getType())) {
if (!isChest(block.getRelative(0, 1, 0).getTypeId())) {
return null;
}
return isProtectedSign(block, player);
@@ -114,7 +115,7 @@ public class SignChestProtection implements ChestProtection {
private boolean isProtectedSignAndChestBinary(Block block, Player player) {
Boolean res = isProtectedSignAndChest(block, player);
if (res == null || res == false) {
if (res == null || !res) {
return false;
}
return true;
@@ -126,31 +127,36 @@ public class SignChestProtection implements ChestProtection {
side = searchBlock;
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
return false;
}
@Deprecated
public boolean isChest(Material material) {
return material == Material.CHEST
|| material == Material.DISPENSER
|| material == Material.FURNACE
|| material == Material.BURNING_FURNACE;
return isChest(material.getId());
}
public boolean isChest(int type) {
return type == BlockID.CHEST
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE;
}
}
@@ -19,10 +19,14 @@
package com.sk89q.worldguard.domains;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
public class DefaultDomain implements Domain {
@@ -66,27 +70,35 @@ public class DefaultDomain implements Domain {
return players;
}
@Override
public boolean contains(LocalPlayer player) {
if (players.contains(player.getName().toLowerCase())) {
if (contains(player.getName())) {
return true;
}
for (String group : groups) {
if (player.hasGroup(group)) {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
return players.contains(playerName.toLowerCase());
}
public int size() {
return groups.size() + players.size();
}
public String toPlayersString() {
StringBuilder str = new StringBuilder();
for (Iterator<String> it = players.iterator(); it.hasNext(); ) {
List<String> output = new ArrayList<String>(players);
Collections.sort(output, String.CASE_INSENSITIVE_ORDER);
for (Iterator<String> it = output.iterator(); it.hasNext();) {
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
@@ -5,9 +5,18 @@ import com.sk89q.worldguard.LocalPlayer;
public interface Domain {
/**
* Returns true if a domain contains a player.
*
* @param player
* @return
*
* @param player The player to check
* @return whether this domain contains {@code player}
*/
public boolean contains(LocalPlayer player);
boolean contains(LocalPlayer player);
/**
* Returns true if a domain contains a player.<br />
* This method doesn't check for groups!
*
* @param playerName The name of the player to check
* @return whether this domain contains a player by that name
*/
boolean contains(String playerName);
}
@@ -19,37 +19,49 @@
package com.sk89q.worldguard.domains;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
public class DomainCollection implements Domain {
private Set<Domain> domains;
public DomainCollection() {
domains = new LinkedHashSet<Domain>();
}
public void add(Domain domain) {
domains.add(domain);
}
public void remove(Domain domain) {
domains.remove(domain);
}
public int size() {
return domains.size();
}
@Override
public boolean contains(LocalPlayer player) {
for (Domain domain : domains) {
if (domain.contains(player)) {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
for (Domain domain : domains) {
if (domain.contains(playerName)) {
return true;
}
}
return false;
}
}
@@ -20,21 +20,22 @@
package com.sk89q.worldguard.domains;
import java.util.Arrays;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
public class GroupDomain implements Domain {
private Set<String> groups;
public GroupDomain() {
this.groups = new LinkedHashSet<String>();
}
public GroupDomain(String[] groups) {
this.groups = new LinkedHashSet<String>(Arrays.asList(groups));
}
public void addGroup(String name) {
groups.add(name);
}
@@ -45,12 +46,16 @@ public class GroupDomain implements Domain {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
return false; // GroupDomains can't contain player names.
}
public int size() {
return groups.size();
}
}
@@ -19,35 +19,40 @@
package com.sk89q.worldguard.domains;
import java.util.Set;
import java.util.HashSet;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
public class PlayerDomain implements Domain {
private Set<String> players;
public PlayerDomain() {
this.players = new HashSet<String>();
}
public PlayerDomain(String[] players) {
this.players = new HashSet<String>();
for (String name : players) {
this.players.add(name.toLowerCase());
}
}
public void addPlayer(String name) {
players.add(name.toLowerCase());
}
public boolean contains(LocalPlayer player) {
return players.contains(player.getName().toLowerCase());
return contains(player.getName());
}
@Override
public boolean contains(String playerName) {
return players.contains(playerName.toLowerCase());
}
public int size() {
return players.size();
}
}
@@ -18,9 +18,6 @@
*/
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
@@ -28,7 +25,15 @@ import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* Represents a set of regions for a particular point or area and the rules
@@ -48,8 +53,8 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Construct the object.
*
* @param applicable
* @param globalRegion
* @param applicable The regions contained in this set
* @param globalRegion The global region, set aside for special handling.
*/
public ApplicableRegionSet(Collection<ProtectedRegion> applicable,
ProtectedRegion globalRegion) {
@@ -60,19 +65,26 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Checks if a player can build in an area.
*
* @param player
* @param player The player to chec
* @return build ability
*/
public boolean canBuild(LocalPlayer player) {
return internalGetState(DefaultFlag.BUILD, player, null, null);
return internalGetState(DefaultFlag.BUILD, player, null);
}
public boolean canConstruct(LocalPlayer player) {
final RegionGroup flag = getFlag(DefaultFlag.CONSTRUCT, player);
return RegionGroupFlag.isMember(this, flag, player);
}
/**
* Checks if a player can use buttons and such in an area.
*
* @param player
* @param player The player to check
* @return able to use items
* @deprecated This method seems to be the opposite of its name
*/
@Deprecated
public boolean canUse(LocalPlayer player) {
return !allows(DefaultFlag.USE, player)
&& !canBuild(player);
@@ -89,7 +101,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, null, null);
return internalGetState(flag, null, null);
}
/**
@@ -104,7 +116,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, flag.getGroupFlag(), player);
return internalGetState(flag, null, player);
}
/**
@@ -145,12 +157,10 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
*
* @param flag flag to check
* @param player null to not check owners and members
* @param groupFlag group flag to check
* @param groupPlayer player to use for the group flag check
* @return
* @return the allow/deny state for the flag
*/
private boolean internalGetState(StateFlag flag, LocalPlayer player,
RegionGroupFlag groupFlag,
LocalPlayer groupPlayer) {
boolean found = false;
boolean hasFlagDefined = false;
@@ -225,10 +235,10 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
}
// Check group permissions
if (groupPlayer != null && groupFlag != null) {
RegionGroupFlag.RegionGroup group = region.getFlag(groupFlag);
if (groupPlayer != null && flag.getRegionGroupFlag() != null) {
RegionGroup group = region.getFlag(flag.getRegionGroupFlag());
if (group == null) {
group = groupFlag.getDefault();
group = flag.getRegionGroupFlag().getDefault();
}
if (!RegionGroupFlag.isMember(region, group, groupPlayer)) {
continue;
@@ -272,16 +282,16 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
found = true;
}
return found == false ? def :
return !found ? def :
(allowed || (player != null && needsClear.size() == 0));
}
/**
* Clear a region's parents for isFlagAllowed().
*
* @param needsClear
* @param hasCleared
* @param region
* @param needsClear The regions that should be cleared
* @param hasCleared The regions already cleared
* @param region The region to start from
*/
private void clearParents(Set<ProtectedRegion> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
@@ -296,18 +306,30 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
}
}
/**
* @see #getFlag(com.sk89q.worldguard.protection.flags.Flag, com.sk89q.worldguard.LocalPlayer)
* @param flag flag to check
* @return value of the flag
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
return getFlag(flag, null);
}
/**
* Gets the value of a flag. Do not use this for state flags
* (use {@link #allows(StateFlag, LocalPlayer)} for that).
*
* @param flag flag to check
* @param groupPlayer player to check {@link RegionGroup}s against
* @return value of the flag
* @throws IllegalArgumentException if a StateFlag is given
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
public <T extends Flag<V>, V> V getFlag(T flag, LocalPlayer groupPlayer) {
/*
if (flag instanceof StateFlag) {
throw new IllegalArgumentException("Cannot use StateFlag with getFlag()");
}
*/
int lastPriority = 0;
boolean found = false;
@@ -325,6 +347,17 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
break;
}
// Check group permissions
if (groupPlayer != null && flag.getRegionGroupFlag() != null) {
RegionGroup group = region.getFlag(flag.getRegionGroupFlag());
if (group == null) {
group = flag.getRegionGroupFlag().getDefault();
}
if (!RegionGroupFlag.isMember(region, group, groupPlayer)) {
continue;
}
}
if (hasCleared.contains(region)) {
// Already cleared, so do nothing
} else if (region.getFlag(flag) != null){
@@ -341,6 +374,10 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
try {
return needsClear.values().iterator().next();
} catch (NoSuchElementException e) {
if (globalRegion != null) {
V gFlag = globalRegion.getFlag(flag);
if (gFlag != null) return gFlag;
}
return null;
}
}
@@ -348,9 +385,9 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Clear a region's parents for getFlag().
*
* @param needsClear
* @param hasCleared
* @param region
* @param needsClear The regions that should be cleared
* @param hasCleared The regions already cleared
* @param region The region to start from
*/
private void clearParents(Map<ProtectedRegion, ?> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
@@ -368,7 +405,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Get the number of regions that are included.
*
* @return
* @return the size of this ApplicbleRegionSet
*/
public int size() {
return applicable.size();
@@ -376,8 +413,6 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Get an iterator of affected regions.
*
* @return
*/
public Iterator<ProtectedRegion> iterator() {
return applicable.iterator();
@@ -19,51 +19,54 @@
package com.sk89q.worldguard.protection;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* This class keeps track of region information for every world. It loads
* world region information as needed.
*
*
* @author sk89q
* @author Redecouverte
*/
public class GlobalRegionManager {
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Reference to the global configuration.
*/
private ConfigurationManager config;
/**
* Map of managers per-world.
*/
private HashMap<String, RegionManager> managers;
/**
* Stores the list of modification dates for the world files. This allows
* WorldGuard to reload files as needed.
@@ -72,8 +75,8 @@ public class GlobalRegionManager {
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public GlobalRegionManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -89,12 +92,12 @@ public class GlobalRegionManager {
managers.clear();
lastModified.clear();
}
/**
* Get the path for a world's regions file.
*
* @param name
* @return
*
* @param name The name of the world
* @return The region file path for a world's region file
*/
protected File getPath(String name) {
return new File(plugin.getDataFolder(),
@@ -103,14 +106,13 @@ public class GlobalRegionManager {
/**
* Unload region information for a world.
*
* @param name
*
* @param name The name of the world to unload
*/
public void unload(String name) {
RegionManager manager = managers.get(name);
RegionManager manager = managers.remove(name);
if (manager != null) {
managers.remove(name);
lastModified.remove(name);
}
}
@@ -125,37 +127,56 @@ public class GlobalRegionManager {
/**
* Load region information for a world.
*
* @param world
* @return
*
* @param world The world to load a RegionManager for
* @return the loaded RegionManager
*/
public RegionManager load(World world) {
String name = world.getName();
File file = getPath(name);
ProtectionDatabase database;
File file = null;
try {
if (!config.useSqlDatabase) {
file = getPath(name);
database = new YAMLDatabase(file, plugin.getLogger());
// Store the last modification date so we can track changes
lastModified.put(name, file.lastModified());
} else {
database = new MySQLDatabase(config, name, plugin.getLogger());
}
// Create a manager
RegionManager manager = new FlatRegionManager(new YAMLDatabase(file));
RegionManager manager = new FlatRegionManager(database);
managers.put(name, manager);
manager.load();
logger.info("WorldGuard: " + manager.getRegions().size()
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
// Store the last modification date so we can track changes
lastModified.put(name, file.lastModified());
return manager;
} catch (ProtectionDatabaseException e) {
String logStr = "Failed to load regions from ";
if (config.useSqlDatabase) {
logStr += "SQL Database <" + config.sqlDsn + "> ";
} else {
logStr += "file \"" + file + "\" ";
}
plugin.getLogger().log(Level.SEVERE, logStr + " : " + e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions from file "
+ file.getAbsolutePath() + " : " + e.getMessage());
plugin.getLogger().log(Level.SEVERE, "Error loading regions for world \""
+ name + "\": " + e.toString() + "\n\t" + e.getMessage());
e.printStackTrace();
}
// @TODO: THIS CREATES PROBLEMS!!
// @TODO: THIS CREATES PROBLEMS!!one!!1!!eleven!!1!!!
return null;
}
/**
* Preloads region managers for all worlds.
*/
@@ -171,11 +192,13 @@ public class GlobalRegionManager {
* have changed.
*/
public void reloadChanged() {
if (config.useSqlDatabase) return;
for (String name : managers.keySet()) {
File file = getPath(name);
Long oldDate = lastModified.get(name);
if (oldDate == null) {
oldDate = 0L;
}
@@ -183,21 +206,21 @@ public class GlobalRegionManager {
try {
if (file.lastModified() > oldDate) {
World world = plugin.getServer().getWorld(name);
if (world != null) {
load(world);
}
}
} catch (Exception e) {
} catch (Exception ignore) {
}
}
}
/**
* Get the region manager for a particular world.
*
* @param world
* @return
*
* @param world The world to get a RegionManager for
* @return The region manager.
*/
public RegionManager get(World world) {
RegionManager manager = managers.get(world.getName());
@@ -212,53 +235,53 @@ public class GlobalRegionManager {
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
* @param player The player to check
* @param world The world to check for
* @return Whether {@code player} has bypass permission for {@code world}
*/
public boolean hasBypass(LocalPlayer player, World world) {
return player.hasPermission("worldguard.region.bypass."
+ world.getName());
}
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
*
* @param player The player to check
* @param world The world to check
* @return Whether {@code player} has bypass permission for {@code world}
*/
public boolean hasBypass(Player player, World world) {
return plugin.hasPermission(player, "worldguard.region.bypass."
+ world.getName());
+ world.getName());
}
/**
* Check if a player has permission to build at a block.
*
* @param player
* @param block
* @return
*
* @param player The player to check
* @param block The block to check at
* @return Whether {@code player} can build at {@code block}'s location
*/
public boolean canBuild(Player player, Block block) {
return canBuild(player, block.getLocation());
}
/**
* Check if a player has permission to build at a location.
*
* @param player
* @param loc
* @return
*
* @param player The player to check
* @param loc The location to check
* @return Whether {@code player} can build at {@code loc}
*/
public boolean canBuild(Player player, Location loc) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!hasBypass(player, world)) {
@@ -272,23 +295,65 @@ public class GlobalRegionManager {
return true;
}
/**
* Checks to see whether a flag is allowed.
*
* @param flag
* @param loc
* @return
*/
public boolean allows(StateFlag flag, Location loc) {
public boolean canConstruct(Player player, Block block) {
return canConstruct(player, block.getLocation());
}
public boolean canConstruct(Player player, Location loc) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!hasBypass(player, world)) {
RegionManager mgr = get(world);
final ApplicableRegionSet applicableRegions = mgr.getApplicableRegions(BukkitUtil.toVector(loc));
if (!applicableRegions.canBuild(localPlayer)) {
return false;
}
if (!applicableRegions.canConstruct(localPlayer)) {
return false;
}
}
return true;
}
/**
* Checks to see whether a flag is allowed.
*
* @see #allows(com.sk89q.worldguard.protection.flags.StateFlag, org.bukkit.Location, com.sk89q.worldguard.LocalPlayer)
* @param flag The flag to check
* @param loc The location to check the flag at
* @return Whether the flag is allowed
*/
public boolean allows(StateFlag flag, Location loc) {
return allows(flag, loc, null);
}
/**
* Checks to see whether a flag is allowed.
*
* @param flag The flag to check
* @param loc The location to check the flag at
* @param player The player to check for the flag's {@link com.sk89q.worldguard.protection.flags.RegionGroup}
* @return Whether the flag is allowed
*/
public boolean allows(StateFlag flag, Location loc, LocalPlayer player) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
return mgr.getApplicableRegions(toVector(loc)).allows(flag);
return mgr.getApplicableRegions(toVector(loc)).allows(flag, player);
}
}
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.protection.databases;
import java.io.IOException;
import com.sk89q.worldguard.protection.managers.RegionManager;
public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
@@ -27,9 +26,9 @@ public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
/**
* Load the list of regions into a region manager.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void load(RegionManager manager) throws IOException {
public void load(RegionManager manager) throws ProtectionDatabaseException {
load();
manager.setRegions(getRegions());
}
@@ -37,9 +36,9 @@ public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
/**
* Save the list of regions from a region manager.
*
* @throws IOException
* @throws ProtectionDatabaseException
*/
public void save(RegionManager manager) throws IOException {
public void save(RegionManager manager) throws ProtectionDatabaseException {
setRegions(manager.getRegions());
save();
}
@@ -19,89 +19,108 @@
package com.sk89q.worldguard.protection.databases;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import au.com.bytecode.opencsv.CSVReader;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.ArrayReader;
/**
* Represents a protected area database that uses CSV files.
*
*
* @author sk89q
*/
public class CSVDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private static final Map<String, StateFlag> legacyFlagCodes = new HashMap<String, StateFlag>();
static {
legacyFlagCodes.put("z", DefaultFlag.PASSTHROUGH);
legacyFlagCodes.put("b", DefaultFlag.BUILD);
legacyFlagCodes.put("p", DefaultFlag.PVP);
legacyFlagCodes.put("m", DefaultFlag.MOB_DAMAGE);
legacyFlagCodes.put("c", DefaultFlag.CREEPER_EXPLOSION);
legacyFlagCodes.put("t", DefaultFlag.TNT);
legacyFlagCodes.put("l", DefaultFlag.LIGHTER);
legacyFlagCodes.put("f", DefaultFlag.FIRE_SPREAD);
legacyFlagCodes.put("F", DefaultFlag.LAVA_FIRE);
legacyFlagCodes.put("C", DefaultFlag.CHEST_ACCESS);
}
private final Logger logger;
/**
* References the CSV file.
*/
private File file;
private final File file;
/**
* Holds the list of regions.
*/
private Map<String,ProtectedRegion> regions;
/**
* Construct the database with a path to a file. No file is read or
* written at this time.
*
* @param file
*
* @param file The file in CSV format containing the region database
* @param logger The logger to log errors to
*/
public CSVDatabase(File file) {
public CSVDatabase(File file, Logger logger) {
this.file = file;
this.logger = logger;
}
/**
* Saves the database.
*/
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
* Load the database from file.
*/
public void load() throws IOException {
public void load() throws ProtectionDatabaseException {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
CSVReader reader = new CSVReader(new FileReader(file));
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(file));
String[] line;
while ((line = reader.readNext()) != null) {
if (line.length < 2) {
logger.warning("Invalid region definition: " + line);
continue;
}
String id = line[0].toLowerCase().replace(".", "");
String type = line[1];
ArrayReader<String> entries = new ArrayReader<String>(line);
if (type.equalsIgnoreCase("cuboid")) {
if (line.length < 8) {
logger.warning("Invalid region definition: " + line);
continue;
}
Vector pt1 = new Vector(
Integer.parseInt(line[2]),
Integer.parseInt(line[3]),
@@ -113,12 +132,12 @@ public class CSVDatabase extends AbstractProtectionDatabase {
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
int priority = entries.get(8) == null ? 0 : Integer.parseInt(entries.get(8));
String ownersData = entries.get(9);
String flagsData = entries.get(10);
//String enterMessage = nullEmptyString(entries.get(11));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
parseFlags(region, flagsData);
@@ -136,7 +155,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
int priority = entries.get(8) == null ? 0 : Integer.parseInt(entries.get(8));
String parentId = entries.get(9);
String ownersData = entries.get(10);
@@ -144,27 +163,29 @@ public class CSVDatabase extends AbstractProtectionDatabase {
String flagsData = entries.get(12);
//String enterMessage = nullEmptyString(entries.get(13));
//String leaveMessage = nullEmptyString(entries.get(14));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
parseFlags(region, flagsData);
region.setOwners(this.parseDomains(ownersData));
region.setMembers(this.parseDomains(membersData));
regions.put(id, region);
// Link children to parents later
if (parentId.length() > 0) {
parentSets.put(region, parentId);
}
}
}
} catch (IOException e) {
throw new ProtectionDatabaseException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
for (Map.Entry<ProtectedRegion, String> entry : parentSets.entrySet()) {
ProtectedRegion parent = regions.get(entry.getValue());
if (parent != null) {
@@ -178,33 +199,33 @@ public class CSVDatabase extends AbstractProtectionDatabase {
logger.warning("Unknown region parent: " + entry.getValue());
}
}
this.regions = regions;
}
/**
* Used to parse the specified domain in the CSV file.
*
* @param data
* @return
*
* @param data The domain data as a string
* @return The domain data as a DefaultDomain
*/
private DefaultDomain parseDomains(String data) {
if (data == null) {
return new DefaultDomain();
}
DefaultDomain domain = new DefaultDomain();
Pattern pattern = Pattern.compile("^([A-Za-z]):(.*)$");
String[] parts = data.split(",");
for (String part : parts) {
if (part.trim().length() == 0) {
continue;
}
Matcher matcher = pattern.matcher(part);
if (!matcher.matches()) {
logger.warning("Invalid owner specification: " + part);
continue;
@@ -221,22 +242,22 @@ public class CSVDatabase extends AbstractProtectionDatabase {
logger.warning("Unknown owner specification: " + type);
}
}
return domain;
}
/**
* Used to parse the list of flags.
*
* @param data
*
* @param data The flag data in string format
*/
private void parseFlags(ProtectedRegion region, String data) {
if (data == null) {
return;
}
State curState = State.ALLOW;
for (int i = 0; i < data.length(); i++) {
char k = data.charAt(i);
if (k == '+') {
@@ -258,8 +279,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
} else {
flagStr = String.valueOf(k);
}
StateFlag flag = DefaultFlag.getLegacyFlag(flagStr);
StateFlag flag = legacyFlagCodes.get(flagStr);
if (flag != null) {
region.setFlag(flag, curState);
} else {
@@ -271,29 +292,29 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* Used to write the list of domains.
*
*
* @param domain
* @return
*/
/* private String writeDomains(DefaultDomain domain) {
StringBuilder str = new StringBuilder();
for (String player : domain.getPlayers()) {
str.append("u:" + player + ",");
}
for (String group : domain.getGroups()) {
str.append("g:" + group + ",");
}
return str.length() > 0 ?
str.toString().substring(0, str.length() - 1) : "";
}*/
/**
* Helper method to prepend '+' or '-' in front of a flag according
* to the flag's state.
*
*
* @param state
* @param flag
* @return
@@ -305,16 +326,16 @@ public class CSVDatabase extends AbstractProtectionDatabase {
} else if (state == State.DENY) {
return "-" + flag;
}
return "";
}
*/
/**
* Returns a null if a string is null or empty.
*
* @param str
* @return
*
* @param str The string to format
* @return null if the string is empty or null, otherwise the provided string
*/
protected String nullEmptyString(String str) {
if (str == null) {
@@ -326,18 +347,10 @@ public class CSVDatabase extends AbstractProtectionDatabase {
}
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Get a list of protected regions.
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = regions;
}
@@ -0,0 +1,20 @@
package com.sk89q.worldguard.protection.databases;
import com.sk89q.worldguard.util.FatalConfigurationLoadingException;
public class InvalidTableFormatException extends FatalConfigurationLoadingException {
private static final long serialVersionUID = 1L;
protected String updateFile;
public InvalidTableFormatException(String updateFile) {
super();
this.updateFile = updateFile;
}
public String toString() {
return "You need to update your database to the latest version.\n" +
"\t\tPlease see " + this.updateFile;
}
}
File diff suppressed because it is too large. Load diff
@@ -19,54 +19,54 @@
package com.sk89q.worldguard.protection.databases;
import java.util.Map;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.io.IOException;
import java.util.Map;
/**
* Represents a database to read and write lists of regions from and to.
*
*
* @author sk89q
*/
public interface ProtectionDatabase {
/**
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws IOException
*
* @throws ProtectionDatabaseException when an error occurs
*/
public void load() throws IOException;
public void load() throws ProtectionDatabaseException;
/**
* Save the list of regions.
*
* @throws IOException
*
* @throws ProtectionDatabaseException when an error occurs
*/
public void save() throws IOException;
public void save() throws ProtectionDatabaseException;
/**
* Load the list of regions into a region manager.
*
* @param manager
* @throws IOException
*
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
public void load(RegionManager manager) throws IOException;
public void load(RegionManager manager) throws ProtectionDatabaseException;
/**
* Save the list of regions from a region manager.
*
* @param manager
* @throws IOException
*
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
public void save(RegionManager manager) throws IOException;
public void save(RegionManager manager) throws ProtectionDatabaseException;
/**
* Get a list of regions.
*
* @return
*
* @return the regions loaded by this ProtectionDatabase
*/
public Map<String,ProtectedRegion> getRegions();
/**
* Set the list of regions.
*
* @param regions
*
* @param regions The regions to be applied to this ProtectionDatabase
*/
public void setRegions(Map<String,ProtectedRegion> regions);
}
@@ -0,0 +1,42 @@
// $Id$
/*
* WorldGuard ProtectionDatabaseException
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases;
import java.lang.Exception;
public class ProtectionDatabaseException extends Exception {
private static final long serialVersionUID = 1L;
public ProtectionDatabaseException() {
super();
}
public ProtectionDatabaseException(String message) {
super(message);
}
public ProtectionDatabaseException(String message, Throwable cause) {
super(message, cause);
}
public ProtectionDatabaseException(Throwable cause) {
super(cause);
}
}
@@ -19,8 +19,11 @@
package com.sk89q.worldguard.protection.databases;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldguard.domains.DefaultDomain;
/**
@@ -29,18 +32,18 @@ import com.sk89q.worldguard.domains.DefaultDomain;
* @author sk89q
*/
public class RegionDBUtil {
private static Pattern groupPattern = Pattern.compile("^[gG]:(.+)$");
private static Pattern groupPattern = Pattern.compile("(?i)^[G]:(.+)$");
private RegionDBUtil() {
}
/**
* Parse a group/player DefaultDomain specification for areas.
* Add the given names to {@code domain}
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain to add to
* @param split The {@link String[]} containing names to add to {@code domain}
* @param startIndex The beginning index in the array
*/
public static void addToDomain(DefaultDomain domain, String[] split,
int startIndex) {
@@ -56,11 +59,11 @@ public class RegionDBUtil {
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* Remove the given names from {@code domain}
*
* @param domain The domain to remove from
* @param split The {@link String[]} containing names to remove from {@code domain}
* @param startIndex The beginning index in the array
*/
public static void removeFromDomain(DefaultDomain domain, String[] split,
int startIndex) {
@@ -78,9 +81,9 @@ public class RegionDBUtil {
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
* @param split The array of names to add
* @param startIndex The beginning index in the array
* @return The resulting DefaultDomain
*/
public static DefaultDomain parseDomainString(String[] split, int startIndex) {
DefaultDomain domain = new DefaultDomain();
@@ -97,4 +100,34 @@ public class RegionDBUtil {
return domain;
}
/**
* Creates a comma separated list of PreparedStatement place holders
*
* @param length The number of wildcards to create
* @return A string with {@code length} wildcards for usage in a PreparedStatement
*/
public static String preparePlaceHolders(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length;) {
builder.append("?");
if (++i < length) {
builder.append(",");
}
}
return builder.toString();
}
/**
* Adds all of the parsed values to the PreparedStatement
*
* @param preparedStatement The preparedStanement to add to
* @param values The values to set
* @throws SQLException see {@link PreparedStatement#setString(int, String)}
*/
public static void setValues(PreparedStatement preparedStatement, String... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
preparedStatement.setString(i + 1, values[i]);
}
}
}
@@ -21,6 +21,7 @@ package com.sk89q.worldguard.protection.databases;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -28,6 +29,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLNode;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
@@ -39,24 +44,33 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.yaml.Configuration;
import com.sk89q.worldguard.util.yaml.ConfigurationNode;
public class YAMLDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private Configuration config;
private YAMLProcessor config;
private Map<String, ProtectedRegion> regions;
private final Logger logger;
public YAMLDatabase(File file) {
config = new Configuration(file);
public YAMLDatabase(File file, Logger logger) throws ProtectionDatabaseException, FileNotFoundException {
this.logger = logger;
if (!file.exists()) { // shouldn't be necessary, but check anyways
try {
file.createNewFile();
} catch (IOException e) {
throw new FileNotFoundException(file.getAbsolutePath());
}
}
config = new YAMLProcessor(file, false, YAMLFormat.COMPACT);
}
public void load() throws IOException {
config.load();
public void load() throws ProtectionDatabaseException {
try {
config.load();
} catch (IOException e) {
throw new ProtectionDatabaseException(e);
}
Map<String, ConfigurationNode> regionData = config.getNodes("regions");
Map<String, YAMLNode> regionData = config.getNodes("regions");
// No regions are even configured
if (regionData == null) {
@@ -69,9 +83,9 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
for (Map.Entry<String, ConfigurationNode> entry : regionData.entrySet()) {
for (Map.Entry<String, YAMLNode> entry : regionData.entrySet()) {
String id = entry.getKey().toLowerCase().replace(".", "");
ConfigurationNode node = entry.getValue();
YAMLNode node = entry.getValue();
String type = node.getString("type");
ProtectedRegion region;
@@ -140,7 +154,7 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
return val;
}
private void setFlags(ProtectedRegion region, ConfigurationNode flagsData) {
private void setFlags(ProtectedRegion region, YAMLNode flagsData) {
if (flagsData == null) {
return;
}
@@ -151,6 +165,13 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
if (o != null) {
setFlag(region, flag, o);
}
if (flag.getRegionGroupFlag() != null) {
Object o2 = flagsData.getProperty(flag.getRegionGroupFlag().getName());
if (o2 != null) {
setFlag(region, flag.getRegionGroupFlag(), o2);
}
}
}
}
@@ -164,7 +185,7 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
region.setFlag(flag, val);
}
private DefaultDomain parseDomain(ConfigurationNode node) {
private DefaultDomain parseDomain(YAMLNode node) {
if (node == null) {
return new DefaultDomain();
}
@@ -182,12 +203,12 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
return domain;
}
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
config.clear();
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
ProtectedRegion region = entry.getValue();
ConfigurationNode node = config.addNode("regions." + entry.getKey());
YAMLNode node = config.addNode("regions." + entry.getKey());
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
@@ -0,0 +1,62 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public abstract class AbstractDatabaseMigrator implements DatabaseMigrator {
private static HashMap<MigratorKey, Class<? extends AbstractDatabaseMigrator>> migrators =
new HashMap<MigratorKey, Class<? extends AbstractDatabaseMigrator>>();
public static Map<MigratorKey, Class<? extends AbstractDatabaseMigrator>> getMigrators() {
if (!migrators.isEmpty()) return migrators;
AbstractDatabaseMigrator.migrators.put(new MigratorKey("mysql", "yaml"), MySQLToYAMLMigrator.class);
AbstractDatabaseMigrator.migrators.put(new MigratorKey("yaml", "mysql"), YAMLToMySQLMigrator.class);
return migrators;
}
protected abstract Set<String> getWorldsFromOld() throws MigrationException;
protected abstract Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException;
protected abstract ProtectionDatabase getNewWorldStorage(String world) throws MigrationException;
public void migrate() throws MigrationException {
for (String world : this.getWorldsFromOld()) {
ProtectionDatabase database = this.getNewWorldStorage(world);
database.setRegions(this.getRegionsForWorldFromOld(world));
try {
database.save();
} catch (ProtectionDatabaseException e) {
throw new MigrationException(e);
}
}
}
}
@@ -1,7 +1,7 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,19 +17,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard;
package com.sk89q.worldguard.protection.databases.migrators;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* Represents a method of converting from one database to another.
*
* @author Nicholas Steicke
*/
public interface DatabaseMigrator {
public class TickSyncDelayLoggerFilter implements Filter {
public boolean isLoggable(LogRecord record) {
if (record.getLevel() == Level.WARNING
&& record.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) {
return false;
}
return true;
}
public void migrate() throws MigrationException;
}
@@ -0,0 +1,40 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
public class MigrationException extends Exception {
private static final long serialVersionUID = 1L;
public MigrationException() {
super();
}
public MigrationException(String message) {
super(message);
}
public MigrationException(String message, Throwable cause) {
super(message, cause);
}
public MigrationException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,43 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
public class MigratorKey {
public final String from;
public final String to;
public MigratorKey(String from, String to) {
this.from = from;
this.to = to;
}
public boolean equals(Object o) {
MigratorKey other = (MigratorKey) o;
return other.from.equals(this.from) && other.to.equals(this.to);
}
public int hashCode() {
int hash = 17;
hash = hash * 31 + this.from.hashCode();
hash = hash * 31 + this.to.hashCode();
return hash;
}
}
@@ -0,0 +1,97 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class MySQLToYAMLMigrator extends AbstractDatabaseMigrator {
private WorldGuardPlugin plugin;
private Set<String> worlds;
public MySQLToYAMLMigrator(WorldGuardPlugin plugin) throws MigrationException {
this.plugin = plugin;
this.worlds = new HashSet<String>();
ConfigurationManager config = plugin.getGlobalStateManager();
try {
Connection conn = DriverManager.getConnection(config.sqlDsn, config.sqlUsername, config.sqlPassword);
ResultSet worlds = conn.prepareStatement("SELECT `name` FROM `world`;").executeQuery();
while(worlds.next()) {
this.worlds.add(worlds.getString(1));
}
conn.close();
} catch (SQLException e) {
throw new MigrationException((Exception) e);
}
}
@Override
protected Set<String> getWorldsFromOld() {
return this.worlds;
}
@Override
protected Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException {
ProtectionDatabase oldDatabase;
try {
oldDatabase = new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
oldDatabase.load();
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
return oldDatabase.getRegions();
}
@Override
protected ProtectionDatabase getNewWorldStorage(String world) throws MigrationException {
try {
File file = new File(plugin.getDataFolder(),
"worlds" + File.separator + world + File.separator + "regions.yml");
return new YAMLDatabase(file, plugin.getLogger());
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
}
}
@@ -0,0 +1,86 @@
// $Id$
/*
* MySQL WordGuard Region Database
* Copyright (C) 2011 Nicholas Steicke <http://narthollis.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.databases.migrators;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class YAMLToMySQLMigrator extends AbstractDatabaseMigrator {
private WorldGuardPlugin plugin;
private HashMap<String,File> regionYamlFiles;
public YAMLToMySQLMigrator(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.regionYamlFiles = new HashMap<String,File>();
File files[] = new File(plugin.getDataFolder(), "worlds" + File.separator).listFiles();
for (File item : files) {
if (item.isDirectory()) {
for (File subItem : item.listFiles()) {
if (subItem.getName().equals("regions.yml")) {
this.regionYamlFiles.put(item.getName(), subItem);
}
}
}
}
}
@Override
protected Set<String> getWorldsFromOld() {
return this.regionYamlFiles.keySet();
}
@Override
protected Map<String, ProtectedRegion> getRegionsForWorldFromOld(String world) throws MigrationException {
ProtectionDatabase oldDatabase;
try {
oldDatabase = new YAMLDatabase(this.regionYamlFiles.get(world), plugin.getLogger());
oldDatabase.load();
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
return oldDatabase.getRegions();
}
@Override
protected ProtectionDatabase getNewWorldStorage(String world) throws MigrationException {
try {
return new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
}
}
}
@@ -0,0 +1,82 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
/**
* This event is fired when PVP is disallowed between players due to a "pvp deny" flag.
* Cancelling this event allows the PVP in spite of this.
*
* @author Score_Under
*/
public class DisallowedPVPEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private final Player attacker;
private final Player defender;
private final EntityDamageByEntityEvent event;
public DisallowedPVPEvent(final Player attacker, final Player defender, EntityDamageByEntityEvent event) {
this.attacker = attacker;
this.defender = defender;
this.event = event;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* @return the attacking player.
*/
public Player getAttacker() {
return attacker;
}
/**
* @return the defending player.
*/
public Player getDefender() {
return defender;
}
public EntityDamageByEntityEvent getCause() {
return event;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class BooleanFlag extends Flag<Boolean> {
public BooleanFlag(String name, char legacyCode) {
super(name, legacyCode);
public BooleanFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public BooleanFlag(String name) {
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class CommandStringFlag extends Flag<String> {
public CommandStringFlag(String name, char legacyCode) {
super(name, legacyCode);
public CommandStringFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public CommandStringFlag(String name) {
@@ -19,88 +19,96 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.entity.CreatureType;
import org.bukkit.GameMode;
import org.bukkit.entity.EntityType;
/**
*
* @author sk89q
*/
public final class DefaultFlag {
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", 'z', false);
public static final StateFlag BUILD = new StateFlag("build", 'b', true);
public static final StateFlag PVP = new StateFlag("pvp", 'p', true);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", 'm', true);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", 'c', true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true);
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", false, RegionGroup.ALL);
public static final StateFlag BUILD = new StateFlag("build", true, RegionGroup.NON_MEMBERS);
public static final RegionGroupFlag CONSTRUCT = new RegionGroupFlag("construct", RegionGroup.MEMBERS);
public static final StateFlag PVP = new StateFlag("pvp", true, RegionGroup.ALL);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", true, RegionGroup.ALL);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true, RegionGroup.ALL);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", true, RegionGroup.ALL);
public static final StateFlag ENDERDRAGON_BLOCK_DAMAGE = new StateFlag("enderdragon-block-damage", true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true, RegionGroup.ALL);
public static final StateFlag SLEEP = new StateFlag("sleep", true);
public static final StateFlag TNT = new StateFlag("tnt", 't', true);
public static final StateFlag LIGHTER = new StateFlag("lighter", 'l', true);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", 'f', true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", 'F', true);
public static final StateFlag TNT = new StateFlag("tnt", true, RegionGroup.ALL);
public static final StateFlag LIGHTER = new StateFlag("lighter", true, RegionGroup.ALL);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", true);
public static final StateFlag LIGHTNING = new StateFlag("lightning", true);
public static final StateFlag CHEST_ACCESS = new StateFlag("chest-access", 'C', false);
public static final StateFlag CHEST_ACCESS = new StateFlag("chest-access", false);
public static final StateFlag WATER_FLOW = new StateFlag("water-flow", true);
public static final StateFlag LAVA_FLOW = new StateFlag("lava-flow", true);
public static final StateFlag USE = new StateFlag("use", true);
public static final StateFlag PLACE_VEHICLE = new StateFlag("vehicle-place", false);
public static final StateFlag DESTROY_VEHICLE = new StateFlag("vehicle-destroy", false);
public static final StateFlag PISTONS = new StateFlag("pistons", true);
public static final StateFlag SNOW_FALL = new StateFlag("snow-fall", true);
public static final StateFlag SNOW_MELT = new StateFlag("snow-melt", true);
public static final StateFlag ICE_FORM = new StateFlag("ice-form", true);
public static final StateFlag ICE_MELT = new StateFlag("ice-melt", true);
public static final StateFlag MUSHROOMS = new StateFlag("mushroom-growth", true);
public static final StateFlag LEAF_DECAY = new StateFlag("leaf-decay", true);
public static final StateFlag GRASS_SPREAD = new StateFlag("grass-growth", true);
public static final StateFlag ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false, RegionGroup.ALL);
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", true, RegionGroup.ALL);
public static final StateFlag SEND_CHAT = new StateFlag("send-chat", true);
public static final StateFlag RECEIVE_CHAT = new StateFlag("receive-chat", true);
public static final StateFlag ENTRY = new StateFlag("entry", true);
public static final RegionGroupFlag ENTRY_PERM = new RegionGroupFlag("entry-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StateFlag EXIT = new StateFlag("exit", true);
public static final RegionGroupFlag EXIT_PERM = new RegionGroupFlag("exit-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter");
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave");
public static final SetFlag<CreatureType> DENY_SPAWN = new SetFlag<CreatureType>("deny-spawn", new CreatureTypeFlag(null));
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final VectorFlag TELE_LOC = new VectorFlag("teleport");
public static final RegionGroupFlag TELE_PERM = new RegionGroupFlag("teleport-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final VectorFlag SPAWN_LOC = new VectorFlag("spawn");
public static final RegionGroupFlag SPAWN_PERM = new RegionGroupFlag("spawn-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final StateFlag ITEM_DROP = new StateFlag("item-drop", true);
public static final StateFlag ENTITY_PAINTING_DESTROY = new StateFlag("entity-painting-destroy", true);
public static final StateFlag POTION_SPLASH = new StateFlag("potion-splash", true);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting", RegionGroup.ALL);
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell", RegionGroup.ALL);
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter", RegionGroup.ALL);
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave", RegionGroup.ALL);
public static final SetFlag<EntityType> DENY_SPAWN = new SetFlag<EntityType>("deny-spawn", RegionGroup.ALL, new EntityTypeFlag(null));
public static final EnumFlag<GameMode> GAME_MODE = new EnumFlag<GameMode>("game-mode", GameMode.class, RegionGroup.ALL);
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay", RegionGroup.ALL);
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount", RegionGroup.ALL);
public static final IntegerFlag MIN_HEAL = new IntegerFlag("heal-min-health", RegionGroup.ALL);
public static final IntegerFlag MAX_HEAL = new IntegerFlag("heal-max-health", RegionGroup.ALL);
public static final IntegerFlag FEED_DELAY = new IntegerFlag("feed-delay", RegionGroup.ALL);
public static final IntegerFlag FEED_AMOUNT = new IntegerFlag("feed-amount", RegionGroup.ALL);
public static final IntegerFlag MIN_FOOD = new IntegerFlag("feed-min-hunger", RegionGroup.ALL);
public static final IntegerFlag MAX_FOOD = new IntegerFlag("feed-max-hunger", RegionGroup.ALL);
public static final LocationFlag TELE_LOC = new LocationFlag("teleport", RegionGroup.MEMBERS);
public static final LocationFlag SPAWN_LOC = new LocationFlag("spawn", RegionGroup.MEMBERS);
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", new CommandStringFlag(null));
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", RegionGroup.ALL, new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", RegionGroup.ALL, new CommandStringFlag(null));
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, PVP, MOB_DAMAGE, MOB_SPAWNING, CREEPER_EXPLOSION, SLEEP,
TNT, LIGHTER, FIRE_SPREAD, LAVA_FIRE, CHEST_ACCESS, WATER_FLOW, LAVA_FLOW,
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER,
NOTIFY_LEAVE, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE, SNOW_FALL, LEAF_DECAY,
GHAST_FIREBALL, BLOCKED_CMDS, ALLOWED_CMDS, ENTRY, ENTRY_PERM, EXIT, EXIT_PERM
PASSTHROUGH, BUILD, CONSTRUCT, PVP, CHEST_ACCESS, PISTONS,
TNT, LIGHTER, USE, PLACE_VEHICLE, DESTROY_VEHICLE, SLEEP,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY, EXP_DROPS,
CREEPER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY, ITEM_DROP,
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, SEND_CHAT, RECEIVE_CHAT,
FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, SPAWN_LOC, POTION_SPLASH,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE,
};
static {
ENTRY.setGroupFlag(ENTRY_PERM);
EXIT.setGroupFlag(EXIT_PERM);
}
private DefaultFlag() {
}
public static Flag<?>[] getFlags() {
return flagsList;
}
/**
* Get the legacy flag.
*
* @param flagString
* @return null if not found
*/
public static StateFlag getLegacyFlag(String flagString) {
for (Flag<?> flag : flagsList) {
if (flag instanceof StateFlag && flagString.equals(String.valueOf(flag.getLegacyCode()))) {
return (StateFlag) flag;
}
}
return null;
}
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class DoubleFlag extends Flag<Double> {
public DoubleFlag(String name, char legacyCode) {
super(name, legacyCode);
public DoubleFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public DoubleFlag(String name) {
@@ -39,7 +40,7 @@ public class DoubleFlag extends Flag<Double> {
public Double parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
@@ -18,30 +18,28 @@
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.EntityType;
/**
* Represents a creature type.
* Represents an entity type.
*
* @author sk89q
*/
public class CreatureTypeFlag extends EnumFlag<CreatureType> {
public class EntityTypeFlag extends EnumFlag<EntityType> {
public CreatureTypeFlag(String name, char legacyCode) {
super(name, legacyCode, CreatureType.class);
public EntityTypeFlag(String name, RegionGroup defaultGroup) {
super(name, EntityType.class, defaultGroup);
}
public CreatureTypeFlag(String name) {
super(name, CreatureType.class);
public EntityTypeFlag(String name) {
super(name, EntityType.class);
}
@Override
public CreatureType detectValue(String input) {
CreatureType lowMatch = null;
public EntityType detectValue(String input) {
EntityType lowMatch = null;
for (CreatureType type : CreatureType.values()) {
for (EntityType type : EntityType.values()) {
if (type.name().equalsIgnoreCase(input.trim())) {
return type;
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -28,9 +29,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class EnumFlag<T extends Enum<T>> extends Flag<T> {
private Class<T> enumClass;
public EnumFlag(String name, char legacyCode, Class<T> enumClass) {
super(name, legacyCode);
public EnumFlag(String name, Class<T> enumClass, RegionGroup defaultGroup) {
super(name, defaultGroup);
this.enumClass = enumClass;
}
@@ -40,6 +41,10 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
}
private T findValue(String input) throws IllegalArgumentException {
if (input != null) {
input = input.toUpperCase();
}
try {
return Enum.valueOf(enumClass, input);
} catch (IllegalArgumentException e) {
@@ -87,5 +92,5 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
public Object marshal(T o) {
return o.name();
}
}
@@ -19,40 +19,43 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
* @param <T>
* @param <T>
*/
public abstract class Flag<T> {
private String name;
private Character legacyCode;
private RegionGroupFlag regionGroup;
public Flag(String name, char legacyCode) {
public Flag(String name, RegionGroup defaultGroup) {
this.name = name;
this.legacyCode = legacyCode;
if (defaultGroup != null) {
this.regionGroup = new RegionGroupFlag(name + "-group", defaultGroup);
}
}
public Flag(String name) {
this.name = name;
this.legacyCode = null;
this(name, RegionGroup.NON_MEMBERS);
}
public String getName() {
return name;
}
public Character getLegacyCode() {
return legacyCode;
public RegionGroupFlag getRegionGroupFlag() {
return regionGroup;
}
public abstract T parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat;
public abstract T unmarshal(Object o);
public abstract Object marshal(T o);
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class IntegerFlag extends Flag<Integer> {
public IntegerFlag(String name, char legacyCode) {
super(name, legacyCode);
public IntegerFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public IntegerFlag(String name) {
@@ -39,7 +40,7 @@ public class IntegerFlag extends Flag<Integer> {
public Integer parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
@@ -0,0 +1,149 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class LocationFlag extends Flag<Location> {
public LocationFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public LocationFlag(String name) {
super(name);
}
@Override
public Location parseInput(WorldGuardPlugin plugin, CommandSender sender, String input) throws InvalidFlagFormat {
input = input.trim();
final Player player;
try {
player = plugin.checkPlayer(sender);
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
}
if ("here".equalsIgnoreCase(input)) {
return BukkitUtil.toLocation(player.getLocation());
} else if ("none".equalsIgnoreCase(input)) {
return null;
} else {
String[] split = input.split(",");
if (split.length >= 3) {
try {
final World world = player.getWorld();
final double x = Double.parseDouble(split[0]);
final double y = Double.parseDouble(split[1]);
final double z = Double.parseDouble(split[2]);
final float yaw = split.length < 4 ? 0 : Float.parseFloat(split[3]);
final float pitch = split.length < 5 ? 0 : Float.parseFloat(split[4]);
return new Location(
BukkitUtil.getLocalWorld(world),
new Vector(
x,
y,
z
),
yaw, pitch
);
} catch (NumberFormatException e) {
}
}
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
}
@Override
public Location unmarshal(Object o) {
if (o instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) o;
Object rawWorld = map.get("world");
if (rawWorld == null) return null;
Object rawX = map.get("x");
if (rawX == null) return null;
Object rawY = map.get("y");
if (rawY == null) return null;
Object rawZ = map.get("z");
if (rawZ == null) return null;
Object rawYaw = map.get("yaw");
if (rawYaw == null) return null;
Object rawPitch = map.get("pitch");
if (rawPitch == null) return null;
World bukkitWorld = Bukkit.getServer().getWorld((String) rawWorld);
LocalWorld world = BukkitUtil.getLocalWorld(bukkitWorld);
Vector position = new Vector(toNumber(rawX), toNumber(rawY), toNumber(rawZ));
float yaw = (float) toNumber(rawYaw);
float pitch = (float) toNumber(rawPitch);
return new Location(world, position, yaw, pitch);
}
return null;
}
@Override
public Object marshal(Location o) {
Vector position = o.getPosition();
Map<String, Object> vec = new HashMap<String, Object>();
vec.put("world", o.getWorld().getName());
vec.put("x", position.getX());
vec.put("y", position.getY());
vec.put("z", position.getZ());
vec.put("yaw", o.getYaw());
vec.put("pitch", o.getPitch());
return vec;
}
private double toNumber(Object o) {
if (o instanceof Number) {
return ((Number) o).doubleValue();
} else {
return 0;
}
}
}
@@ -1,37 +1,31 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
/**
* Configuration exception.
*
* @author sk89q
*/
public class ConfigurationException extends Exception {
private static final long serialVersionUID = -2442886939908724203L;
public ConfigurationException() {
super();
}
public ConfigurationException(String msg) {
super(msg);
}
}
/*
* WorldGuard
* Copyright (C) 2012 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
/**
* A grouping of region membership types
*/
public enum RegionGroup {
MEMBERS,
OWNERS,
NON_MEMBERS,
NON_OWNERS,
ALL,
NONE
}
@@ -21,31 +21,17 @@ package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static enum RegionGroup {
MEMBERS,
OWNERS,
NON_MEMBERS,
NON_OWNERS
}
public class RegionGroupFlag extends EnumFlag<RegionGroup> {
private RegionGroup def;
public RegionGroupFlag(String name, char legacyCode, RegionGroup def) {
super(name, legacyCode);
this.def = def;
}
public RegionGroupFlag(String name, RegionGroup def) {
super(name);
super(name, RegionGroup.class, null);
this.def = def;
}
@@ -54,10 +40,9 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
}
@Override
public RegionGroup parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
public RegionGroup detectValue(String input) {
input = input.trim();
if (input.equalsIgnoreCase("members") || input.equalsIgnoreCase("member")) {
return RegionGroup.MEMBERS;
} else if (input.equalsIgnoreCase("owners") || input.equalsIgnoreCase("owner")) {
@@ -66,58 +51,31 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
return RegionGroup.NON_OWNERS;
} else if (input.equalsIgnoreCase("nonmembers") || input.equalsIgnoreCase("nonmember")) {
return RegionGroup.NON_MEMBERS;
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
}
}
@Override
public RegionGroup unmarshal(Object o) {
String str = o.toString();
if (str.equalsIgnoreCase("members")) {
return RegionGroup.MEMBERS;
} else if (str.equalsIgnoreCase("owners")) {
return RegionGroup.OWNERS;
} else if (str.equalsIgnoreCase("nonmembers")) {
return RegionGroup.NON_MEMBERS;
} else if (str.equalsIgnoreCase("nonowners")) {
return RegionGroup.NON_OWNERS;
} else {
return null;
}
}
@Override
public Object marshal(RegionGroup o) {
if (o == RegionGroup.MEMBERS) {
return "members";
} else if (o == RegionGroup.OWNERS) {
return "owners";
} else if (o == RegionGroup.NON_MEMBERS) {
return "nonmembers";
} else if (o == RegionGroup.NON_OWNERS) {
return "nonowners";
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone") || input.equalsIgnoreCase("all")) {
return RegionGroup.ALL;
} else if (input.equalsIgnoreCase("none") || input.equalsIgnoreCase("noone") || input.equalsIgnoreCase("deny")) {
return RegionGroup.NONE;
} else {
return null;
}
}
public static boolean isMember(ProtectedRegion region, RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (group == null || group == RegionGroup.ALL) {
return true;
} else if (group == RegionGroup.OWNERS) {
if (region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
} else if (group == RegionGroup.MEMBERS) {
if (region.isMember(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
} else if (group == RegionGroup.NON_OWNERS) {
if (!region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
} else if (group == RegionGroup.NON_MEMBERS) {
if (!region.isMember(player)) {
return true;
}
@@ -128,19 +86,21 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static boolean isMember(ApplicableRegionSet set,
RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (group == null || group == RegionGroup.ALL) {
return true;
} else if (group == RegionGroup.OWNERS) {
if (set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
} else if (group == RegionGroup.MEMBERS) {
if (set.isMemberOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
} else if (group == RegionGroup.NON_OWNERS) {
if (!set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
} else if (group == RegionGroup.NON_MEMBERS) {
if (!set.isMemberOfAll(player)) {
return true;
}
@@ -148,5 +108,5 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
return false;
}
}
@@ -18,10 +18,15 @@
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
* Represents a flag that consists of a set.
@@ -31,9 +36,9 @@ import java.util.*;
public class SetFlag<T> extends Flag<Set<T>> {
private Flag<T> subFlag;
public SetFlag(String name, char legacyCode, Flag<T> subFlag) {
super(name, legacyCode);
public SetFlag(String name, RegionGroup defaultGroup, Flag<T> subFlag) {
super(name, defaultGroup);
this.subFlag = subFlag;
}
@@ -56,8 +61,8 @@ public class SetFlag<T> extends Flag<Set<T>> {
@Override
public Set<T> unmarshal(Object o) {
if (o instanceof Collection) {
Collection collection = (Collection) o;
if (o instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) o;
Set<T> items = new HashSet<T>();
for (Object sub : collection) {
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,17 +27,16 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class StateFlag extends Flag<StateFlag.State> {
public enum State {
ALLOW,
DENY
}
private boolean def;
private RegionGroupFlag groupFlag;
public StateFlag(String name, char legacyCode, boolean def) {
super(name, legacyCode);
public StateFlag(String name, boolean def, RegionGroup defaultGroup) {
super(name, defaultGroup);
this.def = def;
}
@@ -49,19 +49,11 @@ public class StateFlag extends Flag<StateFlag.State> {
return def;
}
public RegionGroupFlag getGroupFlag() {
return groupFlag;
}
public void setGroupFlag(RegionGroupFlag groupFlag) {
this.groupFlag = groupFlag;
}
@Override
public State parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (input.equalsIgnoreCase("allow")) {
return State.ALLOW;
} else if (input.equalsIgnoreCase("deny")) {
@@ -69,7 +61,7 @@ public class StateFlag extends Flag<StateFlag.State> {
} else if (input.equalsIgnoreCase("none")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
throw new InvalidFlagFormat("Expected none/allow/deny but got '" + input + "'");
}
}
@@ -95,5 +87,5 @@ public class StateFlag extends Flag<StateFlag.State> {
return null;
}
}
}
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
@@ -26,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class StringFlag extends Flag<String> {
public StringFlag(String name, char legacyCode) {
super(name, legacyCode);
public StringFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public StringFlag(String name) {
@@ -38,7 +39,7 @@ public class StringFlag extends Flag<String> {
@Override
public String parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
return input;
return input.replaceAll("(?!\\\\)\\\\n", "\n").replaceAll("\\\\\\\\n", "\\n");
}
@Override
@@ -54,5 +55,5 @@ public class StringFlag extends Flag<String> {
public Object marshal(String o) {
return o;
}
}
@@ -20,7 +20,9 @@ package com.sk89q.worldguard.protection.flags;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.BukkitUtil;
@@ -32,8 +34,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
public class VectorFlag extends Flag<Vector> {
public VectorFlag(String name, char legacyCode) {
super(name, legacyCode);
public VectorFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public VectorFlag(String name) {
@@ -41,33 +43,48 @@ public class VectorFlag extends Flag<Vector> {
}
@Override
public Vector parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
public Vector parseInput(WorldGuardPlugin plugin, CommandSender sender, String input) throws InvalidFlagFormat {
input = input.trim();
try {
return BukkitUtil.toVector(plugin.checkPlayer(sender).getLocation());
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
if ("here".equalsIgnoreCase(input)) {
try {
return BukkitUtil.toVector(plugin.checkPlayer(sender).getLocation());
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
}
} else {
String[] split = input.split(",");
if (split.length == 3) {
try {
return new Vector(
Double.parseDouble(split[0]),
Double.parseDouble(split[1]),
Double.parseDouble(split[2])
);
} catch (NumberFormatException e) {
}
}
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
}
@Override
public Vector unmarshal(Object o) {
if (o instanceof Map) {
if (o instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) o;
Object rawX = map.get("x");
Object rawY = map.get("y");
Object rawZ = map.get("z");
if (rawX == null || rawY == null || rawZ == null) {
return null;
}
return new Vector(toNumber(rawX), toNumber(rawY), toNumber(rawZ));
}
return null;
}
@@ -79,7 +96,7 @@ public class VectorFlag extends Flag<Vector> {
vec.put("z", o.getZ());
return vec;
}
private double toNumber(Object o) {
if (o instanceof Integer) {
return (Integer) o;
@@ -19,23 +19,24 @@
package com.sk89q.worldguard.protection.managers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import java.util.Iterator;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* A very simple implementation of the region manager that uses a flat list
* and iterates through the list to identify applicable regions. This method
* is not very efficient.
*
*
* @author sk89q
*/
public class FlatRegionManager extends RegionManager {
@@ -47,47 +48,29 @@ public class FlatRegionManager extends RegionManager {
/**
* Construct the manager.
*
* @param regionloader
*
* @param regionLoader The loader for regions
*/
public FlatRegionManager(ProtectionDatabase regionloader) {
super(regionloader);
public FlatRegionManager(ProtectionDatabase regionLoader) {
super(regionLoader);
regions = new TreeMap<String, ProtectedRegion>();
}
/**
* Get a list of protected regions.
*
* @return
*/
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*/
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = new TreeMap<String, ProtectedRegion>(regions);
}
/**
* Adds a region.
*
* @param region
*/
@Override
public void addRegion(ProtectedRegion region) {
regions.put(region.getId().toLowerCase(), region);
}
/**
* Removes a region and its children.
*
* @param id
*/
@Override
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id.toLowerCase());
@@ -109,33 +92,11 @@ public class FlatRegionManager extends RegionManager {
}
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
@Override
public boolean hasRegion(String id) {
return regions.containsKey(id.toLowerCase());
}
/**
* Get a region by its ID.
*
* @param id
*/
@Override
public ProtectedRegion getRegion(String id) {
return regions.get(id.toLowerCase());
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(Vector pt) {
TreeSet<ProtectedRegion> appRegions =
@@ -144,16 +105,16 @@ public class FlatRegionManager extends RegionManager {
for (ProtectedRegion region : regions.values()) {
if (region.contains(pt)) {
appRegions.add(region);
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (!appRegions.contains(parent)) {
appRegions.add(region);
appRegions.add(parent);
}
parent = parent.getParent();
}
}
}
}
@@ -181,12 +142,6 @@ public class FlatRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}*/
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
@Override
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
@@ -200,11 +155,6 @@ public class FlatRegionManager extends RegionManager {
return applicable;
}
/**
* Get an object for a region for rules to be applied with.
*
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(ProtectedRegion checkRegion) {
@@ -212,7 +162,7 @@ public class FlatRegionManager extends RegionManager {
appRegions.addAll(regions.values());
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (Exception e) {
@@ -222,13 +172,6 @@ public class FlatRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param player
* @return
*/
@Override
public boolean overlapsUnownedRegion(ProtectedRegion checkRegion, LocalPlayer player) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
@@ -251,11 +194,6 @@ public class FlatRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -23,16 +23,17 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.khelekore.prtree.MBRConverter;
import org.khelekore.prtree.PRTree;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegionMBRConverter;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import java.io.IOException;
import java.util.Iterator;
public class PRTreeRegionManager extends RegionManager {
@@ -52,30 +53,22 @@ public class PRTreeRegionManager extends RegionManager {
/**
* Construct the manager.
*
* @param regionloader
* @throws IOException
*
* @param regionLoader The region loader to use
* @throws ProtectionDatabaseException when an error occurs while loading
*/
public PRTreeRegionManager(ProtectionDatabase regionloader) throws IOException {
super(regionloader);
public PRTreeRegionManager(ProtectionDatabase regionLoader) throws ProtectionDatabaseException {
super(regionLoader);
regions = new TreeMap<String, ProtectedRegion>();
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
this.load();
}
/**
* Get a list of protected regions.
*
* @return
*/
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*/
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = new TreeMap<String, ProtectedRegion>(regions);
@@ -83,11 +76,6 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Adds a region.
*
* @param region
*/
@Override
public void addRegion(ProtectedRegion region) {
regions.put(region.getId().toLowerCase(), region);
@@ -95,32 +83,11 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
@Override
public boolean hasRegion(String id) {
return regions.containsKey(id.toLowerCase());
}
/**
* Get a region by its ID.
*
* @param id
*/
@Override
public ProtectedRegion getRegion(String id) {
return regions.get(id.toLowerCase());
}
/**
* Removes a region and its children.
*
* @param id
*/
@Override
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id.toLowerCase());
@@ -129,9 +96,7 @@ public class PRTreeRegionManager extends RegionManager {
if (region != null) {
List<String> removeRegions = new ArrayList<String>();
Iterator<ProtectedRegion> iter = regions.values().iterator();
while (iter.hasNext()) {
ProtectedRegion curRegion = iter.next();
for (ProtectedRegion curRegion : regions.values()) {
if (curRegion.getParent() == region) {
removeRegions.add(curRegion.getId().toLowerCase());
}
@@ -146,12 +111,6 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(Vector pt) {
List<ProtectedRegion> appRegions =
@@ -165,7 +124,7 @@ public class PRTreeRegionManager extends RegionManager {
appRegions.add(region);
}
}
Collections.sort(appRegions);
return new ApplicableRegionSet(appRegions, regions.get("__global__"));
@@ -186,12 +145,6 @@ public class PRTreeRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
@Override
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
@@ -208,13 +161,6 @@ public class PRTreeRegionManager extends RegionManager {
return applicable;
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param player
* @return
*/
@Override
public boolean overlapsUnownedRegion(ProtectedRegion checkRegion, LocalPlayer player) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
@@ -237,11 +183,6 @@ public class PRTreeRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -19,12 +19,13 @@
package com.sk89q.worldguard.protection.managers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -33,17 +34,17 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
* simple implementation uses a flat list and iterates through the entire list
* to look for applicable regions, but a more complicated (and more efficient)
* implementation may use space partitioning techniques.
*
*
* @author sk89q
*/
public abstract class RegionManager {
protected ProtectionDatabase loader;
/**
* Construct the object.
*
* @param loader
*
* @param loader The loader for this region
*/
public RegionManager(ProtectionDatabase loader) {
this.loader = loader;
@@ -53,25 +54,25 @@ public abstract class RegionManager {
* Load the list of regions. If the regions do not load properly, then
* the existing list should be used (as stored previously).
*
* @throws IOException thrown on load error
* @throws ProtectionDatabaseException when an error occurs
*/
public void load() throws IOException {
public void load() throws ProtectionDatabaseException {
loader.load(this);
}
/**
* Save the list of regions.
*
* @throws IOException thrown on save eIf checking multiple flags for a single locationror
* @throws ProtectionDatabaseException when an error occurs while saving
*/
public void save() throws IOException {
public void save() throws ProtectionDatabaseException {
loader.save(this);
}
/**
* Get a map of protected regions. Use one of the region manager methods
* if possible if working with regions.
*
*
* @return map of regions, with keys being region IDs (lowercase)
*/
public abstract Map<String, ProtectedRegion> getRegions();
@@ -79,7 +80,7 @@ public abstract class RegionManager {
/**
* Set a list of protected regions. Keys should be lowercase in the given
* map fo regions.
*
*
* @param regions map of regions
*/
public abstract void setRegions(Map<String, ProtectedRegion> regions);
@@ -87,39 +88,77 @@ public abstract class RegionManager {
/**
* Adds a region. If a region by the given name already exists, then
* the existing region will be replaced.
*
*
* @param region region to add
*/
public abstract void addRegion(ProtectedRegion region);
/**
* Return whether a region exists by an ID.
*
*
* @param id id of the region, can be mixed-case
* @return whether the region exists
*/
public abstract boolean hasRegion(String id);
/**
* Get a region by its ID.
*
* Get a region by its ID. Includes symbolic names like #&lt;index&gt;
*
* @param id id of the region, can be mixed-case
* @return region or null if it doesn't exist
*/
public abstract ProtectedRegion getRegion(String id);
public ProtectedRegion getRegion(String id) {
if (id.startsWith("#")) {
int index;
try {
index = Integer.parseInt(id.substring(1)) - 1;
} catch (NumberFormatException e) {
return null;
}
for (ProtectedRegion region : getRegions().values()) {
if (index == 0) {
return region;
}
--index;
}
return null;
}
return getRegionExact(id);
}
/**
* Get a region by its ID.
*
* @param id id of the region, can be mixed-case
* @return region or null if it doesn't exist
*/
public ProtectedRegion getRegionExact(String id) {
return getRegions().get(id.toLowerCase());
}
/**
* Removes a region, including inheriting children.
*
*
* @param id id of the region, can be mixed-case
*/
public abstract void removeRegion(String id);
/**
* Get an object for a point for rules to be applied with. Use this
* in order to query for flag data or membership data for a given
* point.
*
* Get an object for a point for rules to be applied with. Use this in order
* to query for flag data or membership data for a given point.
*
* @param loc Bukkit location
* @return applicable region set
*/
public ApplicableRegionSet getApplicableRegions(org.bukkit.Location loc) {
return getApplicableRegions(com.sk89q.worldedit.bukkit.BukkitUtil.toVector(loc));
}
/**
* Get an object for a point for rules to be applied with. Use this in order
* to query for flag data or membership data for a given point.
*
* @param pt point
* @return applicable region set
*/
@@ -129,17 +168,15 @@ public abstract class RegionManager {
* Get an object for a point for rules to be applied with. This gets
* a set for the given reason.
*
* @deprecated not yet fully supported
* @param region region
* @return regino set
*/
@Deprecated
public abstract ApplicableRegionSet getApplicableRegions(
ProtectedRegion region);
/**
* Get a list of region IDs that contain a point.
*
*
* @param pt point
* @return list of region Ids
*/
@@ -148,7 +185,7 @@ public abstract class RegionManager {
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
*
* @param region region to check
* @param player player to check against
* @return whether there is an overlap
@@ -21,7 +21,9 @@ package com.sk89q.worldguard.protection.regions;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
@@ -29,16 +31,14 @@ public class GlobalProtectedRegion extends ProtectedRegion {
public GlobalProtectedRegion(String id) {
super(id);
min = new BlockVector(0, 0, 0);
max = new BlockVector(0, 0, 0);
}
@Override
public BlockVector getMinimumPoint() {
return new BlockVector(0, 0, 0);
}
@Override
public BlockVector getMaximumPoint() {
return new BlockVector(0, 0, 0);
public List<BlockVector2D> getPoints() {
List<BlockVector2D> pts = new ArrayList<BlockVector2D>();
pts.add(new BlockVector2D(min.getBlockX(),min.getBlockZ()));
return pts;
}
@Override
@@ -18,11 +18,14 @@
*/
package com.sk89q.worldguard.protection.regions;
import com.sk89q.worldedit.*;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
/**
* Represents a cuboid region that can be protected.
*
@@ -30,83 +33,78 @@ import java.util.List;
*/
public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Store the first point.
*/
private BlockVector min;
/**
* Store the second point.
*/
private BlockVector max;
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param min
* @param max
* @param id The region id
* @param pt1 The first point of this region
* @param pt2 The second point of this region
*/
public ProtectedCuboidRegion(String id, BlockVector min, BlockVector max) {
public ProtectedCuboidRegion(String id, BlockVector pt1, BlockVector pt2) {
super(id);
this.min = min;
this.max = max;
setMinMaxPoints(pt1, pt2);
}
/**
* Get the lower point of the cuboid.
* Given any two points, sets the minimum and maximum points
*
* @return min point
* @param pt1 The first point of this region
* @param pt2 The second point of this region
*/
@Override
public BlockVector getMinimumPoint() {
return min;
private void setMinMaxPoints(BlockVector pt1, BlockVector pt2) {
List<Vector> points = new ArrayList<Vector>();
points.add(pt1);
points.add(pt2);
setMinMaxPoints(points);
}
/**
* Set the lower point of the cuboid.
*
* @param pt
* @param pt The point to set as the minimum point
*/
public void setMinimumPoint(BlockVector pt) {
min = pt;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
@Override
public BlockVector getMaximumPoint() {
return max;
setMinMaxPoints(pt, max);
}
/**
* Set the upper point of the cuboid.
*
* @param pt
* @param pt The point to set as the maximum point
*/
public void setMaximumPoint(BlockVector pt) {
max = pt;
setMinMaxPoints(min, pt);
}
public List<BlockVector2D> getPoints() {
List<BlockVector2D> pts = new ArrayList<BlockVector2D>();
int x1 = min.getBlockX();
int x2 = max.getBlockX();
int z1 = min.getBlockZ();
int z2 = max.getBlockZ();
pts.add(new BlockVector2D(x1, z1));
pts.add(new BlockVector2D(x2, z1));
pts.add(new BlockVector2D(x1, z2));
pts.add(new BlockVector2D(x2, z2));
return pts;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
int x = pt.getBlockX();
int y = pt.getBlockY();
int z = pt.getBlockZ();
return x >= min.getBlockX() && x <= max.getBlockX()
&& y >= min.getBlockY() && y <= max.getBlockY()
&& z >= min.getBlockZ() && z <= max.getBlockZ();
final double x = pt.getX();
final double y = pt.getY();
final double z = pt.getZ();
return x >= min.getBlockX() && x < max.getBlockX()+1
&& y >= min.getBlockY() && y < max.getBlockY()+1
&& z >= min.getBlockZ() && z < max.getBlockZ()+1;
}
/*
public boolean intersectsWith(ProtectedRegion region) throws UnsupportedIntersectionException {
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion r1 = (ProtectedCuboidRegion) this;
ProtectedCuboidRegion r2 = (ProtectedCuboidRegion) region;
@@ -131,152 +129,42 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
for (ProtectedRegion region : regions) {
if (!intersectsBoundingBox(region)) continue;
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
//intersectingRegions.add(regions.get(i));
// If both regions are Cuboids and their bounding boxes intersect, they intersect
if (region instanceof ProtectedCuboidRegion) {
intersectingRegions.add(region);
continue;
}
// Check whether the regions points are inside the other region
if (region.contains(new Vector(min.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), min.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i2 < ((ProtectedPolygonalRegion)region).getPoints().size(); i2++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
} else if (region instanceof ProtectedPolygonalRegion) {
// If either region contains the points of the other,
// or if any edges intersect, the regions intersect
if (containsAny(region.getPoints())
|| region.containsAny(getPoints())
|| intersectsEdges(region)) {
intersectingRegions.add(region);
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
List<BlockVector2D> points = new ArrayList<BlockVector2D>();
points.add(new BlockVector2D(min.getBlockX(), min.getBlockZ()));
points.add(new BlockVector2D(min.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), min.getBlockZ()));
for (i2 = 0; i2 < points.size(); i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (points.size() - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = min.getBlockY(); i3 <= max.getBlockY(); i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
throw new UnsupportedOperationException("Not supported yet.");
}
}
return intersectingRegions;
}
/**
* Return the type of region as a user-friendly name.
*
* @return type of region
*/
@Override
public String getTypeName() {
return "cuboid";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int xLength = max.getBlockX() - min.getBlockX() + 1;
int yLength = max.getBlockY() - min.getBlockY() + 1;
int zLength = max.getBlockZ() - min.getBlockZ() + 1;
int volume = xLength * yLength * zLength;
return volume;
return xLength * yLength * zLength;
}
}
}
@@ -18,9 +18,9 @@
*/
package com.sk89q.worldguard.protection.regions;
import java.util.List;
import java.util.ArrayList;
import com.sk89q.worldedit.BlockVector;
import java.util.List;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
@@ -30,55 +30,36 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
protected List<BlockVector2D> points;
protected int minY;
protected int maxY;
private BlockVector min;
private BlockVector max;
public ProtectedPolygonalRegion(String id, List<BlockVector2D> points, int minY, int maxY) {
super(id);
this.points = points;
this.minY = minY;
this.maxY = maxY;
setMinMaxPoints(points, minY, maxY);
this.minY = min.getBlockY();
this.maxY = max.getBlockY();
}
int minX = points.get(0).getBlockX();
int minZ = points.get(0).getBlockZ();
int maxX = points.get(0).getBlockX();
int maxZ = points.get(0).getBlockZ();
for (BlockVector2D v : points) {
int x = v.getBlockX();
int z = v.getBlockZ();
if (x < minX) {
minX = x;
}
if (z < minZ) {
minZ = z;
}
if (x > maxX) {
maxX = x;
}
if (z > maxZ) {
maxZ = z;
}
/**
* Sets the min and max points from all the 2d points and the min/max Y values
*
* @param points2D A {@link List} of points that this region should contain
* @param minY The minimum y coordinate
* @param maxY The maximum y coordinate
*/
private void setMinMaxPoints(List<BlockVector2D> points2D, int minY, int maxY) {
List<Vector> points = new ArrayList<Vector>();
int y = minY;
for (BlockVector2D point2D : points2D) {
points.add(new Vector(point2D.getBlockX(), y, point2D.getBlockZ()));
y = maxY;
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
setMinMaxPoints(points);
}
public List<BlockVector2D> getPoints() {
return points;
}
@Override
public BlockVector getMinimumPoint() {
return min;
}
@Override
public BlockVector getMaximumPoint() {
return max;
}
/**
* Checks to see if a point is inside this region.
*/
@@ -101,6 +82,7 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
int xOld, zOld;
int x1, z1;
int x2, z2;
long crossproduct;
int i;
xOld = points.get(npoints - 1).getBlockX();
@@ -124,10 +106,14 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
z1 = zNew;
z2 = zOld;
}
if ((xNew < targetX) == (targetX <= xOld)
&& ((long) targetZ - (long) z1) * (long) (x2 - x1) <= ((long) z2 - (long) z1)
* (long) (targetX - x1)) {
inside = !inside;
if (x1 <= targetX && targetX <= x2) {
crossproduct = ((long) targetZ - (long) z1) * (long) (x2 - x1)
- ((long) z2 - (long) z1) * (long) (targetX - x1);
if (crossproduct == 0) {
if ((z1 <= targetZ) == (targetZ <= z2)) return true; // on edge
} else if (crossproduct < 0 && (x1 != targetX)) {
inside = !inside;
}
}
xOld = xNew;
zOld = zNew;
@@ -138,124 +124,31 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
int numPoints = points.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
for (ProtectedRegion region : regions) {
if (!intersectsBoundingBox(region)) continue;
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the regions points are inside the other region
for (i2 = 0; i < numPoints; i++) {
Vector pt = new Vector(points.get(i2).getBlockX(), minY, points.get(i2).getBlockZ());
Vector pt2 = new Vector(points.get(i2).getBlockX(), maxY, points.get(i2).getBlockZ());
if (region.contains(pt) || region.contains(pt2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i < ((ProtectedPolygonalRegion)region).getPoints().size(); i++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
if (region instanceof ProtectedPolygonalRegion || region instanceof ProtectedCuboidRegion) {
// If either region contains the points of the other,
// or if any edges intersect, the regions intersect
if (containsAny(region.getPoints())
|| region.containsAny(getPoints())
|| intersectsEdges(region)) {
intersectingRegions.add(region);
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
for (i2 = 0; i2 < numPoints; i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (numPoints - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = this.minY; i3 <= this.maxY; i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
throw new UnsupportedOperationException("Not supported yet.");
}
}
return intersectingRegions;
}
/**
* Return the type of region as a user-friendly name.
*
*
* @return type of region
*/
@Override
@@ -263,15 +156,11 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
return "polygon";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int volume = 0;
int numPoints = points.size();
// TODO: Fix this
/*int numPoints = points.size();
if (numPoints < 3) {
return 0;
}
@@ -279,7 +168,7 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
double area = 0;
int xa, z1, z2;
for (int i = 0; i <= numPoints - 1; i++) {
for (int i = 0; i < numPoints; i++) {
xa = points.get(i).getBlockX();
//za = points.get(i).getBlockZ();
@@ -302,7 +191,7 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
area = area + (xa * (points.get(1).getBlockZ() - points.get(numPoints - 1).getBlockZ()));
volume = (Math.abs(maxY - minY) + 1) * (int) Math.ceil((Math.abs(area) / 2));
volume = (Math.abs(maxY - minY) + 1) * (int) Math.ceil((Math.abs(area) / 2));*/
return volume;
}
@@ -19,51 +19,57 @@
package com.sk89q.worldguard.protection.regions;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.flags.Flag;
import java.awt.geom.Line2D;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.flags.Flag;
/**
* Represents a region of any shape and size that can be protected.
*
*
* @author sk89q
*/
public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
protected BlockVector min;
protected BlockVector max;
private static final Pattern idPattern = Pattern.compile("^[A-Za-z0-9_,'\\-\\+/]{1,}$");
/**
* Holds the region's ID.
*/
private String id;
/**
* Priority.
*/
private int priority = 0;
/**
* Holds the curParent.
*/
private ProtectedRegion parent;
/**
* List of owners.
*/
private DefaultDomain owners = new DefaultDomain();
/**
* List of members.
*/
private DefaultDomain members = new DefaultDomain();
/**
* List of flags.
*/
@@ -72,13 +78,46 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Construct a new instance of this region.
*
* @param id
* @param id The id (name) of this region.
*/
public ProtectedRegion(String id) {
this.id = id;
}
/**
* Sets the minimum and maximum points of the bounding box for a region
*
* @param points The points to set. Must have at least one element.
*/
protected void setMinMaxPoints(List<Vector> points) {
int minX = points.get(0).getBlockX();
int minY = points.get(0).getBlockY();
int minZ = points.get(0).getBlockZ();
int maxX = minX;
int maxY = minY;
int maxZ = minZ;
for (Vector v : points) {
int x = v.getBlockX();
int y = v.getBlockY();
int z = v.getBlockZ();
if (x < minX) minX = x;
if (y < minY) minY = y;
if (z < minZ) minZ = z;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
if (z > maxZ) maxZ = z;
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
}
/**
* Gets the id of this region
*
* @return the id
*/
public String getId() {
@@ -90,14 +129,18 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
*
* @return min point
*/
public abstract BlockVector getMinimumPoint();
public BlockVector getMinimumPoint() {
return min;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
public abstract BlockVector getMaximumPoint();
public BlockVector getMaximumPoint() {
return max;
}
/**
* @return the priority
@@ -112,7 +155,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
public void setPriority(int priority) {
this.priority = priority;
}
/**
* @return the curParent
*/
@@ -123,20 +166,20 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Set the curParent. This checks to make sure that it will not result
* in circular inheritance.
*
*
* @param parent the curParent to setFlag
* @throws CircularInheritanceException
* @throws CircularInheritanceException when circular inheritance is detected
*/
public void setParent(ProtectedRegion parent) throws CircularInheritanceException {
if (parent == null) {
this.parent = null;
return;
}
if (parent == this) {
throw new CircularInheritanceException();
}
ProtectedRegion p = parent.getParent();
while (p != null) {
if (p == this) {
@@ -144,7 +187,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
}
p = p.getParent();
}
this.parent = parent;
}
@@ -180,16 +223,16 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Checks whether a region has members or owners.
*
*
* @return whether there are members or owners
*/
public boolean hasMembersOrOwners() {
return owners.size() > 0 || members.size() > 0;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
*
* @param player player to check
* @return whether an owner
*/
@@ -197,41 +240,95 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
if (owners.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param playerName player name to check
* @return whether an owner
*/
public boolean isOwner(String playerName) {
if (owners.contains(playerName)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(playerName)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is a member OR OWNER of the region
* or any of its parents.
*
*
* @param player player to check
* @return whether an owner or member
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
if (isOwner(player)) {
return true;
}
if (members.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)
|| curParent.getMembers().contains(player)) {
if (curParent.getMembers().contains(player)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is a member OR OWNER of the region
* or any of its parents.
*
* @param playerName player name to check
* @return whether an owner or member
*/
public boolean isMember(String playerName) {
if (isOwner(playerName)) {
return true;
}
if (members.contains(playerName)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getMembers().contains(playerName)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
@@ -258,13 +355,13 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
return false;
}
/**
* Get a flag's value.
*
* @param <T>
* @param <V>
* @param flag
*
* @param <T> The flag type
* @param <V> The type of the flag's value
* @param flag The flag to check
* @return value or null if isn't defined
*/
@SuppressWarnings("unchecked")
@@ -278,14 +375,14 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
}
return val;
}
/**
* Set a flag's value.
*
* @param <T>
* @param <V>
* @param flag
* @param val
*
* @param <T> The flag type
* @param <V> The type of the flag's value
* @param flag The flag to check
* @param val The value to set
*/
public <T extends Flag<V>, V> void setFlag(T flag, V val) {
if (val == null) {
@@ -294,94 +391,195 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
flags.put(flag, val);
}
}
/**
* Get the map of flags.
*
* @return
*
* @return The map of flags currently used for this region
*/
public Map<Flag<?>, Object> getFlags() {
return flags;
}
/**
* Get the map of flags.
*
* @param flags
*
* @param flags The flags to set
*/
public void setFlags(Map<Flag<?>, Object> flags) {
this.flags = flags;
}
/**
* Gets the 2D points for this region
*
* @return The points for this region as (x, z) coordinates
*/
public abstract List<BlockVector2D> getPoints();
/**
* Get the number of blocks in this region
*
* @return
*
* @return the volume of this region in blocks
*/
public abstract int volume();
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
*
* @param pt The point to check
* @return Whether {@code pt} is in this region
*/
public abstract boolean contains(Vector pt);
/**
* Compares to another region.
*
* @param other
* Check to see if a point is inside this region.
*
* @param pt The point to check
* @return Whether {@code pt} is in this region
*/
public boolean contains(BlockVector2D pt) {
return contains(new Vector(pt.getBlockX(), min.getBlockY(), pt.getBlockZ()));
}
/**
* Check to see if a point is inside this region.
*
* @param x The x coordinate to check
* @param y The y coordinate to check
* @param z The z coordinate to check
* @return Whether this region contains the points at the given coordinate
*/
public boolean contains(int x, int y, int z) {
return contains(new Vector(x, y, z));
}
/**
* Check to see if any of the 2D points are inside this region.
*
* @param pts
* @return
*/
public boolean containsAny(List<BlockVector2D> pts) {
for (BlockVector2D pt : pts) {
if (contains(pt)) {
return true;
}
}
return false;
}
/**
* Compares to another region.<br>
*<br>
* Orders primarily by the priority, descending<br>
* Orders secondarily by the id, ascending
*
* @param other The region to compare to
*/
public int compareTo(ProtectedRegion other) {
if (id.equals(other.id)) {
return 0;
} else if (priority == other.priority) {
return 1;
} else if (priority > other.priority) {
if (priority > other.priority) {
return -1;
} else {
} else if (priority < other.priority) {
return 1;
}
return id.compareTo(other.id);
}
/**
* Return the type of region as a user-friendly, lowercase name.
*
*
* @return type of region
*/
public abstract String getTypeName();
/**
* Get a list of intersecting regions.
*
* @param regions
* @return
* @throws UnsupportedIntersectionException
*
* @param regions The list of regions to source from
* @return The elements of {@code regions} that intersect with this region
* @throws UnsupportedIntersectionException if an invalid intersection is detected
*/
public abstract List<ProtectedRegion> getIntersectingRegions(
List<ProtectedRegion> regions)
throws UnsupportedIntersectionException;
/**
* Checks if the bounding box of a region intersects with with the bounding
* box of this region
*
* @param region The region to check
* @return whether the given region intersects
*/
protected boolean intersectsBoundingBox(ProtectedRegion region) {
BlockVector rMaxPoint = region.getMaximumPoint();
BlockVector min = getMinimumPoint();
if (rMaxPoint.getBlockX() < min.getBlockX()) return false;
if (rMaxPoint.getBlockY() < min.getBlockY()) return false;
if (rMaxPoint.getBlockZ() < min.getBlockZ()) return false;
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector max = getMaximumPoint();
if (rMinPoint.getBlockX() > max.getBlockX()) return false;
if (rMinPoint.getBlockY() > max.getBlockY()) return false;
if (rMinPoint.getBlockZ() > max.getBlockZ()) return false;
return true;
}
/**
* Compares all edges of two regions to see if any of them intersect
*
* @param region The region to check
* @return whether any edges of a region intersect
*/
protected boolean intersectsEdges(ProtectedRegion region) {
List<BlockVector2D> pts1 = getPoints();
List<BlockVector2D> pts2 = region.getPoints();
BlockVector2D lastPt1 = pts1.get(pts1.size() - 1);
BlockVector2D lastPt2 = pts2.get(pts2.size() - 1);
for (int i = 0; i < pts1.size(); i++ ) {
for (int j = 0; j < pts2.size(); j++) {
Line2D line1 = new Line2D.Double(
lastPt1.getBlockX(),
lastPt1.getBlockZ(),
pts1.get(i).getBlockX(),
pts1.get(i).getBlockZ());
if (line1.intersectsLine(
lastPt2.getBlockX(),
lastPt2.getBlockZ(),
pts2.get(j).getBlockX(),
pts2.get(j).getBlockZ())) {
return true;
}
lastPt2 = pts2.get(j);
}
lastPt1 = pts1.get(i);
}
return false;
}
/**
* Checks to see if the given ID is accurate.
*
* @param id
* @return
*
* @param id The id to check
* @see #idPattern
* @return Whether the region id given is valid
*/
public static boolean isValidId(String id) {
return idPattern.matcher(id).matches();
}
/**
* Returns the hash code.
*/
@Override
public int hashCode(){
return id.hashCode();
}
/**
* Returns whether this region has the same ID as another region.
*/
@@ -390,15 +588,14 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
if (!(obj instanceof ProtectedRegion)) {
return false;
}
ProtectedRegion other = (ProtectedRegion) obj;
return other.getId().equals(getId());
}
/**
* Thrown when setting a curParent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
@@ -37,5 +37,4 @@ public class ProtectedRegionMBRConverter implements MBRConverter<ProtectedRegion
public double getMaxY(ProtectedRegion t) {
return t.getMaximumPoint().getBlockZ();
}
}
@@ -25,17 +25,24 @@ public class ArrayReader<T> {
public ArrayReader(T[] arr) {
this.arr = arr;
}
/**
* Gets an element from the array
* @param index The index to get an element at
* @return The element at {@code index} if the index is within bounds, otherwise null
*/
public T get(int index) {
if (arr.length > index) {
return arr[index];
} else {
return null;
}
return get(index, null);
}
/**
* Gets an element from the array
* @param index The index to get an element at
* @param def the default value, used when the given index is out of bounds
* @return The element at {@code index} if the index is within bounds, otherwise the default value
*/
public T get(int index, T def) {
if (arr.length > index) {
if (index >= 0 && arr.length > index) {
return arr[index];
} else {
return def;
@@ -0,0 +1,6 @@
package com.sk89q.worldguard.util;
public class FatalConfigurationLoadingException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more