Compare commits

...
263 Commits
Author SHA1 Message Date
wizjany c35686f8d1 [maven-release-plugin] prepare release 5.7.5 2013-05-26 17:20:00 -04:00
wizjany a5b6651582 Update CHANGELOG for 5.7.4 and 5.7.5 2013-05-26 17:10:35 -04:00
wizjany 54973fdf82 Large patch with lots of changes and fixes.
- Unified movement checking. Teleporting is now handled by
  entry/exit flags. Additionally, a region movement event is
  much closer to being added.
- Fixed an issue with enderpearls and exit/entry flags conflicting.
- Fixed a null check issue in several commands.
- Fixed allowed and blocked command flags making false matches and
  improved support for blocking/allowing specific command args.
2013-05-26 17:08:51 -04:00
wizjany 0bee631385 Use getName instead of toString for displaying world name. 2013-05-15 07:56:04 -04:00
wizjany 6283382837 Fixed a few movement flag related issues.
WG no longer prefixes greeting/farewell flags with '**', allowing people to customize the message.
(Adding &c** to the beginning of the message will give previous behavior)
Removed the "game mode locked" message since it returns false gamemodes when being called inside a player move event.
2013-05-05 10:57:46 -04:00
Silthus 39bb522051 Fixes heal flag bugs when player.maxHealth > 20
With the new Bukkit Changes the Player Health can be above 20, this fixes the magic number by using the now built in Bukkit functionality.

Examples of this bug were Health jumping to 1/20 hearts when having a heal-amount: -1
2013-05-04 11:47:43 +03:00
wizjany bf80d57abe Add fishing to xp blocker. 2013-04-21 08:59:24 -04:00
wizjany 865b94006a Apply other-explosion flag to entity damage as well. 2013-04-09 17:23:56 -04:00
wizjany 874248f8b5 Fix other explosion flag only clearing blocklist 2013-04-09 12:25:05 -04:00
steffen cef7d5bb12 Fix explosion check order
If the explosion is blocked and the block damage is also blocked, it's necessary to block the explosion (which includes the damage) instead of just the block damage.
2013-04-01 18:34:11 -04:00
wizjany 2a8131780f Don't ignore canceled air right click events.
Apparently Bukkit pre-cancels them even if they would do something.
2013-03-31 19:13:05 -04:00
Wizjany 7094f70f4a Remove duplicate check. (derp) 2013-03-31 19:13:04 -04:00
wizjany df5af6129c Improved lighter handling. 2013-03-23 21:10:30 -04:00
wizjany a6888c3767 Respect LIGHTER flag for ignition build checks 2013-03-23 15:19:56 -04:00
wizjany 1bd367ddde Fix one last witherskull/fireball conflict 2013-03-22 19:28:18 -04:00
wizjany 0cf87ae561 Allow cow milking in no-build areas 2013-03-22 15:35:30 -04:00
wizjany fa80f5f67f Fix infinite durability.
For whatever reason, the Bukkit API thinks that 'Durability" and "Damage"
are synonymous.
2013-03-18 13:25:11 -04:00
sk89q 7f080f920d [maven-release-plugin] prepare for next development iteration 2013-03-16 22:17:14 -07:00
sk89q 13658323b4 [maven-release-plugin] prepare release 5.7.3 2013-03-16 22:16:51 -07:00
sk89q 2d440ab5ba Cleaned up pom.xml. 2013-03-16 22:01:14 -07:00
sk89q dc55673691 Updated changelog for 5.7.3. 2013-03-16 21:12:26 -07:00
wizjany 92bb3948a6 Fix for minecart naming 2013-03-16 21:47:31 -04:00
wizjany f67ad6478c [maven-release-plugin] prepare for next development iteration 2013-03-15 16:01:09 -04:00
wizjany 1d984198ce [maven-release-plugin] prepare release 5.7.2 2013-03-15 16:01:02 -04:00
wizjany f2ca980771 Update changelog to 5.7.2 2013-03-15 15:44:48 -04:00
wizjany b826697aea Add flag check to smelting/mining xp handling 2013-03-15 15:44:34 -04:00
wizjany 89430c13ec Handle TNT Minecarts with tnt flag/settings. 2013-03-15 15:32:57 -04:00
Wizjany f07acea3e1 Updated to MC 1.5 2013-03-15 14:42:20 -04:00
wizjany e9402c55e6 Fixed a bunch of small bugs 2013-03-14 18:45:05 -04:00
wizjany 2eb6c76da8 Fix stack issue. 2013-03-13 14:38:28 -04:00
Wizjany a34e48a145 Added unit test for entry and exit flags to put the matter to rest.
Also cleaned up a few other things regarding tests.
2013-03-01 22:20:16 -05:00
Wizjany 2d50659b48 Apply exp flag and config setting to xp bottles.
"Workaround" for not being able to blacklist exp bottles at the moment.
Although I supposed I could have just fixed that instead, this allows more flexibility.
2013-02-21 10:20:47 -05:00
Wizjany 327ae2b807 Apply crop trampling setting to all entities. 2013-02-21 10:13:17 -05:00
Wizjany dfb6114584 Fix a few wolf issues 2013-01-31 08:23:38 -05:00
Wizjany 5085841d9d [maven-release-plugin] prepare for next development iteration 2013-01-30 16:26:26 -05:00
Wizjany 7a98944469 [maven-release-plugin] prepare release 5.7.1 2013-01-30 16:26:20 -05:00
Wizjany 3d2b455cda Update changelog for 5.7.1 2013-01-30 16:21:55 -05:00
Wizjany 460d5d0691 Made wolves respect pvp stuff. Removed some extraneous code. 2013-01-30 15:27:52 -05:00
Wizjany b5f80351ec Allow a lot of commands to be sent from the console.
Examples:
 /rg addmem <id> <player> -w <worldname>
 /rg flag <id> <flag> -w <worldname> <flagvalue>
 /rg remove <id> -w <worldname>
Command blocks are currently untested.
List of commands: flag, priority, parent, remove,
 addmember, removemember, addowner, removeowner
2013-01-30 14:45:29 -05:00
Wizjany 72a9472a57 Add vine growth flag and config option. 2013-01-30 14:02:45 -05:00
Wizjany 7eb820c688 Fixed bug where players could place beds on the borders of regions without permissions 2013-01-30 13:47:48 -05:00
Wizjany 886b279da6 Bugfixes for bonemeal and minecarts. 2013-01-27 22:43:29 -05:00
Wizjany f2d7135fc5 Check shooter of projectile when one hits a hanging entity 2013-01-25 21:07:11 -05:00
Wizjany d214a859c3 Check the block that the item frame will end in, not the block the player clicked. 2013-01-21 04:08:17 -05:00
Wizjany d1e221c2b7 Don't cancel explosion if we only want to clear blocklist. May potentially cause issues with multiple settings overlapping. 2013-01-19 08:46:51 -05:00
Dark Arc e0e4207a4d Apply a cap to the health and hunger flags to prevent possible exceptions
If a player's health or hunger is set to higher than its respective maximum CraftBukkit will throw exceptions.
2013-01-16 14:48:39 -05:00
Wizjany 4398c781c5 Wither skulls should be handled separately from fireballs 2013-01-15 18:23:53 -05:00
Wizjany 3e06000fd9 Workaround for CraftBukkit bug with slab placement 2013-01-15 16:06:42 -05:00
Wizjany 833795ebe1 Add enderchest and anvil to blacklist inventories. 2013-01-14 13:31:54 -05:00
Wizjany 6e270d5ec3 Setting summary-on-start to false reduces much more clutter now 2013-01-13 17:21:51 -05:00
Wizjany 09a9bea3a7 Move enderchest to use flag 2013-01-13 16:10:06 -05:00
Wizjany 035ccee2a6 Fixed placing stuff in flower pots. (derp) 2013-01-13 13:44:54 -05:00
Wizjany 17aa2a4153 Fix region teleport permission 2013-01-13 06:13:41 -05:00
Wizjany f5bc5c0b47 That was not in there 2013-01-13 03:48:11 -05:00
Wizjany e7a4afde7d [maven-release-plugin] prepare for next development iteration 2013-01-13 03:08:17 -05:00
Wizjany 8758c9b940 [maven-release-plugin] prepare release 5.7 2013-01-13 03:08:13 -05:00
Wizjany a569d20779 Remove max players flag for now.
There are currently too many unhandled circumstances
which can easily break this flag such as players
entering region in weird ways (teleporting, falling,
logging in) and states changing. It is also horribly
inefficient at the moment.
2013-01-13 02:34:34 -05:00
Wizjany 88e01fa083 Fix enderpearl flag properly 2013-01-12 11:39:59 -05:00
Wizjany 7b435f9283 Added changelog for 5.7. Incremented version in pom.xml. 2013-01-12 00:25:55 -05:00
Wizjany a240e5d128 Added config option to block zombies from breaking down doors 2013-01-12 00:25:55 -05:00
Wizjany 0d0ba31d3a Fixes for tripwire, flower pots, wooden buttons, ender chests, and sneaking 2013-01-12 00:25:54 -05:00
Wizjany e79bb3533d Fireball flag should block blaze fireball ignition too now 2013-01-12 00:25:54 -05:00
Wizjany f94c4ec831 Mob damage setting/flag blocks poison DoT 2013-01-12 00:25:54 -05:00
Wizjany d5afb76105 Added config setting and flag to block explosions by plugins. 2013-01-12 00:25:53 -05:00
Wizjany dd7e9ba05e Add enderpearl flag to prevent players from teleporting to/from regions with enderpearls 2013-01-11 18:21:20 -05:00
Wizjany ee54698fdb Fix players being able to plant cocoa beans in protected areas 2013-01-11 17:54:29 -05:00
Wizjany 955b0e991c Added MAX_PLAYER and MAX_PLAYER_MESSAGE flags
Allows setting maximum number of players in a region
and sends a message if a region is at capacity.
2013-01-11 17:09:15 -05:00
Dilandau c1b98b9e40 Decrease call to PluginManager in WGBukkit
If WorldGuard is already found we bypass the call to
the PluginManager and use a cached version.
2013-01-11 16:16:49 -05:00
Dark Arc d6939b7916 Allow EnderPearls to damage the player who threw them in no-pvp areas 2013-01-02 19:46:41 -05:00
Dark Arc 5f0ca37879 Add support for blocking sub commands 2013-01-02 19:03:22 -05:00
Wizjany 548bdb7eb5 Attempt to fix item frame issues 2012-12-31 17:03:14 -05:00
Wizjany 5c85f39228 Block snowballs in pvp regions again. Reverts 671fd58568 2012-12-30 15:11:19 -05:00
Wizjany 85b2cbc03a Null check for entity explosions without an entity. 2012-12-29 11:46:24 -05:00
Wizjany cc78011da6 Build on latest Bukkit snapshot. Closes WORLDGUARD-2381
Fixes EntityChangeBlockEvent errors. Note that 1.4.5-R0.3-SNAPSHOT means build 2505+ and that there ARE 0.3 snapshots below 2505. Thus, this should be treated as temporary and changed on the next Bukkit Beta.
2012-12-29 11:46:14 -05:00
Dark Arc d016da1895 Resolves WORLDGUARD-2316 TNT still lethal when its damage is disabled 2012-11-24 02:42:28 -05:00
Dark Arc 8593f1c80a Resolves WORLDGUARD-2352 Anvils usable despite the use flag 2012-11-24 02:25:59 -05:00
Dark Arc 0b3c40dc3e Implements WORLDGUARD-2315 Enderdragon portal blocking 2012-11-24 02:17:34 -05:00
sk89q 2e7ecc59c0 Fixed typo where BEACON was COMMAND_BLOCK instead. 2012-11-11 19:08:31 -08:00
sk89q 942ce95dbf Fixed #WORLDGUARD-2297, Beacons are not protected in regions. 2012-11-11 18:45:55 -08:00
sk89q 03f77d5ab7 Fixed #WORLDGUARD-2296, Recent fix for dragon eggs in regions not working for left click. 2012-11-11 18:43:34 -08:00
sk89q 8dec32fa6a Added workaround for #WORLDGUARD-2299, java.lang.IllegalArgumentException: Instant potions cannot be extended. 2012-11-11 18:41:18 -08:00
sk89q 8f409d47d9 Fixed #WORLDGUARD-2289, FlagStateManager is not thread synced with the main thread. 2012-11-11 18:36:08 -08:00
sk89q 93f062d4e3 Hey, we have a mailing list now! Subscribe! https://groups.google.com/d/forum/sk-dev-discuss 2012-11-07 13:00:44 -08:00
Dark Arc b8f9ceafbb Resolves comma issue relating to flag listing
This stops commas from being added when a player types in an invalid flag and the player does not have permission to use one or more of the flag that are listed.
2012-11-07 14:20:44 -05:00
sk89q 75d07b6dad [maven-release-plugin] prepare for next development iteration 2012-11-07 09:19:50 -08:00
sk89q 6060a0a430 [maven-release-plugin] prepare release 5.6.5 2012-11-07 09:19:35 -08:00
sk89q 647ba1572c Updated CHANGELOG.txt for 5.6.5. 2012-11-07 09:10:20 -08:00
sk89q 051e0cb811 Fixed regression bug cause item frames and paintings to not be protected. 2012-11-07 09:07:38 -08:00
sk89q b8c9e78910 [maven-release-plugin] prepare for next development iteration 2012-11-06 20:39:09 -08:00
sk89q 2d7d9c6093 [maven-release-plugin] prepare release 5.6.4 2012-11-06 20:38:50 -08:00
sk89q 0f32f56208 Updated CHANGELOG.txt for 5.6.4. 2012-11-06 20:35:18 -08:00
sk89q 5addfd8975 Added security.deop-everyone-on-join and security.block-in-game-op-command. 2012-11-06 20:32:15 -08:00
sk89q 7f108ce8f0 Changed dragon eggs to be checked like it is a broken block in regions. 2012-11-06 20:19:16 -08:00
sk89q 8c883e1ca8 WGBukkit is not supposed to be there. Now in com.sk89q.worldguard.bukkit. 2012-11-06 19:26:05 -08:00
sk89q d18fe6ffa0 Worked around bug with water potions causing errors. 2012-11-06 19:21:12 -08:00
sk89q 80a8ac9e98 Added mobs.block-above-ground-slimes to block slimes spawning naturally above ground (in swamps). 2012-11-06 18:49:32 -08:00
Dark Arc 671fd58568 Stop snowball blocking 2012-11-06 18:59:08 -05:00
Dark Arc c4ea3b59f0 Resolve WORLDGUARD-2281, for Dispensers 2012-11-06 18:44:36 -05:00
Dark Arc 5d5def206d Actually corrected Javadoc 2012-11-06 18:07:26 -05:00
Dark Arc b2ebbb9b55 Corrected Javadoc 2012-11-06 18:04:22 -05:00
Dark Arc 3734c071bf Fixes WORLDGUARD-2281, NPE on Water Potion Drinking
This resolves the issue where WorldGuard would throw a NullPointerException when a player drank a potion of water while potion blocking was enabled.
2012-11-06 18:01:13 -05:00
sk89q b1a419f2a2 [maven-release-plugin] prepare for next development iteration 2012-11-05 12:40:01 -08:00
sk89q bf5e292160 [maven-release-plugin] prepare release 5.6.3 2012-11-05 12:39:46 -08:00
sk89q df57d91270 Possibly fixed the ladder setting. 2012-11-05 12:28:40 -08:00
sk89q 4da1741578 kekekeke forgot static in WGBukkit's methods. 2012-11-05 12:22:04 -08:00
sk89q 7a3774e730 Updated CHANGELOG.txt for 5.6.3. 2012-11-05 12:20:13 -08:00
sk89q e6e21caeea Added helper WGBukkit class to get references to WorldGuard in other Bukkit plugins. 2012-11-05 12:12:25 -08:00
sk89q 200d47ab09 Added physics.vine-like-rope-ladders to make ladders work like vines. 2012-11-05 11:32:40 -08:00
sk89q ab274151d4 Potential fix for WORLDGUARD-2263, mobs.block-{item-frame,painting}-destroy not working. 2012-11-05 11:27:35 -08:00
sk89q aec1e3a529 Fixed NPE in PlayerInteractEvent due to potion blocking. Fixes WORLDGUARD-2269. 2012-11-05 11:09:14 -08:00
sk89q 916caa1eb2 [maven-release-plugin] prepare for next development iteration 2012-11-04 14:49:50 -08:00
sk89q 50b29f8ad6 [maven-release-plugin] prepare release 5.6.2 2012-11-04 14:49:35 -08:00
sk89q 88d662cf27 Updated CHANGELOG.txt for 5.6.2. 2012-11-04 14:48:30 -08:00
sk89q 5316130ae8 Better handle potion blocking with dispensers/splash potions. 2012-11-04 14:46:36 -08:00
sk89q 4f36dbc636 [maven-release-plugin] prepare for next development iteration 2012-11-04 13:48:25 -08:00
sk89q 230a8697bf [maven-release-plugin] prepare release 5.6.1 2012-11-04 13:48:08 -08:00
sk89q 121449b230 Updated changelog for 5.6.1. 2012-11-04 13:44:52 -08:00
sk89q fede549b51 Added gameplay.block-potions. 2012-11-04 13:42:55 -08:00
sk89q 1bdd7f9a6b Fixed a tab issue with WorldGuardBlockListener due to the mycelium commit. 2012-11-04 13:12:06 -08:00
sk89q b3f9da67b7 Changed version to 5.6.1-SNAPSHOT. 2012-11-04 13:06:35 -08:00
sk89q 1ba7d623b4 Adds null check in EntityExplodeEvent's handler, fixing WORLDGUARD-2267. 2012-11-04 13:05:25 -08:00
Gabriel Harris-Rouquette 47902e1177 Added mycelium-spread flags. 2012-11-03 15:31:16 -07:00
sk89q a035bcc671 [maven-release-plugin] prepare for next development iteration 2012-11-03 12:38:06 -07:00
sk89q 9bcc6b9605 [maven-release-plugin] prepare release 5.6 2012-11-03 12:37:52 -07:00
sk89q 282c3a864e Updated CHANGELOG.txt for 5.6. 2012-11-03 12:15:43 -07:00
sk89q eb083a8934 Updated README.html to mention the moved spawn-protection setting, added more explanations. 2012-11-03 12:15:43 -07:00
sk89q 0fc71ff79e Note the issue tracker in README.html. 2012-11-03 12:15:43 -07:00
sk89q 68a7455496 Added backwards compatibility for versions below MC1.4. 2012-11-03 12:15:43 -07:00
Dark Arc fcfc3acbb8 Improved Performance of some operations
Replaced quite a few whiles and fors with for-eachs giving a performance gain. Also fixed a few issues with the MySQLDatabase and made several other minor improvements.
2012-11-03 00:19:40 -04:00
sk89q aa53c0aa6a We have a new issue tracker. 2012-11-02 18:15:02 -07:00
Dark Arc f098905a92 Fixes WORLDGUARD-2205
Mob Damage from projectiles is now properly blocked in regions where applicable.
2012-11-02 21:07:38 -04:00
Dark Arc eec78092b5 Allow damage to be less than 1
This resolves problems with mods that use fake damage events to check with WorldGuard what's going on.
2012-11-02 20:57:24 -04:00
sk89q 34fa5eceb8 Fixed WORLDGUARD-2255, where region.getId() was lowercase'd each pass of a for loop in MySQLDatabase.updatePoly2dPoints(). 2012-11-02 14:13:53 -07:00
Dark Arc c32d2dd6f8 Fixes WORLDGUARD-2254
Players will now be told that they are in a no-PvP area if they are in one and attempting to attack someone, or that the player they are attacking is in a no-PvP area, if that is the case instead.
2012-11-02 17:06:35 -04:00
Dark Arc da80d3536a Fixes WORLDGUARD-2253
Players who are not in god mode will once again receive damage in PVP areas from Ender Pearls.
2012-11-02 17:06:33 -04:00
sk89q e9361022d2 Protected against using (right-clicking) paintings and item frames. 2012-11-02 13:41:53 -07:00
sk89q dd0c1a5ab5 Fixed Withers still breaking blocks if they smash their bodies into them. Fixes WORLDGUARD-2245. 2012-11-02 12:20:59 -07:00
Wojciech Stryjewski bb9dff7b8c Deleting a region flag also deletes group flag
The group flags set with /region flag -g have no effect if the
normal flag is not also set, nor will they be displayed with
/region info once the normal flag is deleted. However, if a
group flag was to remain set in the database, the next time a
user sets the normal flag, they might be surprised to suddenly
see the corresponding group set as well.

Since the -g group is presented to the user as an attribute of
the normal flag, rather than a standalone flag, the group flag
should be deleted along with the normal flag.
2012-11-01 22:43:24 -07:00
Wojciech Stryjewski 7e419c116e Allow /region flag to set group and value at once
The usage for "/region flag" implies both can be set at once:
/region flag <id> <flag> [-g group] [value]

However if the [-g group] [value] portions are specified, only
the group is set and the value is silently ignored. With this
commit, both values can be set at once. All other behavior of
the "flag" command is preserved. If only the [-g group] part is
given, then only the group flag changes and the regular flag's
value is unaffected. If neither part is given, then the flag is
cleared.
2012-11-01 22:43:23 -07:00
Wojciech Stryjewski 2cbc2f5226 Allow removing of -g group flags with /region flag
The @Command parser requires that a value follow the -g option when
used in /refion flag. Therefore, it's not possible to remove the -g
flag by omitting it's value, as it is possible with the regular flags.

Rather, if the group flag is set to what would be the default region
group for the normal flag, then the group flag is actually removed
and the user sees a "Region group flagfor '...' reset to default."
message.
2012-11-01 22:43:23 -07:00
Wojciech Stryjewski 68b5e3e0a8 Improve /region info output for -g group flags
If a region group flag has been set with the -g option to /region flag
the /region info command will not show it at all because these group
flags are not in the DefaultFlag.getFlags() array.

With this code change, if a group flag has been set on "entry" for
example, it might be shown as "Flags: entry -g OWNERS: ALLOW".
2012-11-01 22:43:23 -07:00
BangL 1502ec12a9 Added support for the hanging events, an item frame destroy region flag, and a mobs.block-item-frame-destroy setting.
Now also using Bukkit 1.4.2-R0.2-SNAPSHOT and WorldEdit 5.4.4-SNAPSHOT.
2012-11-01 22:35:15 -07:00
sk89q 6d09b18479 Check for both LARGE_FIREBALL and FIREBALL for the EntityType in the entity listener.
This is to counteract a breaking Bukkit change.
2012-10-30 09:24:10 -07:00
Dark Arc 08ce207636 Fixed bugs in the PRTreeRegionManager class:
* Point would not be returned if the player was at point which exceeded the flat decimal maximum of a region.
* The getAplicableRegionIDs method would not return the parents of a region.
* All test would fail
2012-10-29 12:14:11 -07:00
sk89q f199b977eb Added more tests for the PRTreeRegionManager to fail. 2012-10-29 12:14:10 -07:00
sk89q 5715e2c835 WorldGuard has good unit tests for regions, why not use them for PRTreeRegionManager?
LET'S WATCH THE WORLD BURN.
2012-10-29 12:14:10 -07:00
sk89q b8642b7ca3 Tiny change to PRTree version to make it load a Java6 compile. 2012-10-29 12:14:10 -07:00
Wizjany 2c4d4708d8 Added parent region checking to PRTree manager as per Dark_Arc's specifications. 2012-10-29 12:14:10 -07:00
Darth Android 0edb6e6157 Include the PRTree library in generated artifacts 2012-10-29 12:14:10 -07:00
Darth Android 4f394b5668 Update PRTree library to v1.5
Updated PRTreeRegionManager code to support 3D points and regions
Changed region manager to PRTreeRegionManager
2012-10-29 12:14:09 -07:00
Glitchfinder 9834c30e3a Adding and fixing support for new and existing explosion types. 2012-10-28 20:23:36 -07:00
sk89q f3f1b0870f Changed default region wand to leather (#334). 2012-10-28 14:12:10 -07:00
sk89q 915d314c18 Removed <modules> that magically appeared thanks to Eclipse. 2012-10-28 14:07:41 -07:00
sk89q 02b3ae6aa5 Added mobs.block-wither-block-damage. 2012-10-28 14:01:17 -07:00
sk89q f725e73653 Move to WG 5.6-SNAPSHOT and Bukkit 1.4.2-R0.1-SNAPSHOT. 2012-10-28 14:01:17 -07:00
sk89q c5858ef202 Removed <packaging> from pom.xml. 2012-10-28 13:56:46 -07:00
sk89q ba2fd2ca2e Brought README.md and CONTRIBUTING.md inline with latest updates. 2012-10-28 13:54:06 -07:00
Wojciech Stryjewski 1075d36748 Fix spurious comma in "Flags:" /region info output
When the "/region info" command displays any flags in the region,
it always prints an extra leading comma character after the
"Flags:" prompt.
2012-10-24 12:48:38 -05:00
sk89q 3ee3799e55 I'm OCD like that. Changed WG->${project.name} in readme, added license ver. to README.md. 2012-10-24 00:29:20 -07:00
sk89q 6654b0a67a More readme cleanup. 2012-10-24 00:29:20 -07:00
sk89q 9577c93edb Better place for README.md logo URL. 2012-10-24 00:29:20 -07:00
sk89q 7cd67281bc Move extraneous files to contrib/, added region_storage_update_20110325.sql to assembly. 2012-10-24 00:29:20 -07:00
sk89q d21c226183 Modernized README.html. 2012-10-24 00:29:19 -07:00
sk89q 4322236b9e Updated the ancient README.html. 2012-10-24 00:29:19 -07:00
sk89q 05e408ee65 Updated README.md. 2012-10-24 00:29:19 -07:00
sk89q 3d1012ba94 Cleaned up pom.xml and updated CommandBook to 2.1. 2012-10-24 00:29:19 -07:00
sk89q 94937e41ef Changed the region MySQL database to marshal and unmarshal values using YAML, which should fix the notable problems regarding non-string flag data types. 2012-10-24 00:28:43 -07:00
sk89q 3957aa83fc Say hi to travis-ci. 2012-10-24 00:28:43 -07:00
Rutr 8aa79d1c4c Fixed detection damager(when attac by magic) http://redmine.sk89q.com/issues/901 2012-10-19 09:02:19 +02:00
sk89q 578eeff0e1 [maven-release-plugin] prepare for next development iteration 2012-10-07 10:47:07 -07:00
sk89q 5f2f1c67f5 [maven-release-plugin] prepare release 5.5.4 2012-10-07 10:46:51 -07:00
sk89q c92b9c3d97 Updated CHANGELOG.txt. 2012-10-07 10:40:00 -07:00
sk89q 0951d00da3 Fixed permissions for region loading/saving. 2012-10-06 21:47:37 -07:00
zml2008 6df9c3660b Merge pull request #201 from eric-wieser/patch-1
Did `wcfg.useRegions` really need to be checked twice?
2012-09-16 12:31:17 -07:00
Alexander 19be2bf96e Updated fireball item blocking 2012-08-23 12:41:36 +02:00
Fletch to 99 e10ed6ac7a Report the amount of plugins loaded 2012-08-12 16:56:22 -03:00
sk89q 479ebf4d89 Copying and pasting is bad. Fixed references of worldedit -> worldguard in new pom.xml changes. 2012-08-11 00:28:02 -07:00
sk89q 1f1e36e9f7 Updated pom.xml for license, distributionManagement, maven-site-plugin. 2012-08-11 00:26:06 -07:00
TomyLobo 27e634ae03 Fixed a warning. 2012-08-11 04:37:49 +02:00
unknown e60b20b37b Add 'use' flag to cakes 2012-08-10 22:33:55 +02:00
zml2008 684214ff6a Update for async player chat stupidity 2012-08-04 19:56:48 -07:00
sk89q ba5be6071f Added regions.use-creature-spawn-event configuration setting. 2012-07-23 13:45:04 -07:00
TomyLobo 6c8d13690e Fixed eggs, snowballs and the likes being dupable with /stack. 2012-07-16 16:08:04 +02:00
TomyLobo 3e0b2ef3e4 Upped Bukkit dependency version to 1.2.4-R4.1. 2012-07-14 00:16:45 +02:00
sk89q c5304d2775 [maven-release-plugin] prepare for next development iteration 2012-07-07 10:55:58 -07:00
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
Eric Wieser acb1d18654 Did wcfg.useRegions really need to be checked twice? 2012-04-28 18:18:51 +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
110 changed files with 5939 additions and 3086 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
language: java
jdk:
- oraclejdk7
- openjdk7
- openjdk6
notifications:
email: false
+214 -1
View File
@@ -1,3 +1,216 @@
5.7.5:
- Refixed a few issues from 5.7.4.
5.7.4:
- BREAKING CHANGE: Removed the cyan "**" in front of greeting
and farewell messages to allow more customizability. You can
re-add them by adding "&c**" to the flag.
- Fixed an issue enderpearling inside exit/entry deny regions.
- Added checks to players teleporting in and out of exit/entry regions.
- Fix bad matching in blocked and allowed command flags.
- Fixed heal flag bugs when player max health was increased.
- Add fishing to xp blocker.
- Applied other-explosion flag to entity damage as well.
- Fixed an issue with interaction that should allow blacklisting item use actions with no block involved (eg fishing rods, potions)
- Fix witherskull/fireball settings not being differentiated in one case
- Allow cow milking in no-build areas
- Fix infinite durability breaking items instantly.
5.7.3:
- Fixed the error caused by Bukkit's change of the TNT minecart API.
5.7.2:
- Updated to MineCraft 1.5.
- Added TNT Minecart support. They are handled with the same flags/settings as TNT.
- Added mining and smelting xp handling to the xp drops flag and setting.
- Fixed a few edge cases for placing items on region borders.
- Legacy: Fixed issue with //stack not respecting item metadata.
5.7.1:
- Added a vine growth config option and flag.
- Added support for many commands to be used from console.
Usage is with -w flag and a world name e.g.
/rg addmem <id> <player> -w <worldname>
/rg flag <id> <flag> -w <worldname> <flagvalue>
- Fixed bug that blocks placing plants in flower pots.
- Fixed permissions check for /rg tp
- Fixed enderchests not being accessible (they are now part of the USE flag)
- Fixed an issue with slabs being placable in protected regions. This was
also fixed in CraftBukkit but has been left in for users running other versions.
- Fixed wither skulls being handled with other fireballs, despite having their own settings.
- Fixed item frames being placable on region borders.
- Fixed a bug that made explosions more ineffective than they should have been.
- Fixed bonemeal usage in protected regions.
- Fixed special minecarts being placable in protected regions.
- Fixed bugs being placable on region borders.
- Fixed wolves bypassing pvp flags.
5.7:
- Fixed thread sync issue with FlagStateManager.
- Fixed dragon egg region protection not working in certain cases.
- Added beacon and anvil usage protection in regions.
- Add mobs.block-enderdragon-portal-creation to stop enderdragons
from making portals on death.
- Fix TNT being lethal in some case when damage was disabled.
- Fix snowballs and enderpearls being able to knock players back in
pvp deny regions.
- Add subcommand support for allowed and blocked command flags.
- Add max-players-allowed and max-players-reject-message flags to
limit the numbers of players in a region.
- Fix players being able to plant cocoa beans in protected areas.
- Add an enderpearl flag to prevent players from teleporting to and
from regions.
- Added mobs.block-other-explosions config setting and other-explosion
flag to block explosions caused by uncovered things, such as other
plugins. (It doesn't actually have to be a mob)
- Fix mob damage setting and flag not blocking the DoT wither effect.
- Ghast fireball flag will not block blaze fireballs from lighting things
on fire.
- Fixed players without region permissions being able to trigger tripwires,
use enderchests, use wooden buttons, and put plants in flower pots.
- Added mobs.block-zombie-door-destruction setting to stop zombies from
breaking down doors while difficulty is set to hard.
Thank you to thvortex, Dilandau, tophathacker, and Dark_arc for their contributions this release.
5.6.5:
- Fixed a regression that caused paintings and item frames to no longer be properly
protected.
5.6.4:
- Added mobs.block-above-ground-slimes to block slimes spawning naturally above ground.
- Added security.deop-everyone-on-join to de-op all players when they join.
- Added security.block-in-game-op-command to prevent usage of /op from in-game.
- Fixed a NullPointerException in PlayerInteract involving water potions and
potion blocking.
- Fixed an issue with snowballs being blocked in regions.
- Changed dragon eggs to be checked like it is a broken block in regions.
- Moved developer's WGBukkit class to package com.sk89q.worldguard.bukkit.
5.6.3:
- Added helper WGBukkit class to get references to WorldGuard from other plugins.
- Added physics.vine-like-rope-ladders to make ladders work like vines. As long as the
top ladder block is present, ladder blocks will hold even if they have no block
behind them, like a rope ladder.
- Fixed NullPointerException in PlayerInteractEvent caused by potion blocking.
- Fixed mobs.block-{item-frame,painting}-destroy not working.
Thank you to def for testing the above fixes and features.
5.6.2:
- Fixed potion blocking not working well for splash potions.
5.6.1:
- Added a mycelium-spread region flag.
- Added a dynamics.disable-mycelium-spread configuration setting.
- Added new gameplay.block-potions option. For example:
gameplay:
block-potions: [invisibility, speed]
- Fixed a bug in the entity explosion event handler that caused a NullPointerException.
Thank you for gabizou for his contribution in this release.
5.6:
- Added official support for Minecraft 1.4. Support for 1.3.2 (and below) is still
provided in this release.
- Added support for new and existing explosion types.
- Added support for blocking withers with the following settings:
mobs:
block-wither-explosions: false
block-wither-block-damage: false
block-wither-skull-explosions: false
block-wither-skull-block-damage: true
- Added support for blocking item frames (and their use) in protected regions.
- Added item frame destruction region flags (if you wish to disable item frame
destruction completely).
- (Re-)added support for priority R-tree region indexes. This means quicker region lookup,
and better support for servers with thousands of regions.
- Improved /region info output for -g group flags.
- Allowed removing of -g group flags with /region flag.
- Allowed /region flag to set group and value at once.
- Deleting a region flag now also deletes group flag.
- Fixed detection of attack by projectiles to be more accurate.
- Fixed support for saving non-string flags in the MySQL region support.
- Fixed spurious comma in "Flags:" /region info output.
- Fixed players who are not in god mode not receiving damage in PVP areas from
enderpearls.
- Players will now be told that they are in a no-PvP area if they are in one and
attempting to attack someone, or that the player they are attacking is in a
no-PvP area, if that is the case instead.
- Fixed an issue where region.getId() was lowercase'd each pass of a for loop in
MySQLDatabase.updatePoly2dPoints().
- Fixed mob damage from projectiles not being properly blocked in regions where
applicable.
- Changed default region wand to leather (#334).
Thank you to the following individuals for their contribution:
thvortex, Rutr, Glitchfinder, and DarthAndroid.
5.5.4:
- Minecraft 1.3 support.
- Fixed /stack dupe bugs.
- Added regions.use-creature-spawn-event.
- Update for Async chat issue.
- Add use flag to cakes.
- Report number of plugins loaded in report writer.
- Updated fireblal item blocking.
- Fixed permissions for /region reload.
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
@@ -355,4 +568,4 @@ EduardBaer, TomyLobo, and halvors
- Added block lag fix.
1.0
- Initial release.
- Initial release.
+69
View File
@@ -0,0 +1,69 @@
Contributing
============
Thank you for your interest in contributing to WorldGuard! We appreciate your
effort, but to make sure that the inclusion of your patch is a smooth process, we
ask that you make note of the following guidelines.
* **Follow the [Oracle coding conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html).**
We can't stress this enough; if your code has notable issues, it may delay
the process significantly.
* **Target Java 6 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
and other such tasks easier. Ignore this guideline if it makes the code
too unreadable.
* **Write complete Javadocs.** Do so only for public methods, and make sure
that your `@param` and `@return` fields are not just blank.
* **Don't tag classes with @author.** Some legacy classes may have this tag,
but we are phasing it out.
* **Make sure the code is efficient.** One way you can achieve this is to spend
around ten minutes to think about what the code is doing and whether it
seems awfully roundabout. If you had to copy the same large piece of
code in several places, that's bad.
* **Keep commit summaries under 70 characters.** For more details, place two
new lines after the summary line and write away!
* **Test your code.** We're not interested in broken code, for the obvious reasons.
* **Write unit tests.** While this is strictly optional, we recommend it for
complicated algorithms.
Checklist
---------
Ready to submit? Perform the checklist below:
1. Have all tabs been replaced into four spaces? Are indentations 4-space wide?
2. Have I written proper Javadocs for my public methods? Are the @param and
@return fields actually filled out?
3. Have I `git rebase`d my pull request to the latest commit of the target
branch?
4. Have I combined my commits into a reasonably small number (if not one)
commit using `git rebase`?
5. Have I made my pull request too large? Pull requests should introduce
small sets of changes at a time. Major changes should be discussed with
the team prior to starting work.
6. Are my commit messages descriptive?
You should be aware of [`git rebase`](http://learn.github.com/p/rebasing.html).
It allows you to modify existing commit messages, and combine, break apart, or
adjust past changes.
Example
-------
This is **GOOD:**
if (var.func(param1, param2)) {
// do things
}
This is **EXTREMELY BAD:**
if(var.func( param1, param2 ))
{
// do things
}
+204 -88
View File
@@ -1,116 +1,232 @@
<!DOCTYPE html>
<html>
<head>
<title>WorldGuard ${version}</title>
<title>${project.name} ${version}</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Ropa+Sans" rel="stylesheet" type="text/css">
<style>
body {
margin: 0;
padding: 20px;
background: #efefef;
color: #333;
margin: 0;
padding: 3em 1em;
background: #efefef;
color: #333;
line-height: 1.5;
}
#wrapper {
margin: 20px auto 20px auto;
width: 600px;
background: #fff;
padding: 40px;
border: 1px solid #fff;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
box-shadow: 0 0 2px #999;
-webkit-box-shadow: 0 0 3px #999;
}
a img {
border: 0;
width: 600px;
margin: auto;
}
body, th, td, input {
font: 13px/17px "Lucida Grande", "Lucida Sans Unicode", Arial, Verdana, sans-serif;
font: 14px 'Source Sans Pro', Arial, sans-serifsans-serif;
}
.section {
background: #fff;
position: relative;
padding: 2em 2.4em;
margin: 3em auto 4em auto;
width: 80%;
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.section:before, .section:after {
content: "";
position: absolute;
z-index: -2;
}
.section {
-moz-border-radius: 4px;
border-radius: 4px;
}
.section:before, .section:after {
bottom: 15px;
left: 10px;
width: 50%;
height: 20%;
max-width: 300px;
max-height: 100px;
-webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-webkit-transform: rotate(-1deg);
-moz-transform: rotate(-1deg);
-ms-transform: rotate(-1deg);
-o-transform: rotate(-1deg);
transform: rotate(-1deg);
}
.section:after {
right: 10px;
left: auto;
-webkit-transform: rotate(1deg);
-moz-transform: rotate(1deg);
-ms-transform: rotate(1deg);
-o-transform: rotate(1deg);
transform: rotate(1deg);
}
a:link, a:visited {
color: #00688f;
text-decoration: underline;
color: #0004b2;
text-decoration: none;
}
a:hover, a:active {
color: #000;
border: 0;
a:hover {
color: #ac0000;
text-decoration: none;
border-bottom: 1px solid #999;
}
h1 {
font: 170% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #b90000;
margin: 15px 0 5px 0;
font: 2.7em 'Ropa Sans', 'Trebuchet MS', Helvetica, Arial, sans-serif;
color: #000;
margin: 0 0;
padding: 0 0 0.2em 0;
font-weight: normal;
text-align: center;
text-shadow: 2px 2px #FFF;
}
h2 {
font: 130% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #6a45ac;
margin: 50px 0 5px 0;
padding: 0 0 3px 0;
border-bottom: 1px solid #ccc;
font-size: 1.3em;
color: #FFF;
margin: -2.5em 0 0.8em 0;
float: left;
background: #0049FF;
padding: 0.4em 0.8em;
border-radius: 0.2em;
font-weight: normal;
text-align: center;
}
.warning {
background: #fffedf;
padding: 8px;
border: 1px dashed #ccc;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 90%;
h3 {
text-transform: uppercase;
font-weight: bold;
}
.subtle {
color: #999;
h2 + * {
clear: both;
}
.optional {
background: none repeat scroll 0 0 #FFE081;
border-radius: 3px 3px 3px 3px;
font-size: 80%;
font-weight: normal;
padding: 1px 4px;
@media (max-width: 650px) {
#wrapper {
width: 100%;
}
}
</style>
</head>
<body>
<div id="wrapper">
<h1>WorldGuard ${version}</h1>
<p>Thanks for choosing WorldGuard!</p>
<h2>Getting Started</h2>
<p>Now, to begin, you want to:</p>
<ol>
<li><strong>Install the plugin:</strong> Copy WorldGuard.jar into your Bukkit server's &quot;plugins&quot; directory.</li>
<li><strong>Change the configuration:</strong> Run your server once (with WorldGuard) to generate the default configuration files. There are <em>two</em> types of configuration files:
<ul>
<li>The main config.yml file inside &quot;plugins/WorldGuard&quot; is the main configuration. </li>
<li>Each world has a configuration file in &quot;plugins/WorldGuard/worlds&quot; that you can use to override any setting in the main configuration file for that specific world.</li>
</ul>
</li>
Use <em>/wg reload</em> in the console to reload the configuration.
<li><strong>Learn how to use WorldGuard:</strong> Check <a href="http://wiki.sk89q.com/wiki/WorldGuard">out the wiki</a> to learn how to disable things like fire and to protect regions.</li>
</ol>
<p class="warning"><strong>Note:</strong> <a href="http://www.sk89q.com/projects/worldedit/">WorldEdit</a> must be installed, but if you do not want it, put WorldEdit.jar into your Bukkit root folder (outside of plugins/). Note that region protection requires WorldEdit in plugins/.</p>
<p>Be sure to:</p>
<ul>
<li>Subscribe to <a href="http://minecraftnews.sk89q.com/">SK's Minecraft blog</a> for news about WorldGuard</li>
<li>Idle with us in IRC at <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a></li>
</ul>
<h2>Getting Help</h2>
<p>If you need help, the best two ways to ask are:</p>
<ul>
<li><a href="http://forum.sk89q.com/">Visit the WorldGuard forum</a></li>
<li>Ask in IRC chat on <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a> (idle with us!)</li>
<li>Submit bug reports and suggestions to the <a href="http://redmine.sk89q.com/projects/worldguard/issues">issue tracker</a></li>
</ul>
<h2>Contributing</h2>
<p>WorldGuard is entirely open source! You can download all of the plugin code to learn from it, modify it for your own self, or even contribute back!</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">Download WorldGuard code from GitHub</a></li>
<li>You can also <a href="http://www.sk89q.com/donate/">donate</a></li>
</ul>
<p>The code is covered under the GNU General Public License v3.</p>
<p class="subtle">Maven information: ${groupId}/${artifactId}/${version}</p>
<h1>${project.name} ${version}</h1>
<div class="section">
<h2>Getting Started</h2>
<p>
Thanks for choosing ${project.name}! When you first install ${project.name},
nothing will be enabled, so you will need to switch on the features
that you need to use, whenever it is convenient for you.
</p>
<ul>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Installation">How do I install ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Upgrading">How do I update ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}#Usage">How do I use ${project.name}?</a></li>
</ul>
<p>
Need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Common Issues</h2>
<h3>What are the other files that come with the download?</h3>
<p>
Inside the folder "contrib" of the download are the following files:
</p>
<ul>
<li>blacklist_table.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Blacklist">blacklist feature</a>.</li>
<li>region_storage.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Regions">region protection feature</a>.</li>
<li>region_storage_update_20110325.sql is for updating your region protection
database (if you're using it) if your database was made before March 25, 2011.</li>
</ul>
<h3>${project.name} doesn't seem to work.</h3>
<p>
Two common mistakes include forgetting to install WorldEdit
(${project.name} needs it), or making
a syntax error in one of ${project.name}'s configuration files (this is very
fatal unfortunately, and can be caused by a single character typed in the wrong place). Try
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">asking in IRC</a>
to see whether anyone can help you.
</p>
<h3>How do I protect my spawn, or another area?</h3>
<p>
Read the <a href="http://wiki.sk89q.com/wiki/${project.name}/Regions/Tutorial">area protection tutorial</a>
on our wiki. For more detailed information, be sure to read about
<a href="http://wiki.sk89q.com/wiki/WorldGuard/Regions">region protection on the wiki</a>. Note
that if you can't build in spawn, don't forget that Minecraft comes with its own
limited spawn protection that you have to disable (see below).
</p>
<h3>I or others don't have permission to build.</h3>
<p>
Unless you copied configuration files from an older installation of
${project.name}, your problem is either caused by another plugin, or by not
disabling the built-in spawn protection of the Minecraft server.
</p>
<h3>No one can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'deny' means that
no one can modify the things inside the region.</li>
<li>That you added the player as an owner or member of the region. If you are using
a group (g:groupName), you may have to give the group the permission of
group.groupName for ${project.name} to recognize it.</li>
<li>That you disabled spawn protection. The Minecraft server has an automatic
spawn protection feature where only 'ops' can build in a definable
radius around spawn (by default, it is 16 blocks). If you are on Minecraft
1.4 or newer, edit "spawn-protection" in server.properties; otherwise, modify bukkit.yml
and change the spawn-radius setting.</li>
<li>That it's not another plugin causing you trouble. The error messages of ${project.name} are of
a dark red shade. If the color of the "no permission" message is not
that color, it is not ${project.name}.</li>
</ul>
<h3>Everyone can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'allow' means that
anyone can modify the things inside the region.</li>
<li>That it's not caused by another plugin. If players are getting a dark red
permission denied message, but they can still build, another plugin
is likely causing the conflict.</li>
</ul>
<h3>Where do I report bugs or suggest ideas?</h3>
<p>
Make sure you are using the latest version of ${project.name}, try asking in
IRC first (see "Need help?" above) if it's a problem, and if you think you've
found a bug or have a great suggestion to provide, please
report it to <a href="http://youtrack.sk89q.com/issues/WORLDGUARD">our issue tracker</a>.
</p>
<p>
Still need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Contributing</h2>
<p>
Did you know that ${project.name} is open source? That means that you can
read the code and learn from it, as well as modify it and submit back
changes to help the community!
</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">View the source code</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Development">More information</a></li>
</ul>
</div>
</div>
</body>
</html>
+26 -13
View File
@@ -1,25 +1,38 @@
WorldGuard
![WorldGuard](http://static.sk89q.com/readme/worldguard.png)
==========
WorldGuard protects your Minecraft server. As Minecraft's oldest surviving world protection mod, you know you're in safe hands.
WorldGuard is a toolbox of various functions, useful for multiplayer servers, that lets you:
* Protect your server from a number of problems.
* Block fire spread, lava spread, endermen, and more.
* Flag areas as "no PVP" or "no TNT."
* Assign ownership to areas so only selected individuals can build.
* Use a number of useful commands.
WorldGuard is open source and is available under the GNU General Public License v3.
Compiling
---------
You need to have Maven installed (http://maven.apache.org). Once installed,
simply run:
The project is written for Java 6 and our build process makes use of [Maven](http://maven.apache.org). Detailed compilation information [can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
mvn clean install
Maven will automatically download dependencies for you. Note: For that to work,
be sure to add Maven to your "PATH".
Dependencies are automatically handled by Maven.
Contributing
------------
We happily accept contributions. The best way to do this is to fork WorldGuard
on GitHub, add your changes, and then submit a pull request. We'll look at it,
make comments, and merge it into WorldGuard if everything works out.
We happily accept contributions, especially through pull requests on GitHub. Submissions
must be licensed under the GNU General Public License v3.
By submitting code, you agree to place to license your code under the
GNU General Public License v3.
Please read CONTRIBUTING.md for important guidelines to follow.
We recommend following our [mailing list](https://groups.google.com/d/forum/sk-dev-discuss), especially if you have some big ideas that you want to implement.
Links
-----
* [Mailing list](https://groups.google.com/d/forum/sk-dev-discuss)
* [IRC channel](http://skq.me/irc/irc.esper.net/sk89q/) (#sk89q on irc.esper.net)
* [Issue tracker](http://youtrack.sk89q.com/issues/WORLDGUARD)
* [Continuous integration](http://build.sk89q.com) [![Build Status](https://secure.travis-ci.org/sk89q/worldguard.png)](http://travis-ci.org/sk89q/worldguard)
* [End-user documentation](http://wiki.sk89q.com/wiki/WorldGuard)
@@ -1,24 +1,24 @@
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`world` varchar(32) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`world` varchar(32) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
ALTER TABLE `blacklist_events` ADD `world` VARCHAR( 32 ) NOT NULL
+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;
+165 -51
View File
@@ -1,90 +1,152 @@
<!--
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</version>
<version>5.7.5</version>
<packaging>jar</packaging>
<!-- Project information -->
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
<license>
<name>GNU General Public License 2.0</name>
<url>LICENSE.txt</url>
<distribution>repo</distribution>
<comments>License on all contributions</comments>
</license>
</licenses>
<issueManagement>
<system>YouTrack</system>
<url>http://youtrack.sk89q.com</url>
</issueManagement>
<ciManagement>
<system>Jenkins</system>
<url>http://build.sk89q.com</url>
</ciManagement>
<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>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
</scm>
<mailingLists>
<mailingList>
<name>Developer Discussion</name>
<archive>https://groups.google.com/d/forum/sk-dev-discuss</archive>
</mailingList>
</mailingLists>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
</distributionManagement>
<properties> <!-- Fix encoding warnings -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<!-- Repository for zml's stuff -->
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<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.2</version>
<version>5.5.3</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.1-R3</version>
<version>1.5-R0.1-SNAPSHOT</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
<version>2.1</version>
<scope>compile</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
<version>1.5.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
<type>jar</type>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions> <!-- Used for uploading the docs -->
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
@@ -107,14 +169,16 @@
</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>
@@ -132,9 +196,7 @@
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
@@ -147,20 +209,19 @@
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
@@ -174,8 +235,7 @@
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
@@ -186,20 +246,74 @@
<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>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</reporting>
</build>
<profiles>
<!-- Attach javadocs and source .jars -->
<profile>
<id>attach-docs</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
-184
View File
@@ -1,184 +0,0 @@
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 `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `group`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `group` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `world`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `world` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region` (
`id` VARCHAR(128) NOT NULL ,
`world_id` INT UNSIGNED NOT NULL ,
`type` ENUM('cuboid','poly2d','global') NOT NULL ,
`priority` SMALLINT NOT NULL DEFAULT 0 ,
`parent` VARCHAR(128) NULL ,
PRIMARY KEY (`id`, `world_id`) ,
INDEX `parent` (`parent` ASC) ,
INDEX `fk_region_world` (`world_id` ASC) ,
CONSTRAINT `parent`
FOREIGN KEY (`parent` )
REFERENCES `region` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_region_world1`
FOREIGN KEY (`world_id` )
REFERENCES `world` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_flag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_flag` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`flag` VARCHAR(64) NOT NULL ,
`value` VARCHAR(256) NOT NULL ,
INDEX `fk_flags_region` (`region_id` ASC) ,
PRIMARY KEY (`id`) ,
CONSTRAINT `fk_flags_region1`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_cuboid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_cuboid` (
`region_id` VARCHAR(128) NOT NULL ,
`min_z` BIGINT NOT NULL ,
`min_y` BIGINT NOT NULL ,
`min_x` BIGINT NOT NULL ,
`max_z` BIGINT NOT NULL ,
`max_y` BIGINT NOT NULL ,
`max_x` BIGINT NOT NULL ,
PRIMARY KEY (`region_id`) ,
INDEX `fk_region_cuboid_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_poly2d`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d` (
`region_id` VARCHAR(128) NOT NULL ,
`max_y` INT NOT NULL ,
`min_y` INT NOT NULL ,
PRIMARY KEY (`region_id`) ,
INDEX `fk_region_poly2d_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_players`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_players` (
`region_id` VARCHAR(128) NOT NULL ,
`user_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `user_id`) ,
INDEX `fk_region_players_region` (`region_id` ASC) ,
INDEX `fk_region_players_user` (`user_id` ASC) ,
CONSTRAINT `fk_region_players_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_players_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_groups` (
`region_id` VARCHAR(128) NOT NULL ,
`group_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `group_id`) ,
INDEX `fk_region_groups_region` (`region_id` ASC) ,
INDEX `fk_region_groups_group` (`group_id` ASC) ,
CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_poly2d_point`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d_point` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`z` BIGINT NOT NULL ,
`x` BIGINT NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` )
REFERENCES `region_poly2d` (`region_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+3 -2
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>
@@ -29,7 +28,9 @@
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>blacklist_table.sql</include>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_storage.sql</include>
<include>contrib/region_storage_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
@@ -25,68 +25,66 @@ 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);
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LocalPlayer)) {
return false;
}
return ((LocalPlayer)obj).getName().equals(getName());
return obj instanceof LocalPlayer && ((LocalPlayer) obj).getName().equals(getName());
}
@Override
@@ -73,7 +73,7 @@ public abstract class Blacklist {
/**
* Returns whether the list is empty.
*
* @return
* @return whether the blacklist is empty
*/
public boolean isEmpty() {
return blacklist.isEmpty();
@@ -82,8 +82,8 @@ 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);
@@ -92,7 +92,7 @@ public abstract class Blacklist {
/**
* 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();
@@ -101,7 +101,7 @@ public abstract class Blacklist {
/**
* 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;
@@ -110,7 +110,7 @@ public abstract class Blacklist {
/**
* Get the logger.
*
* @return
* @return The logger used in this blacklist
*/
public BlacklistLogger getLogger() {
return blacklistLogger;
@@ -119,10 +119,10 @@ 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());
@@ -141,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;
@@ -170,7 +170,7 @@ public abstract class Blacklist {
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
int id;
try {
id = Integer.parseInt(item.trim());
@@ -248,7 +248,7 @@ public abstract class Blacklist {
if (input != null) {
input.close();
}
} catch (IOException e2) {
} catch (IOException ignore) {
}
}
}
@@ -256,7 +256,7 @@ public abstract class Blacklist {
/**
* Get the last event.
*
* @return
* @return The last event
*/
public BlacklistEvent getLastEvent() {
return lastEvent;
@@ -265,8 +265,8 @@ public abstract class Blacklist {
/**
* 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;
@@ -282,14 +282,14 @@ public abstract class Blacklist {
/**
* 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());
@@ -305,7 +305,8 @@ 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);
@@ -319,7 +320,8 @@ 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,6 +19,7 @@
package com.sk89q.worldguard.blacklist;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -69,7 +70,7 @@ public class BlacklistEntry {
/**
* Construct the object.
*
* @param blacklist
* @param blacklist The blacklist that contains this entry
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
@@ -105,105 +106,103 @@ public class BlacklistEntry {
*/
public void setIgnorePermissions(String[] ignorePermissions) {
Set<String> ignorePermissionsSet = new HashSet<String>();
for (String perm : ignorePermissions) {
ignorePermissionsSet.add(perm);
}
Collections.addAll(ignorePermissionsSet, ignorePermissions);
this.ignorePermissions = ignorePermissionsSet;
}
/**
* @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;
@@ -240,8 +239,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) {
@@ -266,8 +265,8 @@ public class BlacklistEntry {
/**
* 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) {
@@ -299,11 +298,11 @@ 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();
@@ -329,11 +328,11 @@ 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) {
@@ -412,7 +411,7 @@ 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);
@@ -39,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);
@@ -64,7 +64,7 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
@@ -32,8 +32,8 @@ 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";
@@ -48,11 +48,6 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
this.logger = logger;
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
@@ -113,14 +108,15 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* 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;
}
}
@@ -73,11 +73,12 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* 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, Logger logger) {
this.dsn = dsn;
@@ -91,8 +92,8 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* 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()) {
@@ -104,11 +105,11 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event to the database.
*
* @param event
* @param player
* @param pos
* @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) {
@@ -137,7 +138,7 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
@@ -197,7 +198,7 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
} catch (SQLException ignore) {
}
}
@@ -39,13 +39,6 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
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.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;
/**
*
@@ -85,8 +78,9 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* 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, Logger logger) {
this.pathPattern = pathPattern;
@@ -97,9 +91,10 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* 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, Logger logger) {
if (cacheSize < 1) {
@@ -114,7 +109,8 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* 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();
@@ -171,8 +167,9 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* 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());
@@ -220,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();
@@ -240,8 +237,8 @@ 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();
@@ -255,55 +252,17 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* 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);
@@ -321,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) {
}
}
@@ -42,8 +42,8 @@ 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;
@@ -54,14 +54,14 @@ 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;
@@ -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;
@@ -57,6 +57,7 @@ public class BukkitPlayer extends LocalPlayer {
@Override
public void ban(String msg) {
player.setBanned(true);
player.kickPlayer(msg);
}
@@ -19,59 +19,51 @@
package com.sk89q.worldguard.bukkit;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
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.*;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import java.util.List;
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());
@@ -79,22 +71,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) {
@@ -102,12 +96,14 @@ 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(),
@@ -117,7 +113,7 @@ public class BukkitUtil {
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
*
* @param world
* @param ox
* @param oy
@@ -133,21 +129,38 @@ public class BukkitUtil {
/**
* Checks if the given block is water
*
* @param world
* @param ox
* @param oy
* @param oz
* @return
*
* @param world the world
* @param ox x
* @param oy y
* @param oz z
* @return true if it's water
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
return true;
} else {
return false;
}
return id == 8 || id == 9;
}
/**
* Checks if the given potion is a vial of water.
*
* @param item the item to check
* @return true if it's a water vial
*/
public static boolean isWaterPotion(ItemStack item) {
return (item.getDurability() & 0x3F) == 0;
}
/**
* Get just the potion effect bits. This is to work around bugs with potion
* parsing.
*
* @param item item
* @return new bits
*/
public static int getPotionEffectBits(ItemStack item) {
return item.getDurability() & 0x3F;
}
/**
@@ -168,7 +181,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 {
@@ -236,14 +249,48 @@ public class BukkitUtil {
* Returns whether an entity should be removed for the halt activity mode.
*
* @param entity
* @return
* @return true if it's to be removed
*/
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));
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
/**
* Returns whether our running CraftBukkit already supports
* the HangingEvent instead of the PaintingEvent
*
* @return true if the hanging event is supported
*/
public static boolean hasHangingEvent() {
Class<?> tmp = null;
try {
tmp = Class.forName("org.bukkit.event.hanging.HangingEvent");
} catch (ClassNotFoundException ignored) { }
return (tmp != null);
}
/**
* Search an enum for a value, and return the first one found. Return null if the
* enum entry is not found.
*
* @param enumType enum class
* @param values values to test
* @return a value in the enum or null
*/
public static <T extends Enum<T>> T tryEnum(Class<T> enumType, String ... values) {
for (String val : values) {
try {
return Enum.valueOf(enumType, val);
} catch (IllegalArgumentException e) {
}
}
return null;
}
}
@@ -18,22 +18,23 @@
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import org.bukkit.World;
import org.bukkit.entity.Player;
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 com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Represents the global configuration and also delegates configuration
@@ -73,7 +74,7 @@ public class ConfigurationManager {
/**
* Holds configurations for different worlds.
*/
private Map<String, WorldConfiguration> worlds;
private ConcurrentMap<String, WorldConfiguration> worlds;
/**
* The global configuration for use when loading worlds
@@ -90,15 +91,18 @@ public class ConfigurationManager {
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
public boolean suppressTickSyncWarnings;
public boolean useRegionsScheduler;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
public boolean deopOnJoin;
public boolean blockInGameOp;
public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
@@ -110,16 +114,17 @@ public class ConfigurationManager {
/**
* Construct the object.
*
* @param plugin
* @param plugin The plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.worlds = new HashMap<String, WorldConfiguration>();
this.worlds = new ConcurrentHashMap<String, WorldConfiguration>();
}
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
plugin.createDefaultConfiguration(
@@ -133,14 +138,27 @@ public class ConfigurationManager {
e.printStackTrace();
}
suppressTickSyncWarnings = config.getBoolean(
"suppress-tick-sync-warnings", false);
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
autoGodMode = config.getBoolean(
"auto-invincible", config.getBoolean("auto-invincible-permission", true));
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
config.removeProperty("suppress-tick-sync-warnings");
useRegionsScheduler = config.getBoolean("regions.use-scheduler", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
autoGodMode = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean("use-player-move-event", true);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
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);
@@ -154,10 +172,7 @@ public class ConfigurationManager {
get(world);
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
@@ -174,16 +189,20 @@ 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);
WorldConfiguration newConfig = null;
if (config == null) {
config = new WorldConfiguration(plugin, worldName, this.config);
worlds.put(worldName, config);
while (config == null) {
if (newConfig == null) {
newConfig = new WorldConfiguration(plugin, worldName, this.config);
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
@@ -192,7 +211,7 @@ 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
@@ -212,17 +231,18 @@ public class ConfigurationManager {
/**
* 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) {
@@ -232,8 +252,8 @@ public class ConfigurationManager {
/**
* 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) {
@@ -248,7 +268,7 @@ public class ConfigurationManager {
/**
* 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());
@@ -257,22 +277,22 @@ public class ConfigurationManager {
/**
* 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.
* Check to see if amphibious mode is enabled for a player.
*
* @param player
* @return
* @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")) {
@@ -283,7 +303,7 @@ public class ConfigurationManager {
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
@@ -19,41 +19,40 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.HashMap;
import java.util.Map;
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 org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
/**
* 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>();
}
@@ -66,16 +65,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,11 +82,9 @@ public class FlagStateManager implements Runnable {
}
Vector playerLocation = toVector(player.getLocation());
RegionManager regionManager = plugin.getGlobalRegionManager()
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
RegionManager regionManager = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet applicable = regionManager.getApplicableRegions(playerLocation);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
&& !(player.getGameMode() == GameMode.CREATIVE)) {
@@ -96,38 +93,42 @@ public class FlagStateManager implements Runnable {
}
}
}
/**
* 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 (maxHealth == null) maxHealth = player.getMaxHealth();
// Apply a cap to prevent possible exceptions
minHealth = Math.min(player.getMaxHealth(), minHealth);
maxHealth = Math.min(player.getMaxHealth(), maxHealth);
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
@@ -137,13 +138,13 @@ public class FlagStateManager implements Runnable {
state.lastHeal = now;
}
}
/**
* Process restoring hunger for a player.
*
* @param applicable
* @param player
* @param state
*
* @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) {
@@ -154,13 +155,17 @@ public class FlagStateManager implements Runnable {
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;
// Apply a cap to prevent possible exceptions
minHunger = Math.min(20, minHunger);
maxHunger = Math.min(20, maxHunger);
if (player.getFoodLevel() >= maxHunger && feedAmount > 0) {
return;
}
@@ -177,8 +182,8 @@ public class FlagStateManager implements Runnable {
/**
* Forget a player.
*
* @param player
*
* @param player The player to forget
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
@@ -192,22 +197,23 @@ public class FlagStateManager implements Runnable {
}
/**
* Get a player's flag state.
*
* @param player
* @return
* 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.
*/
@@ -219,6 +225,7 @@ public class FlagStateManager implements Runnable {
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public GameMode lastGameMode;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
@@ -26,8 +26,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
@@ -44,7 +42,7 @@ public class LegacyWorldGuardMigration {
/**
* Port over the blacklist.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateBlacklist(WorldGuardPlugin plugin) {
World mainWorld = plugin.getServer().getWorlds().get(0);
@@ -77,7 +75,7 @@ public class LegacyWorldGuardMigration {
/**
* Migrate region settings.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateRegions(WorldGuardPlugin plugin) {
try {
@@ -111,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) {
@@ -133,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) {
}
}
}
@@ -19,8 +19,6 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
@@ -61,7 +59,7 @@ public class RegionQueryUtil {
set = mgr.getApplicableRegions(vec);
}
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY);
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
}
return state.wasInvincible;
@@ -73,7 +71,7 @@ public class RegionQueryUtil {
Vector vec = new Vector(state.lastInvincibleX, state.lastInvincibleY, state.lastInvincibleZ);
StateFlag.State regionState = plugin.getGlobalRegionManager().get(world).
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY);
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
if (regionState == StateFlag.State.ALLOW) {
return Boolean.TRUE;
} else if (regionState == StateFlag.State.DENY) {
@@ -127,7 +127,7 @@ public class ReportWriter {
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -166,7 +166,7 @@ public class ReportWriter {
}
private void appendPluginInformation(Plugin[] plugins) {
appendHeader("Plugins");
appendHeader("Plugins (" + plugins.length + ")");
LogListBlock log = new LogListBlock();
@@ -274,7 +274,7 @@ public class ReportWriter {
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -324,7 +324,7 @@ public class ReportWriter {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
@@ -28,12 +28,12 @@ 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();
@@ -53,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();
@@ -0,0 +1,73 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Helper class to get a reference to WorldGuard and its components.
*/
public class WGBukkit {
private static WorldGuardPlugin cachedPlugin = null;
private WGBukkit() {
}
/**
* Get the WorldGuard plugin. If WorldGuard isn't loaded yet, then this will
* return null.
* <p>
* If you are depending on WorldGuard in your plugin, you should place
* <code>softdepend: [WorldGuard]</code> or <code>depend: [WorldGuard]</code>
* in your plugin.yml so that this won't return null for you.
*
* @return the WorldGuard plugin or null
*/
public static WorldGuardPlugin getPlugin() {
if (cachedPlugin == null) {
cachedPlugin = (WorldGuardPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
}
return cachedPlugin;
}
/**
* Set cache to null for reload WorldGuardPlugin
*/
public static void cleanCache() {
cachedPlugin = null;
}
/**
* Returns the region manager for a given world. May return null if WorldGuard
* is not loaded or region protection is not enabled for the given world.
*
* @param world world
* @return a region manager or null
*/
public static RegionManager getRegionManager(World world) {
if (getPlugin() == null) {
return null;
}
return cachedPlugin.getRegionManager(world);
}
}
@@ -29,14 +29,14 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.block.Block;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
import com.sk89q.worldguard.blacklist.loggers.ConsoleLoggerHandler;
@@ -69,23 +69,26 @@ public class WorldConfiguration {
private String worldName;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File configFile;
private File blacklistFile;
private Blacklist blacklist;
private ChestProtection chestProtection = new SignChestProtection();
/* Configuration data start */
public boolean summaryOnStart;
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean itemDurability;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
public Set<PotionEffectType> blockPotions;
public boolean blockPotionsAlways;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean ropeLadders;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockLighter;
@@ -97,9 +100,20 @@ public class WorldConfiguration {
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public boolean blockWitherExplosions;
public boolean blockWitherBlockDamage;
public boolean blockWitherSkullExplosions;
public boolean blockWitherSkullBlockDamage;
public boolean blockEnderDragonBlockDamage;
public boolean blockEnderDragonPortalCreation;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockOtherExplosions;
public boolean blockEntityPaintingDestroy;
public boolean blockEntityItemFrameDestroy;
public boolean blockPluginSpawning;
public boolean blockGroundSlimes;
public boolean blockZombieDoorDestruction;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
@@ -114,8 +128,8 @@ public class WorldConfiguration {
public boolean disableMobDamage;
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand = 287;
public Set<CreatureType> blockCreatureSpawn;
public int regionWand;
public Set<EntityType> blockCreatureSpawn;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
@@ -124,6 +138,7 @@ public class WorldConfiguration {
public int maxRegionCountPerPlayer;
public boolean antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
@@ -143,11 +158,13 @@ public class WorldConfiguration {
public boolean disableIceFormation;
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableMyceliumSpread;
public boolean disableVineGrowth;
public boolean disableEndermanGriefing;
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
/* Configuration data end */
@@ -161,7 +178,7 @@ public class WorldConfiguration {
*/
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;
@@ -171,10 +188,12 @@ public class WorldConfiguration {
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
config = new YAMLProcessor(this.configFile, true, YAMLFormat.EXTENDED);
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
plugin.getLogger().info("Loaded configuration for world '" + worldName + '"');
if (summaryOnStart) {
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
}
}
private boolean getBoolean(String node, boolean def) {
@@ -280,6 +299,7 @@ public class WorldConfiguration {
e.printStackTrace();
}
summaryOnStart = getBoolean("summary-on-start", true);
opPermissions = getBoolean("op-permissions", true);
itemDurability = getBoolean("protection.item-durability", true);
@@ -287,6 +307,18 @@ public class WorldConfiguration {
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
blockPotions = new HashSet<PotionEffectType>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
PotionEffectType effect = PotionEffectType.getByName(potionName);
if (effect == null) {
plugin.getLogger().warning("Unknown potion effect type '" + potionName + "'");
} else {
blockPotions.add(effect);
}
}
blockPotionsAlways = getBoolean("gameplay.block-potions-overly-reliably", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
@@ -296,6 +328,7 @@ public class WorldConfiguration {
noPhysicsGravel = getBoolean("physics.no-physics-gravel", false);
noPhysicsSand = getBoolean("physics.no-physics-sand", false);
ropeLadders = getBoolean("physics.vine-like-rope-ladders", false);
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
@@ -310,11 +343,22 @@ public class WorldConfiguration {
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
blockWitherExplosions = getBoolean("mobs.block-wither-explosions", false);
blockWitherBlockDamage = getBoolean("mobs.block-wither-block-damage", false);
blockWitherSkullExplosions = getBoolean("mobs.block-wither-skull-explosions", false);
blockWitherSkullBlockDamage = getBoolean("mobs.block-wither-skull-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockEntityItemFrameDestroy = getBoolean("mobs.block-item-frame-destroy", false);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
blockGroundSlimes = getBoolean("mobs.block-above-ground-slimes", false);
blockOtherExplosions = getBoolean("mobs.block-other-explosions", false);
blockZombieDoorDestruction = getBoolean("mobs.block-zombie-door-destruction", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -331,6 +375,7 @@ public class WorldConfiguration {
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);
@@ -351,18 +396,20 @@ public class WorldConfiguration {
disableIceFormation = getBoolean("dynamics.disable-ice-formation", false);
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-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);
regionWand = getInt("regions.wand", 334);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
@@ -376,12 +423,14 @@ public class WorldConfiguration {
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<CreatureType>();
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) {
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);
}
@@ -421,7 +470,9 @@ public class WorldConfiguration {
this.blacklist = null;
} else {
this.blacklist = blist;
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
if (summaryOnStart) {
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
}
BlacklistLogger blacklistLogger = blist.getLogger();
@@ -447,7 +498,7 @@ public class WorldConfiguration {
}
// Print an overview of settings
if (getBoolean("summary-on-start", true)) {
if (summaryOnStart) {
plugin.getLogger().log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
@@ -472,10 +523,7 @@ public class WorldConfiguration {
}
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
config.save();
}
@@ -500,10 +548,8 @@ public class WorldConfiguration {
}
public boolean isChestProtected(Block block) {
if (!signChestProtection) {
return false;
}
return chestProtection.isProtected(block, null);
return signChestProtection && chestProtection.isProtected(block, null);
}
public boolean isChestProtectedPlacement(Block block, Player player) {
@@ -531,7 +577,7 @@ public class WorldConfiguration {
public ChestProtection getChestProtection() {
return chestProtection;
}
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
@@ -18,12 +18,11 @@
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.dropSign;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
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.Player;
@@ -33,10 +32,13 @@ 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.BlockDispenseEvent;
import org.bukkit.event.block.BlockExpEvent;
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.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
@@ -45,12 +47,14 @@ 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 org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
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.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
@@ -61,7 +65,7 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* The listener for block events.
*
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
@@ -70,8 +74,8 @@ public class WorldGuardBlockListener implements Listener {
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -86,9 +90,9 @@ public class WorldGuardBlockListener implements Listener {
/**
* 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);
@@ -96,23 +100,19 @@ public class WorldGuardBlockListener implements Listener {
/**
* 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.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
@@ -126,16 +126,12 @@ public class WorldGuardBlockListener implements Listener {
}
}
}
/**
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
@@ -144,12 +140,13 @@ public class WorldGuardBlockListener implements Listener {
if (held.getTypeId() > 0
&& !(ItemType.usesDamageValue(held.getTypeId())
|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) -1);
held.setDurability((short) 0);
player.setItemInHand(held);
}
}
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;
@@ -172,7 +169,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
@@ -180,15 +177,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when fluids flow.
*/
@EventHandler
@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();
@@ -239,7 +232,7 @@ public class WorldGuardBlockListener implements Listener {
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
@@ -249,7 +242,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
@@ -277,15 +270,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block gets ignited.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
}
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
@@ -297,7 +286,6 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
@@ -315,7 +303,7 @@ public class WorldGuardBlockListener implements Listener {
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);
@@ -351,12 +339,8 @@ public class WorldGuardBlockListener implements Listener {
if (player != null && !plugin.getGlobalRegionManager().hasBypass(player, world)) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (cause == IgniteCause.FLINT_AND_STEEL) {
if (!set.canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (!set.allows(DefaultFlag.LIGHTER)
if (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL) {
if (!set.allows(DefaultFlag.LIGHTER, localPlayer)
&& !plugin.hasPermission(player, "worldguard.override.lighter")) {
event.setCancelled(true);
return;
@@ -375,20 +359,27 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.FIREBALL && event.getPlayer() == null) {
// wtf bukkit, FIREBALL is supposed to be reserved to players
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block is destroyed from burning.
*/
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -403,7 +394,9 @@ public class WorldGuardBlockListener implements Listener {
}
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
@@ -412,6 +405,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
@@ -420,14 +414,18 @@ public class WorldGuardBlockListener implements Listener {
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;
}
@@ -435,16 +433,26 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
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.
*/
@EventHandler
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -469,18 +477,20 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
if (wcfg.ropeLadders && event.getBlock().getType() == Material.LADDER) {
if (event.getBlock().getRelative(0, 1, 0).getType() == Material.LADDER) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a player places a block.
*/
@EventHandler(priority = EventPriority.HIGH)
@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();
@@ -489,7 +499,9 @@ public class WorldGuardBlockListener implements Listener {
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;
@@ -504,7 +516,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
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.");
@@ -526,12 +538,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
@@ -562,29 +573,28 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a sign is changed.
*/
@EventHandler(priority = EventPriority.HIGH)
@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().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;
}
@@ -593,11 +603,11 @@ public class WorldGuardBlockListener implements Listener {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (below == BlockID.TNT || below == BlockID.SAND
@@ -605,21 +615,21 @@ public class WorldGuardBlockListener implements Listener {
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;
}
@@ -632,12 +642,8 @@ public class WorldGuardBlockListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -659,15 +665,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -703,15 +705,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
@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,16 +743,41 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
if (fromType == BlockID.MYCELIUM) {
if (wcfg.disableMyceliumSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.MYCELIUM_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.VINE) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.VINE_GROWTH, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -786,15 +809,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -812,15 +831,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -828,7 +843,44 @@ public class WorldGuardBlockListener implements Listener {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block is damaged.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.blockPotions.size() > 0) {
ItemStack item = event.getItem();
if (item.getType() == Material.POTION && !BukkitUtil.isWaterPotion(item)) {
Potion potion = Potion.fromDamage(BukkitUtil.getPotionEffectBits(item));
for (PotionEffect effect : potion.getEffects()) {
if (potion.isSplash() && wcfg.blockPotions.contains(effect.getType())) {
event.setCancelled(true);
return;
}
}
}
}
}
/*
* Called when a block yields exp
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockExp(BlockExpEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.disableExpDrops || !plugin.getGlobalRegionManager().allows(DefaultFlag.EXP_DROPS,
event.getBlock().getLocation())) {
event.setExpToDrop(0);
}
}
}
@@ -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));
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
// $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 static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
/**
* Listener for painting related events.
*
* @author BangL <henno.rickowski@gmail.com>
*/
public class WorldGuardHangingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardHangingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
Entity removerEntity = entityEvent.getRemover();
if (removerEntity instanceof Projectile) {
Projectile projectile = (Projectile) removerEntity;
removerEntity = projectile.getShooter() != null ? projectile.getShooter() : removerEntity;
}
if (removerEntity instanceof Player) {
Player player = (Player) removerEntity;
if (wcfg.getBlacklist() != null) {
if (hanging instanceof Painting
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (hanging instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, hanging.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (removerEntity instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, hanging.getLocation())) {
event.setCancelled(true);
return;
}
}
if (hanging instanceof Painting
&& (wcfg.blockEntityPaintingDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame
&& (wcfg.blockEntityItemFrameDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
}
}
} else {
// Explosions from mobs are not covered by HangingBreakByEntity
if (hanging instanceof Painting && wcfg.blockEntityPaintingDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame && wcfg.blockEntityItemFrameDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingPlace(HangingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (event.getEntity() instanceof Painting
&& !wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (event.getEntity() instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getRelative(event.getBlockFace()))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getRightClicked();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.useRegions && (entity instanceof ItemFrame || entity instanceof Painting)) {
if (!plugin.getGlobalRegionManager().canBuild(player, entity.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
// if (entity instanceof ItemFrame
// && ((!plugin.getGlobalRegionManager().allows(
// DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, entity.getLocation())))) {
// event.setCancelled(true);
// } else if (entity instanceof Painting
// && ((!plugin.getGlobalRegionManager().allows(
// DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
// event.setCancelled(true);
// }
}
}
}
@@ -0,0 +1,174 @@
// $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 static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.Warning;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
/**
* Listener for painting related events.
*
* @author sk89q
* @deprecated Use {@link com.sk89q.worldguard.bukkit.WorldGuardHangingListener} instead.
*/
@Deprecated
@Warning(reason="This listener has been replaced by WorldGuardHangingListener")
public class WorldGuardPaintingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardPaintingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
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
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation()))) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getRightClicked();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.useRegions && entity instanceof Painting) {
if (!plugin.getGlobalRegionManager().canBuild(player, entity.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (entity instanceof Painting
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -19,6 +19,8 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.hasHangingEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@@ -28,14 +30,10 @@ 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.logging.Filter;
import java.util.logging.Logger;
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;
@@ -43,26 +41,37 @@ import org.bukkit.World.Environment;
import org.bukkit.block.Block;
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.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.SimpleInjector;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.wepif.PermissionsResolverManager;
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.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 {
/**
* Manager for commands. This automatically handles nested commands,
* permissions checking, and a number of other fancy command things.
@@ -74,12 +83,12 @@ public class WorldGuardPlugin extends JavaPlugin {
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Used for scheduling flags.
*/
@@ -101,10 +110,11 @@ public class WorldGuardPlugin extends JavaPlugin {
}
};
}
/**
* Called on plugin enable.
*/
@Override
@SuppressWarnings("deprecation")
public void onEnable() {
@@ -115,7 +125,7 @@ public class WorldGuardPlugin extends JavaPlugin {
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() {
@@ -132,11 +142,16 @@ public class WorldGuardPlugin extends JavaPlugin {
// 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);
@@ -144,17 +159,8 @@ public class WorldGuardPlugin extends JavaPlugin {
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);
}
getServer().getScheduler().scheduleSyncRepeatingTask(this, flagStateManager,
FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
// Register events
@@ -164,6 +170,16 @@ public class WorldGuardPlugin extends JavaPlugin {
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
if (hasHangingEvent()) {
(new WorldGuardHangingListener(this)).registerEvents();
} else {
(new WorldGuardPaintingListener(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));
@@ -186,12 +202,13 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Called on plugin disable.
*/
@Override
public void onDisable() {
globalRegionManager.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@@ -217,43 +234,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;
@@ -261,10 +278,11 @@ 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 {
@@ -277,9 +295,9 @@ 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 {
@@ -289,42 +307,44 @@ public class WorldGuardPlugin extends JavaPlugin {
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()) {
@@ -337,22 +357,22 @@ public class WorldGuardPlugin extends JavaPlugin {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
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 {
@@ -360,13 +380,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 {
@@ -376,22 +396,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>();
@@ -399,43 +424,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 {
@@ -443,25 +468,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()));
}
@@ -474,7 +506,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);
@@ -482,7 +514,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>();
@@ -490,7 +522,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(
@@ -500,32 +532,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)
@@ -533,48 +566,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 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();
@@ -584,7 +627,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) {
@@ -594,7 +637,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) {
@@ -608,65 +651,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 void createDefaultConfiguration(File actual,
String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
@@ -687,7 +730,7 @@ public class WorldGuardPlugin extends JavaPlugin {
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
@@ -708,60 +751,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);
@@ -784,9 +835,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();
@@ -24,11 +24,15 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
}
@@ -7,8 +7,6 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@@ -46,9 +44,6 @@ public class WorldGuardVehicleListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a vehicle is destroyed.
*/
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
Vehicle vehicle = event.getVehicle();
@@ -69,7 +64,7 @@ public class WorldGuardVehicleListener implements Listener {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.DESTROY_VEHICLE)) {
&& !set.allows(DefaultFlag.DESTROY_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to destroy vehicles here.");
event.setCancelled(true);
return;
@@ -77,9 +72,6 @@ public class WorldGuardVehicleListener implements Listener {
}
}
/**
* Called when a vehicle moves.
*/
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
@@ -127,44 +119,44 @@ public class WorldGuardVehicleListener implements Listener {
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);
if (state.lastFarewell != null && (farewell == null
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: "
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: "
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
@@ -20,8 +20,6 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -44,7 +42,7 @@ public class WorldGuardWeatherListener implements Listener {
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -54,11 +52,8 @@ public class WorldGuardWeatherListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -73,12 +68,8 @@ public class WorldGuardWeatherListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -93,12 +84,8 @@ public class WorldGuardWeatherListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@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());
@@ -5,8 +5,6 @@
*/
package com.sk89q.worldguard.bukkit;
import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
@@ -21,7 +19,7 @@ public class WorldGuardWorldListener implements Listener {
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -34,9 +32,6 @@ public class WorldGuardWorldListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a chunk is loaded.
*/
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -58,14 +53,19 @@ public class WorldGuardWorldListener implements Listener {
}
}
/**
* Called when a world is loaded.
*/
@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);
@@ -275,17 +275,19 @@ public class GeneralCommands {
if (item2.getTypeId() == item.getTypeId() &&
((!ItemType.usesDamageValue(item.getTypeId()) && ignoreDamaged)
|| item.getDurability() == item2.getDurability()) &&
item.getEnchantments().equals(item2.getEnchantments())) {
((item.getItemMeta() == null && item2.getItemMeta() == null)
|| (item.getItemMeta() != null &&
item.getItemMeta().equals(item2.getItemMeta())))) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(64);
item.setAmount(max);
item2.setAmount(item2.getAmount() - needed);
break;
// This stack will
} else {
items[j] = null;
item.setAmount(item.getAmount() + item2.getAmount());
needed = 64 - item.getAmount();
needed = max - item.getAmount();
}
affected++;
File diff suppressed because it is too large. Load diff
@@ -30,11 +30,11 @@ 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.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
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.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.util.RegionUtil;
// @TODO: A lot of code duplication here! Need to fix.
@@ -44,15 +44,30 @@ public class RegionMemberCommands {
public RegionMemberCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"addmember", "addmember"}, usage = "<id> <members...>",
desc = "Add a member to a region", min = 2)
@Command(aliases = {"addmember", "addmember"},
usage = "<id> <members...>",
flags = "w:",
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();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
final World world;
Player player = null;
LocalPlayer localPlayer = null;
if (sender instanceof Player) {
player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
}
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
if (player != null) {
world = player.getWorld();
} else {
throw new CommandException("No world specified. Use -w <worldname>.");
}
}
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -61,20 +76,24 @@ 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.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.member." + id.toLowerCase());
} else {
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 (ProtectionDatabaseException e) {
@@ -82,15 +101,30 @@ public class RegionMemberCommands {
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"}, usage = "<id> <owners...>",
desc = "Add an owner to a region", min = 2)
@Command(aliases = {"addowner", "addowner"},
usage = "<id> <owners...>",
flags = "w:",
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();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
final World world;
Player player = null;
LocalPlayer localPlayer = null;
if (sender instanceof Player) {
player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
}
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
if (player != null) {
world = player.getWorld();
} else {
throw new CommandException("No world specified. Use -w <worldname>.");
}
}
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -100,48 +134,67 @@ public class RegionMemberCommands {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (flag != null && flag == true && 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.");
if (localPlayer != null) {
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 {
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());
}
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
}
RegionDBUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"},
usage = "<id> <owners...>",
flags = "w:",
desc = "Remove an owner to a region",
min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player = null;
LocalPlayer localPlayer = null;
if (sender instanceof Player) {
player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
}
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
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());
if (player != null) {
world = player.getWorld();
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
throw new CommandException("No world specified. Use -w <worldname>.");
}
}
RegionUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} 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", min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -150,20 +203,24 @@ 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.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.member." + id.toLowerCase());
} else {
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 (ProtectionDatabaseException e) {
@@ -171,16 +228,31 @@ public class RegionMemberCommands {
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
@Command(aliases = {"removeowner", "remowner"},
usage = "<id> <owners...>",
flags = "w:",
desc = "Remove an owner to a region",
min = 2)
public void removeOwner(CommandContext args,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
final World world;
Player player = null;
LocalPlayer localPlayer = null;
if (sender instanceof Player) {
player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
}
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
if (player != null) {
world = player.getWorld();
} else {
throw new CommandException("No world specified. Use -w <worldname>.");
}
}
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -189,20 +261,24 @@ 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.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.member." + id.toLowerCase());
} else {
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 (ProtectionDatabaseException e) {
@@ -128,7 +128,7 @@ public class ToggleCommands {
if (removed > 10) {
sender.sendMessage("" + removed + " entities (>10) auto-removed from "
+ world.toString());
+ world.getName());
}
}
@@ -34,6 +34,7 @@ import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.LoggerToChatHandler;
import com.sk89q.worldguard.bukkit.ReportWriter;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
@@ -72,6 +73,7 @@ public class WorldGuardCommands {
plugin.getGlobalRegionManager().unload();
plugin.getGlobalStateManager().load();
plugin.getGlobalRegionManager().preload();
WGBukkit.cleanCache();
sender.sendMessage("WorldGuard configuration reloaded.");
} catch (Throwable t) {
sender.sendMessage("Error while reloading: "
@@ -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,26 +41,27 @@ 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);
@@ -68,8 +69,8 @@ public interface ChestProtection {
/**
* Returns whether a material is a chest.
*
* @param type
* @return
* @param type The type to check
* @return Whether type is a 'chest' (block that can be protected)
*/
public boolean isChest(int type);
@@ -115,10 +115,7 @@ public class SignChestProtection implements ChestProtection {
private boolean isProtectedSignAndChestBinary(Block block, Player player) {
Boolean res = isProtectedSignAndChest(block, player);
if (res == null || !res) {
return false;
}
return true;
return !(res == null || !res);
}
public boolean isAdjacentChestProtected(Block searchBlock, Player player) {
@@ -127,23 +124,23 @@ 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;
}
@@ -70,20 +70,26 @@ 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();
}
@@ -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);
}
@@ -26,31 +26,42 @@ 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;
}
}
@@ -27,15 +27,15 @@ 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);
}
@@ -46,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();
}
}
@@ -26,29 +26,33 @@ 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,22 +18,13 @@
*/
package com.sk89q.worldguard.protection;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
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.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.*;
/**
* Represents a set of regions for a particular point or area and the rules
* that are represented by that set. An instance of this can be used to
@@ -52,8 +43,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) {
@@ -64,19 +55,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);
@@ -93,7 +91,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);
}
/**
@@ -108,7 +106,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);
}
/**
@@ -149,12 +147,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;
@@ -210,16 +206,12 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
Set<ProtectedRegion> needsClear = new HashSet<ProtectedRegion>();
Set<ProtectedRegion> hasCleared = new HashSet<ProtectedRegion>();
Iterator<ProtectedRegion> it = applicable.iterator();
while (it.hasNext()) {
ProtectedRegion region = it.next();
for (ProtectedRegion region : applicable) {
// Ignore lower priority regions
if (hasFlagDefined && region.getPriority() < lastPriority) {
break;
}
lastPriority = region.getPriority();
// Ignore non-build regions
@@ -229,16 +221,16 @@ 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;
}
}
State v = region.getFlag(flag);
// Allow DENY to override everything
@@ -276,16 +268,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) {
@@ -300,15 +292,25 @@ 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()");
@@ -321,23 +323,30 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
Map<ProtectedRegion, V> needsClear = new HashMap<ProtectedRegion, V>();
Set<ProtectedRegion> hasCleared = new HashSet<ProtectedRegion>();
Iterator<ProtectedRegion> it = applicable.iterator();
while (it.hasNext()) {
ProtectedRegion region = it.next();
for (ProtectedRegion region : applicable) {
// Ignore lower priority regions
if (found && region.getPriority() < lastPriority) {
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){
} else if (region.getFlag(flag) != null) {
clearParents(needsClear, hasCleared, region);
needsClear.put(region, region.getFlag(flag));
found = true;
}
@@ -358,9 +367,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) {
@@ -378,7 +387,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();
@@ -386,8 +395,6 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Get an iterator of affected regions.
*
* @return
*/
public Iterator<ProtectedRegion> iterator() {
return applicable.iterator();
@@ -21,8 +21,10 @@ package com.sk89q.worldguard.protection;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.World;
@@ -34,12 +36,12 @@ 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.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
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.PRTreeRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
@@ -64,7 +66,7 @@ public class GlobalRegionManager {
/**
* Map of managers per-world.
*/
private HashMap<String, RegionManager> managers;
private ConcurrentHashMap<String, RegionManager> managers;
/**
* Stores the list of modification dates for the world files. This allows
@@ -75,12 +77,12 @@ public class GlobalRegionManager {
/**
* Construct the object.
*
* @param plugin
* @param plugin The plugin instance
*/
public GlobalRegionManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
config = plugin.getGlobalStateManager();
managers = new HashMap<String, RegionManager>();
managers = new ConcurrentHashMap<String, RegionManager>();
lastModified = new HashMap<String, Long>();
}
@@ -95,8 +97,8 @@ public class GlobalRegionManager {
/**
* 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(),
@@ -106,13 +108,12 @@ 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,19 +126,26 @@ public class GlobalRegionManager {
lastModified.clear();
}
public RegionManager load(World world) {
RegionManager manager = create(world);
managers.put(world.getName(), manager);
return manager;
}
/**
* 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) {
public RegionManager create(World world) {
String name = world.getName();
ProtectionDatabase database = null;
boolean sql = config.useSqlDatabase;
ProtectionDatabase database;
File file = null;
try {
if (!config.useSqlDatabase) {
if (!sql) {
file = getPath(name);
database = new YAMLDatabase(file, plugin.getLogger());
@@ -148,27 +156,27 @@ public class GlobalRegionManager {
}
// Create a manager
RegionManager manager = new FlatRegionManager(database);
managers.put(name, manager);
RegionManager manager = new PRTreeRegionManager(database);
manager.load();
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
if (plugin.getGlobalStateManager().get(world).summaryOnStart) {
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
}
return manager;
} catch (ProtectionDatabaseException e) {
String logStr = "Failed to load regions from ";
if (config.useSqlDatabase) {
if (sql) {
logStr += "SQL Database <" + config.sqlDsn + "> ";
} else {
logStr += "file \"" + file + "\" ";
}
plugin.getLogger().info(logStr + " : " + e.getMessage());
plugin.getLogger().log(Level.SEVERE, logStr + " : " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
plugin.getLogger().info("Error loading regions for world \""
} catch (FileNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "Error loading regions for world \""
+ name + "\": " + e.toString() + "\n\t" + e.getMessage());
e.printStackTrace();
}
@@ -211,7 +219,7 @@ public class GlobalRegionManager {
load(world);
}
}
} catch (Exception e) {
} catch (Exception ignore) {
}
}
}
@@ -219,14 +227,19 @@ public class GlobalRegionManager {
/**
* 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());
RegionManager newManager = null;
if (manager == null) {
manager = load(world);
while (manager == null) {
if (newManager == null) {
newManager = create(world);
}
managers.putIfAbsent(world.getName(), newManager);
manager = managers.get(world.getName());
}
return manager;
@@ -235,9 +248,9 @@ 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."
@@ -247,21 +260,21 @@ 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
* @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());
@@ -270,9 +283,9 @@ public class GlobalRegionManager {
/**
* 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();
@@ -296,14 +309,11 @@ 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);
@@ -311,7 +321,52 @@ public class GlobalRegionManager {
return true;
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
return mgr.getApplicableRegions(toVector(loc)).allows(flag);
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 = get(world);
return mgr.getApplicableRegions(toVector(loc)).allows(flag, player);
}
}
@@ -48,6 +48,21 @@ import com.sk89q.worldguard.util.ArrayReader;
* @author sk89q
*/
public class CSVDatabase extends AbstractProtectionDatabase {
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;
/**
@@ -63,7 +78,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
* 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, Logger logger) {
this.file = file;
@@ -77,9 +93,6 @@ public class CSVDatabase extends AbstractProtectionDatabase {
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
* Load the database from file.
*/
public void load() throws ProtectionDatabaseException {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
@@ -169,7 +182,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
} finally {
try {
reader.close();
} catch (IOException e) {
} catch (IOException ignored) {
}
}
@@ -193,8 +206,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* 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) {
@@ -236,7 +249,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* 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) {
@@ -267,7 +280,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
flagStr = String.valueOf(k);
}
StateFlag flag = DefaultFlag.getLegacyFlag(flagStr);
StateFlag flag = legacyFlagCodes.get(flagStr);
if (flag != null) {
region.setFlag(flag, curState);
} else {
@@ -321,8 +334,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* 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) {
@@ -334,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;
}
}
@@ -20,20 +20,6 @@
package com.sk89q.worldguard.protection.databases;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
@@ -46,10 +32,23 @@ 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 org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MySQLDatabase extends AbstractProtectionDatabase {
private final Logger logger;
private Yaml yaml;
private Map<String, ProtectedRegion> regions;
private Map<String, ProtectedRegion> cuboidRegions;
@@ -60,24 +59,35 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private final ConfigurationManager config;
private Connection conn;
private String world;
private int worldDbId = -1; // The database will never have an id of -1;
public MySQLDatabase(ConfigurationManager config, String world, Logger logger) throws ProtectionDatabaseException {
this.config = config;
this.world = world;
String world1 = world;
this.logger = logger;
try {
connect();
try {
// Test if the database is up to date, if not throw a critical error
PreparedStatement verTest = this.conn.prepareStatement(
"SELECT `world_id` FROM `region_cuboid` LIMIT 0,1;"
);
verTest.execute();
} catch (SQLException ex) {
throw new InvalidTableFormatException(
"region_storage_update_20110325.sql"
);
}
PreparedStatement worldStmt = conn.prepareStatement(
"SELECT `id` FROM " +
"`world` " +
"WHERE `name` = ? LIMIT 0,1"
);
worldStmt.setString(1, this.world);
worldStmt.setString(1, world1);
ResultSet worldResult = worldStmt.executeQuery();
if (worldResult.first()) {
@@ -110,9 +120,32 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
// no point continuing
return;
}
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setDefaultFlowStyle(FlowStyle.FLOW);
Representer representer = new Representer();
representer.setDefaultFlowStyle(FlowStyle.FLOW);
// We have to use this in order to properly save non-string values
yaml = new Yaml(new SafeConstructor(), new Representer(), options);
}
private void connect() throws SQLException {
if (conn != null) {
// Make a dummy query to check the connnection is alive.
try {
conn.prepareStatement("SELECT 1;").execute();
} catch (SQLException ex) {
// Test if the dummy query failed because the connection is dead,
// and if it is mark the connection as closed (the MySQL Driver
// does not ensure that the connection is marked as closed unless
// the close() method has been called.
if ("08S01".equals(ex.getSQLState())) {
conn.close();
}
}
}
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(config.sqlDsn, config.sqlUsername, config.sqlPassword);
}
@@ -122,11 +155,12 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
// @TODO: Iterate _ONCE_
try {
PreparedStatement flagsStatement = this.conn.prepareStatement(
"SELECT " +
"SELECT " +
"`region_flag`.`flag`, " +
"`region_flag`.`value` " +
"FROM `region_flag` " +
"WHERE `region_flag`.`region_id` = ? "
"WHERE `region_flag`.`region_id` = ? " +
"AND `region_flag`.`world_id` = " + this.worldDbId
);
flagsStatement.setString(1, region.getId().toLowerCase());
@@ -136,8 +170,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
while (flagsResultSet.next()) {
regionFlags.put(
flagsResultSet.getString("flag"),
flagsResultSet.getObject("value")
);
sqlUnmarshal(flagsResultSet.getString("value"))
);
}
// @TODO: Make this better
@@ -178,7 +212,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"LEFT JOIN `user` ON ( " +
"`region_players`.`user_id` = " +
"`user`.`id`) " +
"WHERE `region_players`.`region_id` = ? "
"WHERE `region_players`.`region_id` = ? " +
"AND `region_players`.`world_id` = " + this.worldDbId
);
usersStatement.setString(1, region.getId().toLowerCase());
@@ -203,7 +238,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"LEFT JOIN `group` ON ( " +
"`region_groups`.`group_id` = " +
"`group`.`id`) " +
"WHERE `region_groups`.`region_id` = ? "
"WHERE `region_groups`.`region_id` = ? " +
"AND `region_groups`.`world_id` = " + this.worldDbId
);
groupsStatement.setString(1, region.getId().toLowerCase());
@@ -235,7 +271,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region` " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`type` = 'global' " +
"AND `region`.`world_id` = ? "
);
@@ -289,9 +326,11 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region_cuboid` " +
"LEFT JOIN `region` " +
"ON (`region_cuboid`.`region_id` = `region`.`id`) " +
"ON (`region_cuboid`.`region_id` = `region`.`id` " +
"AND `region_cuboid`.`world_id` = `region`.`world_id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`world_id` = ? "
);
@@ -358,9 +397,11 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region_poly2d` " +
"LEFT JOIN `region` " +
"ON (`region_poly2d`.`region_id` = `region`.`id`) " +
"ON (`region_poly2d`.`region_id` = `region`.`id` " +
"AND `region_poly2d`.`world_id` = `region`.`world_id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`world_id` = ? "
);
@@ -372,7 +413,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`region_poly2d_point`.`x`, " +
"`region_poly2d_point`.`z` " +
"FROM `region_poly2d_point` " +
"WHERE `region_poly2d_point`.`region_id` = ? "
"WHERE `region_poly2d_point`.`region_id` = ? " +
"AND `region_poly2d_point`.`world_id` = " + this.worldDbId
);
while (poly2dResultSet.next()) {
@@ -418,6 +460,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
poly2dRegions = regions;
}
@Override
public void load() throws ProtectionDatabaseException {
try {
connect();
@@ -428,7 +471,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
parentSets = new HashMap<ProtectedRegion,String>();
// We load the cuboid regions first, as this is likely to be the
// largest dataset. This should save time in regards to the putAll()s
// largest dataset. This should save time in regards to the putAll()s
this.loadCuboid();
Map<String,ProtectedRegion> regions = this.cuboidRegions;
this.cuboidRegions = null;
@@ -498,15 +541,15 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
Statement.RETURN_GENERATED_KEYS
);
for(int i=0, len=usernames.length; i<len; i++) {
if (!users.containsKey(usernames[i])) {
insertUserStatement.setString(1, usernames[i]);
for (String username : usernames) {
if (!users.containsKey(username)) {
insertUserStatement.setString(1, username);
insertUserStatement.execute();
ResultSet generatedKeys = insertUserStatement.getGeneratedKeys();
if (generatedKeys.first()) {
users.put(usernames[i], generatedKeys.getInt(1));
users.put(username, generatedKeys.getInt(1));
} else {
logger.warning("Could not get the database id for user " + usernames[i]);
logger.warning("Could not get the database id for user " + username);
}
}
}
@@ -562,15 +605,15 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
Statement.RETURN_GENERATED_KEYS
);
for(int i=0, len=groupnames.length; i<len; i++) {
if (!groups.containsKey(groupnames[i])) {
insertGroupStatement.setString(1, groupnames[i]);
for (String groupname : groupnames) {
if (!groups.containsKey(groupname)) {
insertGroupStatement.setString(1, groupname);
insertGroupStatement.execute();
ResultSet generatedKeys = insertGroupStatement.getGeneratedKeys();
if (generatedKeys.first()) {
groups.put(groupnames[i], generatedKeys.getInt(1));
groups.put(groupname, generatedKeys.getInt(1));
} else {
logger.warning("Could not get the database id for user " + groupnames[i]);
logger.warning("Could not get the database id for user " + groupname);
}
}
}
@@ -590,12 +633,13 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
* b) If the region is not in the database, we insert it
* 3) We iterate over what remains of the in-database list and remove
* them from the database
*
*
* TODO: Look at adding/removing/updating the database when the in
* memory region is created/remove/updated
*
*
* @see com.sk89q.worldguard.protection.databases.ProtectionDatabase#save()
*/
@Override
public void save() throws ProtectionDatabaseException {
try {
connect();
@@ -663,7 +707,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement setParentStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`parent` = ? " +
"WHERE `id` = ? "
"WHERE `id` = ? AND `world_id` = " + this.worldDbId
);
setParentStatement.setString(1, entry.getValue().getParent().getId().toLowerCase());
@@ -694,7 +738,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updateFlags(ProtectedRegion region) throws SQLException {
PreparedStatement clearCurrentFlagStatement = this.conn.prepareStatement(
"DELETE FROM `region_flag` " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearCurrentFlagStatement.setString(1, region.getId().toLowerCase());
@@ -703,15 +748,16 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
for (Map.Entry<Flag<?>, Object> entry : region.getFlags().entrySet()) {
if (entry.getValue() == null) continue;
Object flag = marshalFlag(entry.getKey(), entry.getValue());
Object flag = sqlMarshal(marshalFlag(entry.getKey(), entry.getValue()));
PreparedStatement insertFlagStatement = this.conn.prepareStatement(
"INSERT INTO `region_flag` ( " +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`flag`, " +
"`value` " +
") VALUES (null, ?, ?, ?)"
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
insertFlagStatement.setString(1, region.getId().toLowerCase());
@@ -734,6 +780,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement deleteUsersForRegion = this.conn.prepareStatement(
"DELETE FROM `region_players` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId + " " +
"AND `owner` = ?"
);
@@ -743,12 +790,13 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertUsersForRegion = this.conn.prepareStatement(
"INSERT INTO `region_players` " +
"(`region_id`, `user_id`, `owner`) VALUES (?, ?, ?)"
"(`region_id`, `world_id`, `user_id`, `owner`) " +
"VALUES (?, " + this.worldDbId + ", ?, ?)"
);
Map<String,Integer> players = getUserIds(domain.getPlayers().toArray(new String[0]));
Set<String> var = domain.getPlayers();
for (Integer player : players.values()) {
for (Integer player : getUserIds(var.toArray(new String[var.size()])).values()) {
insertUsersForRegion.setString(1, region.getId().toLowerCase());
insertUsersForRegion.setInt(2, player);
insertUsersForRegion.setBoolean(3, owners);
@@ -759,6 +807,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement deleteGroupsForRegion = this.conn.prepareStatement(
"DELETE FROM `region_groups` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId + " " +
"AND `owner` = ?"
);
@@ -768,12 +817,12 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertGroupsForRegion = this.conn.prepareStatement(
"INSERT INTO `region_groups` " +
"(`region_id`, `group_id`, `owner`) VALUES (?, ?, ?)"
"(`region_id`, `world_id`, `group_id`, `owner`) " +
"VALUES (?, " + this.worldDbId + ", ?, ?)"
);
Map<String,Integer> groups = getGroupIds(domain.getGroups().toArray(new String[0]));
for (Integer group : groups.values()) {
Set<String> groupVar = domain.getGroups();
for (Integer group : getGroupIds(groupVar.toArray(new String[groupVar.size()])).values()) {
insertGroupsForRegion.setString(1, region.getId().toLowerCase());
insertGroupsForRegion.setInt(2, group);
insertGroupsForRegion.setBoolean(3, owners);
@@ -795,12 +844,13 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`type`, " +
"`priority`, " +
"`parent` " +
") VALUES (?, " + this.worldDbId + ", ?, ?, null)"
") VALUES (?, ?, ?, ?, null)"
);
insertRegionStatement.setString(1, region.getId().toLowerCase());
insertRegionStatement.setString(2, type);
insertRegionStatement.setInt(3, region.getPriority());
insertRegionStatement.setInt(2, this.worldDbId);
insertRegionStatement.setString(3, type);
insertRegionStatement.setInt(4, region.getPriority());
insertRegionStatement.execute();
@@ -816,13 +866,14 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertCuboidRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_cuboid` (" +
"`region_id`, " +
"`world_id`, " +
"`min_z`, " +
"`min_y`, " +
"`min_x`, " +
"`max_z`, " +
"`max_y`, " +
"`max_x` " +
") VALUES (?, ?, ?, ?, ?, ?, ?)"
") VALUES (?, " + this.worldDbId + ", ?, ?, ?, ?, ?, ?)"
);
BlockVector min = region.getMinimumPoint();
@@ -845,9 +896,10 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertPoly2dRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d` (" +
"`region_id`, " +
"`world_id`, " +
"`max_y`, " +
"`min_y` " +
") VALUES (?, ?, ?)"
") VALUES (?, " + this.worldDbId + ", ?, ?)"
);
insertPoly2dRegionStatement.setString(1, region.getId().toLowerCase());
@@ -862,7 +914,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updatePoly2dPoints(ProtectedPolygonalRegion region) throws SQLException {
PreparedStatement clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
@@ -873,13 +926,15 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, ?, ?)"
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
String lowerId = region.getId();
for (BlockVector2D point : region.getPoints()) {
insertPoly2dPointStatement.setString(1, region.getId().toLowerCase());
insertPoly2dPointStatement.setString(1, lowerId);
insertPoly2dPointStatement.setInt(2, point.getBlockZ());
insertPoly2dPointStatement.setInt(3, point.getBlockX());
@@ -894,7 +949,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updateRegion(ProtectedRegion region, String type) throws SQLException {
PreparedStatement updateRegionStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`priority` = ? WHERE `id` = ? "
"`priority` = ? WHERE `id` = ? AND `world_id` = " + this.worldDbId
);
updateRegionStatement.setInt(1, region.getPriority());
@@ -919,7 +974,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`max_z` = ?, " +
"`max_y` = ?, " +
"`max_x` = ? " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
BlockVector min = region.getMinimumPoint();
@@ -943,7 +999,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"UPDATE `region_poly2d` SET " +
"`max_y` = ?, " +
"`min_y` = ? " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
updatePoly2dRegionStatement.setInt(1, region.getMaximumPoint().getBlockY());
@@ -959,11 +1016,25 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
updateRegion(region, "global");
}
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = regions;
}
protected Object sqlUnmarshal(String rawValue) {
try {
return yaml.load(rawValue);
} catch (YAMLException e) {
return String.valueOf(rawValue);
}
}
protected String sqlMarshal(Object rawObject) {
return yaml.dump(rawObject);
}
}
@@ -34,39 +34,39 @@ public interface ProtectionDatabase {
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws ProtectionDatabaseException
* @throws ProtectionDatabaseException when an error occurs
*/
public void load() throws ProtectionDatabaseException;
/**
* Save the list of regions.
*
* @throws ProtectionDatabaseException
* @throws ProtectionDatabaseException when an error occurs
*/
public void save() throws ProtectionDatabaseException;
/**
* Load the list of regions into a region manager.
*
* @param manager
* @throws ProtectionDatabaseException
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
public void load(RegionManager manager) throws ProtectionDatabaseException;
/**
* Save the list of regions from a region manager.
*
* @param manager
* @throws ProtectionDatabaseException
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
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);
}
@@ -32,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) {
@@ -59,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) {
@@ -81,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();
@@ -104,8 +104,8 @@ public class RegionDBUtil {
/**
* Creates a comma separated list of PreparedStatement place holders
*
* @param length
* @return
* @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();
@@ -121,9 +121,9 @@ public class RegionDBUtil {
/**
* Adds all of the parsed values to the PreparedStatement
*
* @param preparedStatement
* @param values
* @throws SQLException
* @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++) {
@@ -165,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);
}
}
}
}
@@ -19,6 +19,14 @@
package com.sk89q.worldguard.protection.databases.migrators;
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;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
@@ -29,14 +37,6 @@ 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;
@@ -59,7 +59,7 @@ public class MySQLToYAMLMigrator extends AbstractDatabaseMigrator {
conn.close();
} catch (SQLException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
}
}
@@ -75,7 +75,7 @@ public class MySQLToYAMLMigrator extends AbstractDatabaseMigrator {
oldDatabase = new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
oldDatabase.load();
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
}
return oldDatabase.getRegions();
@@ -89,9 +89,9 @@ public class MySQLToYAMLMigrator extends AbstractDatabaseMigrator {
return new YAMLDatabase(file, plugin.getLogger());
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
}
}
}
@@ -19,12 +19,6 @@
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;
@@ -32,6 +26,12 @@ import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class YAMLToMySQLMigrator extends AbstractDatabaseMigrator {
private WorldGuardPlugin plugin;
@@ -66,9 +66,9 @@ public class YAMLToMySQLMigrator extends AbstractDatabaseMigrator {
oldDatabase = new YAMLDatabase(this.regionYamlFiles.get(world), plugin.getLogger());
oldDatabase.load();
} catch (FileNotFoundException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(e);
}
return oldDatabase.getRegions();
@@ -79,7 +79,7 @@ public class YAMLToMySQLMigrator extends AbstractDatabaseMigrator {
try {
return new MySQLDatabase(plugin.getGlobalStateManager(), world, plugin.getLogger());
} catch (ProtectionDatabaseException e) {
throw new MigrationException((Exception) e);
throw new MigrationException(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;
}
}
@@ -27,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) {
@@ -27,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,7 +19,8 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.entity.CreatureType;
import org.bukkit.GameMode;
import org.bukkit.entity.EntityType;
/**
*
@@ -27,21 +28,23 @@ import org.bukkit.entity.CreatureType;
*/
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 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);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true, RegionGroup.ALL);
public static final StateFlag OTHER_EXPLOSION = new StateFlag("other-explosion", true);
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", false, RegionGroup.NON_MEMBERS);
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);
@@ -55,76 +58,65 @@ public final class DefaultFlag {
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 MYCELIUM_SPREAD = new StateFlag("mycelium-spread", true);
public static final StateFlag VINE_GROWTH = new StateFlag("vine-growth", true);
public static final StateFlag ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false);
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", 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 IntegerFlag MIN_HEAL = new IntegerFlag("heal-min-health");
public static final IntegerFlag MAX_HEAL = new IntegerFlag("heal-max-health");
public static final IntegerFlag FEED_DELAY = new IntegerFlag("feed-delay");
public static final IntegerFlag FEED_AMOUNT = new IntegerFlag("feed-amount");
public static final IntegerFlag MIN_FOOD = new IntegerFlag("feed-min-hunger");
public static final IntegerFlag MAX_FOOD = new IntegerFlag("feed-max-hunger");
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 ENDERPEARL = new StateFlag("enderpearl", true);
public static final StateFlag ENTITY_PAINTING_DESTROY = new StateFlag("entity-painting-destroy", true);
public static final StateFlag ENTITY_ITEM_FRAME_DESTROY = new StateFlag("entity-item-frame-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 IntegerFlag MAX_PLAYERS = new IntegerFlag("max-players-allowed", RegionGroup.ALL);
// public static final StringFlag MAX_PLAYERS_MESSAGE = new StringFlag("max-players-reject-message", 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 StateFlag ENABLE_SHOP = new StateFlag("allow-shop", false);
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, CHEST_ACCESS, PISTONS,
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,
CREEPER_EXPLOSION, OTHER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, EXIT_PERM, ENTRY, ENTRY_PERM, LIGHTNING,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY, ENDERPEARL,
ENTITY_ITEM_FRAME_DESTROY, ITEM_DROP, /*MAX_PLAYERS, MAX_PLAYERS_MESSAGE,*/
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD,
FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, TELE_PERM, SPAWN_LOC, SPAWN_PERM,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, MYCELIUM_SPREAD, VINE_GROWTH,
SEND_CHAT, RECEIVE_CHAT, FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, SPAWN_LOC, POTION_SPLASH,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE, ENABLE_SHOP
};
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;
}
}
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
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) {
@@ -18,28 +18,28 @@
*/
package com.sk89q.worldguard.protection.flags;
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;
}
@@ -29,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;
}
@@ -41,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) {
@@ -88,5 +92,5 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
public Object marshal(T o) {
return o.name();
}
}
@@ -30,24 +30,26 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public abstract class Flag<T> {
private String name;
private Character legacyCode;
public Flag(String name, char legacyCode) {
private RegionGroupFlag regionGroup;
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,
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
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) {
@@ -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 ignored) {
}
}
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;
}
}
}
@@ -0,0 +1,31 @@
/*
* 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
}
@@ -18,10 +18,7 @@
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -29,24 +26,12 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
*
* @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;
}
@@ -55,8 +40,7 @@ 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")) {
@@ -67,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("Expected [non]member/[non]owner/anyone but got '" + 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;
}
@@ -129,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;
}
@@ -36,9 +36,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
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;
}
@@ -34,10 +34,9 @@ public class StateFlag extends Flag<StateFlag.State> {
}
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;
}
@@ -50,14 +49,6 @@ 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 {
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
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) {
@@ -39,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
@@ -33,9 +33,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
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) {
@@ -43,14 +43,29 @@ 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 ignored) {
}
}
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
}
@@ -18,13 +18,6 @@
*/
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;
@@ -32,6 +25,8 @@ import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.*;
/**
* A very simple implementation of the region manager that uses a flat list
* and iterates through the list to identify applicable regions. This method
@@ -49,46 +44,28 @@ 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());
@@ -96,9 +73,7 @@ public class FlatRegionManager 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());
}
@@ -110,33 +85,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 =
@@ -182,12 +135,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>();
@@ -201,11 +148,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) {
@@ -223,13 +165,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>();
@@ -252,11 +187,6 @@ public class FlatRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -18,24 +18,18 @@
*/
package com.sk89q.worldguard.protection.managers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
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 org.khelekore.prtree.MBR;
import org.khelekore.prtree.MBRConverter;
import org.khelekore.prtree.PRTree;
import org.khelekore.prtree.SimpleMBR;
import java.util.*;
public class PRTreeRegionManager extends RegionManager {
@@ -56,29 +50,19 @@ public class PRTreeRegionManager extends RegionManager {
/**
* Construct the manager.
*
* @param regionloader
* @throws IOException
* @param regionLoader The region loader to use
*/
public PRTreeRegionManager(ProtectionDatabase regionloader) throws ProtectionDatabaseException {
super(regionloader);
public PRTreeRegionManager(ProtectionDatabase regionLoader) {
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);
@@ -86,11 +70,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);
@@ -98,32 +77,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());
@@ -132,9 +90,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());
}
@@ -145,27 +101,32 @@ public class PRTreeRegionManager extends RegionManager {
}
}
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
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 =
new ArrayList<ProtectedRegion>();
int x = pt.getBlockX();
int z = pt.getBlockZ();
// Floor the vector to ensure we get accurate points
pt = pt.floor();
for (ProtectedRegion region : tree.find(x, z, x, z)) {
if (region.contains(pt)) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
MBR pointMBR = new SimpleMBR(pt.getX(), pt.getX(), pt.getY(), pt.getY(), pt.getZ(), pt.getZ());
for (ProtectedRegion region : tree.find(pointMBR)) {
if (region.contains(pt) && !appRegions.contains(region)) {
appRegions.add(region);
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (!appRegions.contains(parent)) {
appRegions.add(parent);
}
parent = parent.getParent();
}
}
}
@@ -189,35 +150,34 @@ 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) {
// Floor the vector to ensure we get accurate points
pt = pt.floor();
List<String> applicable = new ArrayList<String>();
MBR pointMBR = new SimpleMBR(pt.getX(), pt.getX(), pt.getY(), pt.getY(), pt.getZ(), pt.getZ());
int x = pt.getBlockX();
int z = pt.getBlockZ();
for (ProtectedRegion region : tree.find(x, z, x, z)) {
if (region.contains(pt)) {
for (ProtectedRegion region : tree.find(pointMBR)) {
if (region.contains(pt) && !applicable.contains(region.getId())) {
applicable.add(region.getId());
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (!applicable.contains(parent.getId())) {
applicable.add(parent.getId());
}
parent = parent.getParent();
}
}
}
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>();
@@ -240,11 +200,6 @@ public class PRTreeRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -262,4 +217,4 @@ public class PRTreeRegionManager extends RegionManager {
return count;
}
}
}
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.protection.managers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@@ -45,7 +44,7 @@ public abstract class RegionManager {
/**
* Construct the object.
*
* @param loader
* @param loader The loader for this region
*/
public RegionManager(ProtectionDatabase loader) {
this.loader = loader;
@@ -55,7 +54,7 @@ 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 ProtectionDatabaseException {
loader.load(this);
@@ -64,7 +63,7 @@ public abstract class RegionManager {
/**
* 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 ProtectionDatabaseException {
loader.save(this);
@@ -102,13 +101,41 @@ public abstract class RegionManager {
*/
public abstract boolean hasRegion(String 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 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 abstract ProtectedRegion getRegion(String id);
public ProtectedRegion getRegionExact(String id) {
return getRegions().get(id.toLowerCase());
}
/**
* Removes a region, including inheriting children.
@@ -36,9 +36,9 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param pt1
* @param pt2
* @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 pt1, BlockVector pt2) {
super(id);
@@ -48,8 +48,8 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Given any two points, sets the minimum and maximum points
*
* @param pt1
* @param pt2
* @param pt1 The first point of this region
* @param pt2 The second point of this region
*/
private void setMinMaxPoints(BlockVector pt1, BlockVector pt2) {
List<Vector> points = new ArrayList<Vector>();
@@ -61,7 +61,7 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Set the lower point of the cuboid.
*
* @param pt
* @param pt The point to set as the minimum point
*/
public void setMinimumPoint(BlockVector pt) {
setMinMaxPoints(pt, max);
@@ -70,7 +70,7 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Set the upper point of the cuboid.
*
* @param pt
* @param pt The point to set as the maximum point
*/
public void setMaximumPoint(BlockVector pt) {
setMinMaxPoints(min, pt);
@@ -91,9 +91,6 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
return pts;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
final double x = pt.getX();
@@ -157,29 +154,17 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
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;
}
}
@@ -42,9 +42,9 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
/**
* Sets the min and max points from all the 2d points and the min/max Y values
*
* @param points2D
* @param minY
* @param maxY
* @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>();
@@ -156,11 +156,6 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
return "polygon";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int volume = 0;
@@ -19,12 +19,6 @@
package com.sk89q.worldguard.protection.regions;
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;
@@ -33,6 +27,12 @@ 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;
/**
* Represents a region of any shape and size that can be protected.
*
@@ -78,7 +78,7 @@ 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;
@@ -87,7 +87,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Sets the minimum and maximum points of the bounding box for a region
*
* @param points
* @param points The points to set. Must have at least one element.
*/
protected void setMinMaxPoints(List<Vector> points) {
int minX = points.get(0).getBlockX();
@@ -116,6 +116,8 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
}
/**
* Gets the id of this region
*
* @return the id
*/
public String getId() {
@@ -166,7 +168,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* 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) {
@@ -251,6 +253,29 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
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.
@@ -259,14 +284,45 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* @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;
}
@@ -303,9 +359,9 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* 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")
@@ -323,10 +379,10 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* 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) {
@@ -339,7 +395,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get the map of flags.
*
* @return
* @return The map of flags currently used for this region
*/
public Map<Flag<?>, Object> getFlags() {
return flags;
@@ -348,7 +404,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get the map of flags.
*
* @param flags
* @param flags The flags to set
*/
public void setFlags(Map<Flag<?>, Object> flags) {
this.flags = flags;
@@ -357,30 +413,30 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Gets the 2D points for this region
*
* @return
* @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);
/**
* 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 boolean contains(BlockVector2D pt) {
return contains(new Vector(pt.getBlockX(), min.getBlockY(), pt.getBlockZ()));
@@ -389,10 +445,10 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Check to see if a point is inside this region.
*
* @param x
* @param y
* @param z
* @return
* @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));
@@ -419,8 +475,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* Orders primarily by the priority, descending<br>
* Orders secondarily by the id, ascending
*
* @param other
* @return
* @param other The region to compare to
*/
public int compareTo(ProtectedRegion other) {
if (priority > other.priority) {
@@ -442,9 +497,9 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* 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)
@@ -454,7 +509,8 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* Checks if the bounding box of a region intersects with with the bounding
* box of this region
*
* @param region
* @param region The region to check
* @return whether the given region intersects
*/
protected boolean intersectsBoundingBox(ProtectedRegion region) {
BlockVector rMaxPoint = region.getMaximumPoint();
@@ -477,33 +533,33 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Compares all edges of two regions to see if any of them intersect
*
* @param region
* @return
* @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++) {
for (BlockVector2D aPts1 : pts1) {
for (BlockVector2D aPts2 : pts2) {
Line2D line1 = new Line2D.Double(
lastPt1.getBlockX(),
lastPt1.getBlockZ(),
pts1.get(i).getBlockX(),
pts1.get(i).getBlockZ());
aPts1.getBlockX(),
aPts1.getBlockZ());
if (line1.intersectsLine(
lastPt2.getBlockX(),
lastPt2.getBlockZ(),
pts2.get(j).getBlockX(),
pts2.get(j).getBlockZ())) {
lastPt2.getBlockX(),
lastPt2.getBlockZ(),
aPts2.getBlockX(),
aPts2.getBlockZ())) {
return true;
}
lastPt2 = pts2.get(j);
lastPt2 = aPts2;
}
lastPt1 = pts1.get(i);
lastPt1 = aPts1;
}
return false;
}
@@ -511,16 +567,14 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* 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();
@@ -542,7 +596,6 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Thrown when setting a curParent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
@@ -22,19 +22,35 @@ package com.sk89q.worldguard.protection.regions;
import org.khelekore.prtree.MBRConverter;
public class ProtectedRegionMBRConverter implements MBRConverter<ProtectedRegion> {
public double getMinX(ProtectedRegion t) {
return t.getMinimumPoint().getBlockX();
@Override
public int getDimensions() {
return 3;
}
public double getMinY(ProtectedRegion t) {
return t.getMinimumPoint().getBlockZ();
@Override
public double getMax(int dimension, ProtectedRegion region) {
switch (dimension) {
case 0:
return region.getMaximumPoint().getBlockX();
case 1:
return region.getMaximumPoint().getBlockY();
case 2:
return region.getMaximumPoint().getBlockZ();
}
return 0;
}
public double getMaxX(ProtectedRegion t) {
return t.getMaximumPoint().getBlockX();
}
public double getMaxY(ProtectedRegion t) {
return t.getMaximumPoint().getBlockZ();
@Override
public double getMin(int dimension, ProtectedRegion region) {
switch (dimension) {
case 0:
return region.getMinimumPoint().getBlockX();
case 1:
return region.getMinimumPoint().getBlockY();
case 2:
return region.getMinimumPoint().getBlockZ();
}
return 0;
}
}
@@ -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;
}
@@ -84,7 +84,7 @@ public class PastebinPoster {
in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append("\r\n");
@@ -114,13 +114,13 @@ public class PastebinPoster {
if (in != null) {
try {
in.close();
} catch (IOException e) {
} catch (IOException ignored) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
} catch (IOException ignored) {
}
}
}
@@ -1,41 +0,0 @@
/*
* WorldGuard
* Copyright (C) 2011 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;
import java.lang.reflect.Field;
/**
* @author zml2008
*/
public class ReflectionUtil {
@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
Class<?> checkClass = from.getClass();
do {
try {
Field field = checkClass.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(from);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
return null;
}
}
@@ -19,83 +19,58 @@
package com.sk89q.worldguard.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
/**
* Various utility functions for regions.
*
* @author sk89q
*/
@Deprecated
public class RegionUtil {
private static Pattern groupPattern = Pattern.compile("^[gG]:(.+)$");
private RegionUtil() {
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#addToDomain(com.sk89q.worldguard.domains.DefaultDomain, String[], int)}
*/
@Deprecated
public static void addToDomain(DefaultDomain domain, String[] split,
int startIndex) {
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.addGroup(m.group(1));
} else {
domain.addPlayer(s);
}
}
RegionDBUtil.addToDomain(domain, split, startIndex);
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain to add to
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#removeFromDomain(com.sk89q.worldguard.domains.DefaultDomain, String[], int)}
*/
@Deprecated
public static void removeFromDomain(DefaultDomain domain, String[] split,
int startIndex) {
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.removeGroup(m.group(1));
} else {
domain.removePlayer(s);
}
}
RegionDBUtil.removeFromDomain(domain, split, startIndex);
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
*
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#parseDomainString(String[], int)}
* @return the parsed domain
*/
@Deprecated
public static DefaultDomain parseDomainString(String[] split, int startIndex) {
DefaultDomain domain = new DefaultDomain();
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.addGroup(m.group(1));
} else {
domain.addPlayer(s);
}
}
return domain;
return RegionDBUtil.parseDomainString(split, startIndex);
}
}
@@ -19,11 +19,12 @@
package com.sk89q.worldguard;
import java.util.Set;
import java.util.HashSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import java.util.Set;
import com.sk89q.worldedit.Vector;
@org.junit.Ignore
public class TestPlayer extends LocalPlayer {
private String name;
private Set<String> groups = new HashSet<String>();
@@ -48,32 +49,27 @@ public class TestPlayer extends LocalPlayer {
@Override
public Vector getPosition() {
// TODO Auto-generated method stub
return null;
return new Vector(0, 0, 0);
}
@Override
public void kick(String msg) {
// TODO Auto-generated method stub
System.out.println("TestPlayer{" + this.name + "} kicked!");
}
@Override
public void ban(String msg) {
// TODO Auto-generated method stub
System.out.println("TestPlayer{" + this.name + "} banned!");
}
@Override
public void printRaw(String msg) {
// TODO Auto-generated method stub
System.out.println("-> TestPlayer{" + this.name + "}: " + msg);
}
@Override
public String[] getGroups() {
// TODO Auto-generated method stub
return null;
return groups.toArray(new String[groups.size()]);
}
@Override
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more