Compare commits

...
224 Commits
Author SHA1 Message Date
sk89q 1241e18f9c Added /worldguard report [-p] 2011-04-03 17:20:13 -07:00
sk89q 6566acf7eb Added more aliases to /region subcommands. 2011-04-03 11:05:48 -07:00
sk89q 4332ed92f2 Added /region select. 2011-04-03 11:04:18 -07:00
sk89q 2e7f96aab0 Fixed /region setparent. 2011-04-03 10:35:06 -07:00
sk89q 21a04cc8c8 Added anti-wolf-dumbness. 2011-04-02 22:44:45 -07:00
sk89q dcc1b59627 Fixed region bypass. 2011-04-02 19:46:26 -07:00
sk89q e8fb3e6d24 Added a region high frequency flags setting to disable high frequency flags. Enable it if you've got the system resources to support it. This covers the fire spread, lava fire spread, lava flow, and water flow flags. 2011-04-02 18:45:11 -07:00
sk89q 93d084d5ba Caught CircularInheritanceException exception. 2011-04-02 18:02:16 -07:00
sk89q e45ecf9c86 Added the ability to clear parents with /region setparent. 2011-04-02 18:01:59 -07:00
sk89q beb10e22f2 Changed the /region flag flags list to check permissions. 2011-04-02 18:00:48 -07:00
sk89q 64b12f8497 Improved vehicle place flag to handle boats. 2011-04-02 17:57:58 -07:00
sk89q 0821a08df2 Updated /god to remove fire. 2011-04-02 17:53:09 -07:00
sk89q 50870a9b32 Fixed flag resolution algorithm not catching NoSuchElementException correctly. Now the spawn flag works. Note that the IDs for the spawn and farewell/greeting flags were changed. 2011-04-02 17:49:11 -07:00
sk89q b823446e28 Fixed flags, added separate lava flow flag. 2011-04-02 17:43:01 -07:00
sk89q 48b00874e5 Removed extra space. 2011-04-02 17:23:56 -07:00
sk89q deba6c79f3 Re-implemented the region spawn location flag. 2011-04-02 17:21:05 -07:00
sk89q c0be10ad94 Changed /god to mention /ungod. 2011-04-02 17:05:11 -07:00
sk89q 5010d35ff3 Added a basic API. 2011-04-02 16:26:35 -07:00
sk89q 42d26a1f4f Moved blacklist logger configuration back to be per-world. 2011-04-02 16:24:37 -07:00
sk89q 92c25d2df4 Updated default configuration file. 2011-04-02 16:22:27 -07:00
sk89q 5b5349fc34 Improved amphibious stuff, added pumpkin scuba. 2011-04-02 16:07:59 -07:00
sk89q cc6ac93b7a Fixed auto-god mode and auto-amphibious mode. 2011-04-02 15:58:52 -07:00
sk89q 1b843b3586 Fixed /god. 2011-04-02 15:54:41 -07:00
sk89q 3b9a426547 Fixed some flags and permissions. 2011-04-02 15:39:44 -07:00
sk89q 989ba0103d Added snakeyaml.jar to the build.xml file. 2011-04-02 14:19:01 -07:00
sk89q b584b996a3 Fixed parenting not saving. 2011-04-02 14:11:12 -07:00
sk89q 896c7fc467 Improved the cake processing mix to be less bitter. 2011-04-02 13:48:40 -07:00
sk89q bd2393342f Fixed the blacklist. 2011-04-02 13:35:57 -07:00
sk89q 762b10cb17 Fixed CSV->YAML conversion. 2011-04-02 12:15:40 -07:00
sk89q 9322eedb4e Fixed an error with the legacy flags. 2011-04-02 11:48:06 -07:00
sk89q 4e2a902b75 Fixed flag resolution algorithm. 2011-04-02 11:47:14 -07:00
sk89q d3b8bd6f39 Fixed more default flag values. 2011-04-02 10:41:33 -07:00
sk89q 0fa64dad7f Fixed the default values for the flags. 2011-04-02 10:40:30 -07:00
sk89q 792e8663e6 Re-implemented the block/player interact hooks that changed in Bukkit recently. 2011-04-02 10:17:02 -07:00
sk89q 4dc999b0d9 Fixed up default configuration files. 2011-04-02 02:40:01 -07:00
sk89q 7c15c2de41 Re-added /worldguard set of commands. 2011-04-02 02:33:23 -07:00
sk89q 43137c3e53 Rolled in Stefan's changes. 2011-04-02 02:07:42 -07:00
sk89q 521ecd438e Added proper support for global regions and a region ID validation regex. 2011-04-02 02:03:32 -07:00
sk89q 949c6599b3 Disallowed '.' in region IDs. 2011-04-02 01:41:13 -07:00
sk89q ea79efe693 /stack re-added. 2011-04-02 01:36:05 -07:00
sk89q b4a89462f8 /locate re-added, but it doesn't seem to work. (Potential Bukkit bug.) 2011-04-02 01:26:22 -07:00
sk89q 70bd3d0e9a Re-added /slay and /heal. 2011-04-02 01:20:11 -07:00
sk89q c33474e0f9 Added /god back in. 2011-04-02 01:16:10 -07:00
sk89q 3d0ebe5c91 Made /stopfire and /allowfire say the world that it was toggled for. 2011-04-02 00:42:19 -07:00
sk89q a9ab0702e0 /region update added. 2011-04-02 00:33:07 -07:00
sk89q 9272741a3c Added more region commands. 2011-04-02 00:18:28 -07:00
sk89q 2b72a99608 Re-added /region setparent. 2011-04-01 23:39:13 -07:00
sk89q 4c38e10fe1 Re-added /region save and /region load. 2011-04-01 23:31:28 -07:00
sk89q 7806b48d34 Re-added /region remove. 2011-04-01 23:23:23 -07:00
sk89q 9803d6b731 Improved YAML loading/saving. 2011-04-01 22:46:45 -07:00
sk89q 649db3aca2 Fixed an extraneous space in an insignificant message. 2011-04-01 22:46:26 -07:00
sk89q b75ab68e7a Completed marshalling implementations for all the flags and changed the LocationFlag to a VectorFlag. 2011-04-01 22:34:31 -07:00
sk89q 8ffc42d349 Added marshalling implementations for most of the flags, fixed configuration issue in WorldConfiguration. 2011-04-01 22:21:30 -07:00
sk89q 145c9750cd Added YAML protection database driver. 2011-04-01 22:12:29 -07:00
sk89q 12647c3a6c Project files and .gitignore should not be in the repo. 2011-04-01 18:28:23 -07:00
sk89q 056f8a57c7 Removed JSON database support. Restored flag loading support to the CSV database so that they can be ported over to the new format. 2011-04-01 18:24:34 -07:00
sk89q 94f0acf9f3 Fixed permissions not being loaded. 2011-04-01 18:05:24 -07:00
sk89q 40bf65d56a Updated for latest Bukkit. 2011-04-01 17:51:33 -07:00
sk89q 726e3a5c20 Added /region flag. DON'T USE THIS VERSION ON A PRODUCTION SERVER. 2011-04-01 13:39:29 -07:00
sk89q d1cab0da7f More stuff works. 2011-03-30 12:01:11 -07:00
sk89q ede4873c6a More progress. 2011-03-27 23:49:30 -07:00
sk89q fd8c827bf1 Updated createDefaultConfiguration() to create parent directories. 2011-03-27 11:18:30 -07:00
sk89q 20afbdf264 More is working! DO NOT USE THIS YET or I will have to personally slap you. 2011-03-26 19:33:29 -07:00
sk89q 0dd92e5189 Work in progress. EVERYTHING IS BROKEN. 2011-03-26 16:59:06 -07:00
sk89q 4b1ba5acb0 Fixed permissions not being load()ed. 2011-03-22 09:34:40 -07:00
sk89q edc94594eb Some cleanup. 2011-03-17 02:31:38 -07:00
DarkLiKally 837efb75d1 Updated iConomy.jar and added quickfix for timed flags crash 2011-03-14 12:01:43 +01:00
DarkLiKally 252208a479 Fixed DoubleRegionFlags 2011-03-10 16:18:30 +01:00
Redecouverte 2641cb7d4f fixed permissions for commands, hasPermission() does "worldguard." + perm so do prefix with "worldguard." 2011-03-09 13:36:10 +01:00
Redecouverte 9c91f06c5d re-added Init() functions to flags class, do not remove it, or the flags class will NOT be loaded on startup which will cause unexpected behaviour 2011-03-09 13:30:07 +01:00
sk89q 7fab4144ae Fixed bad merge. 2011-03-08 10:06:40 -08:00
sk89q 81eb2cad1a Some initial code reorganization. Todo: Have CSVDatabase handle flags so they can be ported over, and do the commands system a cleaner way. 2011-03-08 10:03:49 -08:00
DarkLiKally eda7db7aca Updated MobType to CreateType 2011-03-08 08:54:33 +01:00
DarkLiKally 45a7653dcd Updated iConomy.jar to 4.4.3 (Arcadia) 2011-03-07 08:38:39 +01:00
Valentin Churavy 36fef995e4 fixed nullpointer exception in GlobalRegionManager.java 2011-03-06 15:25:41 +01:00
DarkLiKally af2e862ca2 Updated iConomy.jar to 4.3(.1) 2011-03-04 12:04:30 +01:00
DarkLiKally 7f48ce06be Updated iConomy.jar to 4.2 2011-03-03 10:02:39 +01:00
Redecouverte 1c5ae9ef67 make sure the Flags class is always loaded on startup 2011-03-02 17:37:31 +01:00
Redecouverte 3bf18c41bb flags are now type-safe 2011-03-02 17:24:33 +01:00
DarkLiKally 7ab49f1909 Fixed command /buyregion 2011-03-02 16:44:02 +01:00
DarkLiKally 44b5e5548d added message if player has not enough money for the region 2011-03-02 16:28:01 +01:00
DarkLiKally 50ca9d129b Updated /buyregion command 2011-03-02 15:57:37 +01:00
DarkLiKally 7b725d655c Fixed sign alternative for /buyregion 2011-03-02 13:43:21 +01:00
DarkLiKally 3e9c7aa74b Fixed error with player-eat-check 2011-03-01 19:58:54 +01:00
DarkLiKally 916ed2652e Added check if player eats something 2011-03-01 19:43:50 +01:00
DarkLiKally 59a1726e8c Fixed heal flag (for max. player health(20)) 2011-03-01 15:18:34 +01:00
DarkLiKally 20f91b5258 Fixed denyspawn flag 2011-03-01 12:45:20 +01:00
Redecouverte 353ce7e825 removed legacy comments 2011-02-28 21:15:41 +01:00
Redecouverte 94be4ab18e updated permissions_list.txt 2011-02-28 20:39:30 +01:00
DarkLiKally df7409607f Added administrator notification functionality and flag for greets and farewells 2011-02-28 20:28:14 +01:00
Redecouverte 79b937e8d2 yet another fix for state flag fallback 2011-02-28 19:57:20 +01:00
DarkLiKally 83c6c9c743 Removed unused imports from WorldGuardVehicleListener.java 2011-02-28 19:47:25 +01:00
Redecouverte 6a2affc0f9 new global flags are now read from .yml files 2011-02-28 19:36:46 +01:00
Redecouverte 8ad713c183 implemented passthrough flag 2011-02-28 19:32:59 +01:00
DarkLiKally f8fb746f64 Fixed WorldGuardVehicleListener.java 2011-02-28 19:19:45 +01:00
DarkLiKally c6b3507bf4 Added placeVehicle Flag 2011-02-28 19:15:37 +01:00
Redecouverte 2dc95da6e0 moved registerEvents() int event listeners 2011-02-28 19:05:07 +01:00
Redecouverte 8f9bfcf474 enum flags now also take lovercase names 2011-02-28 18:51:37 +01:00
Redecouverte a8b54757e9 fixed /region info and region flag fallback 2011-02-28 18:36:19 +01:00
Redecouverte 19cfd9edc6 renamed new map to not confuse gson 2011-02-28 18:14:44 +01:00
Redecouverte 03d0f962e5 some more fixes for the new flag containers 2011-02-28 18:08:52 +01:00
Redecouverte 0ff24627ca fixed npe with new flag containers 2011-02-28 17:47:51 +01:00
Redecouverte 4d8cd430b7 renamed isFlagAllowed() to isStateFlagAllowed() 2011-02-28 17:25:31 +01:00
Redecouverte 30b0e5d0b1 rewrote flag system to end the madness 2011-02-28 17:19:51 +01:00
Redecouverte cdf067bba8 fixed crash in removeRegion 2011-02-28 11:00:37 +01:00
Redecouverte e4d05e14ac now using new command system 2011-02-28 10:45:00 +01:00
DarkLiKally 82dc78523f Added sign alternative for /buyregion
Added flag for lever and button usability
2011-02-28 10:42:34 +01:00
Redecouverte 676e744c02 replaced string comparison with instanceof 2011-02-28 00:52:26 +01:00
Redecouverte 0d80265ff2 updated permissions example in config.yml, fixed typo in CommandTpRegion, removed debug output in RegionCommandHandler 2011-02-28 00:49:24 +01:00
DarkLiKally 442521a73c Added getIntersectingRegions() method for polygonal and cuboid regions 2011-02-27 21:03:46 +01:00
Redecouverte dcef083e30 fixed worldguard.notify and worldguard.bypass permissions, optimized getApplicableRegionSet() calls 2011-02-27 19:31:49 +01:00
Redecouverte 162cd20f80 added permissions worldguard.region.priority.own and worldguard.region.priority.all 2011-02-27 18:43:39 +01:00
Redecouverte c74433422a region priority is now set correctly in /region claim 2011-02-27 18:40:32 +01:00
Redecouverte f338650b24 hopefully final fix for tnt block 2011-02-27 18:20:07 +01:00
Redecouverte 65c0d77d3e updated protection classes for getIntersectingRegions() 2011-02-27 18:16:09 +01:00
Redecouverte 09a150b6e9 updated config.yml, removed old permissions 2011-02-27 17:59:01 +01:00
Redecouverte 06173a446a blacklist can now be used as whitelist 2011-02-27 17:48:07 +01:00
Redecouverte d6adea447e json data is now reloaded if manually edited 2011-02-27 17:25:13 +01:00
Redecouverte d042b785ed updated tnt fix, updated respawn teleport 2011-02-27 17:00:34 +01:00
Redecouverte 881846d301 fixed tnt block npe thanks to Brettflan, added claim-only-inside-existing-regions and max-region-count-per-player region options, updated ApplicableRegionSet for regions 2011-02-27 16:24:07 +01:00
DarkLiKally 2092cc43b3 Updated for iConomy 4.0 2011-02-27 09:54:43 +01:00
DarkLiKally dc637d0f2b Fixed wall sign protection 2011-02-26 16:54:18 +01:00
DarkLiKally 987a20b33c Added ability to set a max. claim volume 2011-02-26 15:35:48 +01:00
DarkLiKally dbf65f798f Optimized the countBlocks() method for polygonal regions 2011-02-26 14:56:49 +01:00
DarkLiKally 97aa259b2d Added method to count the blocks in a polygonal region 2011-02-26 14:54:25 +01:00
Redecouverte 770a108bad /region info now names locations correctly 2011-02-26 13:18:31 +01:00
DarkLiKally 71aaa574b2 Added method to count the blocks in a cuboid region 2011-02-26 13:11:27 +01:00
Redecouverte a02fe633e2 fixed spawn/teleport flags 2011-02-26 12:49:14 +01:00
Redecouverte 0669bab563 added aliases /rd, /rc, /rf, /ri, /rl, /rp for region commands 2011-02-26 12:24:49 +01:00
Redecouverte a258400443 fixed npe for onPlayerRespawn 2011-02-26 12:00:02 +01:00
Redecouverte d02c5057c6 for
/region flag id name subname some string with spacaes

valueStr now contains 'some string with spaces'

this does only work for flags with a subname
2011-02-26 11:57:15 +01:00
Redecouverte a473f47235 /tpregion now checks for flag rights 2011-02-26 01:18:50 +01:00
Redecouverte 7bedf6bb15 fixed logical error in playerlistener 2011-02-26 01:08:18 +01:00
Redecouverte 9d813290c6 removed upcoming settings 2011-02-26 01:02:47 +01:00
Redecouverte 05239bccb0 updated FlagInfo, don't check for commands directly in CommandRegionFlag, use FlagInfo 2011-02-26 00:51:35 +01:00
Redecouverte 1d5c28f37f optimized getAffectedRegion() 2011-02-26 00:21:02 +01:00
Redecouverte 16fb6b4f9d fixed some major flaws in the flag system 2011-02-26 00:21:01 +01:00
Redecouverte 97b09aab34 added /region priority command, fixed loading region parent loading 2011-02-26 00:21:01 +01:00
Valentin Churavy 55210caceb Added onPlayerRespawn and registered listener 2011-02-25 23:25:08 +01:00
Valentin Churavy 8127e56603 Added /region flag <id> (spawn|teleport) (allow|deny)
(all|owner|member).
2011-02-25 23:11:21 +01:00
DarkLiKally e61b496ca4 Fixed iConomy 4.0 API support 2011-02-25 21:53:19 +01:00
Redecouverte 3ed8eb76c2 better error messgae for /region flag 2011-02-25 21:17:13 +01:00
Redecouverte a5c3b8a245 more fixed for flag system and /region flag 2011-02-25 21:13:37 +01:00
Redecouverte 3f5d52f901 getAreaFlag() functions now won't throw exceptions, updated /region info, fixed a typo in /region flag, parent regions are no longer required to overlap their children 2011-02-25 20:58:48 +01:00
Redecouverte 46e0607a26 /region info now outputs all flag types, /region flag cspawn still needs fixing 2011-02-25 19:20:49 +01:00
Redecouverte 23fa7a89ad some fixes for /region flag 2011-02-25 18:53:28 +01:00
Redecouverte dcd379bce7 location flags are now supported in FlagInfo class 2011-02-25 18:42:27 +01:00
Redecouverte 40238a9d25 added input filter for json parser 2011-02-25 18:04:21 +01:00
Redecouverte 44db374e09 better console output 2011-02-25 17:50:19 +01:00
Redecouverte d960d543ff fixed npe in creature spawn event listener 2011-02-25 17:44:03 +01:00
Redecouverte 0a45292587 merged with recent commits 2011-02-25 17:28:08 +01:00
Redecouverte 9b4a7c705b configuration is now per-world, updated permissions, made commands compatible with console where possible, /region flag now checks correctly for permissions, & some fixes 2011-02-25 16:50:28 +01:00
DarkLiKally 71a6d8ab44 Updated for iConomy 4.0 API 2011-02-25 15:30:28 +01:00
DarkLiKally 91f9acb633 Fixed /buyregion bug (now regions can be bought only one time) 2011-02-25 12:40:22 +01:00
DarkLiKally 0e45dc5a3f Improved iConomy support: added functionality to /buyregion to set the owenr of the region 2011-02-25 12:37:15 +01:00
DarkLiKally 3341574e02 Replaced some tabs with spaces 2011-02-25 12:22:58 +01:00
DarkLiKally 881dc38a18 Fixed for iConomy 3.0 and
fixed tha tabs in plugin.yml
2011-02-25 10:35:15 +01:00
DarkLiKally e54b201aa5 Updated for iConomy 3.0 2011-02-25 10:06:13 +01:00
DarkLiKally 2d06a40127 Added iConomy.jar to build.xml 2011-02-25 01:48:42 +01:00
DarkLiKally f7e68798fa Added iConomy.jar to the librarys and the /buyregion command class for iConomy Support 2011-02-25 01:41:06 +01:00
DarkLiKally b9fe5d2afc Added iConomy support:
- Ability to pay for claiming a region (price per block)
- Ability to create buyable regions with custom price

NOTE: inserted only placeholders for countBlocks(); so buy on claim will not work correctly

INFO: I had not enough time to test it
2011-02-25 01:36:47 +01:00
DarkLiKally 5f12d99e73 Added water flow flag 2011-02-24 23:14:26 +01:00
Valentin Churavy 933987ac0a /tpr <id> spawn does now need the permissions /tpregion.spawn and also
added /region flag <id> spawn delete
2011-02-24 23:04:50 +01:00
Valentin Churavy 3a10a0969a add /tpr <region id> spawn 2011-02-24 22:53:20 +01:00
Valentin Churavy ba4907e67b add region.contains(location) for /region flag <id> spawn set 2011-02-24 22:29:49 +01:00
Valentin Churavy 99b37147d3 added /tpregion <region id> and /region flag <regionid> teleport
<set|delete>
2011-02-24 22:17:55 +01:00
Valentin Churavy 92a03ab7d6 added /region flag teleport 2011-02-24 21:35:45 +01:00
Redecouverte 68a0c67769 fixed for latest changes 2011-02-24 21:18:08 +01:00
Redecouverte 17e9105b9c commands now handled by commandhandler, updated /region info and /region flag for extended flag data 2011-02-24 21:15:05 +01:00
Redecouverte 5411a294e7 implemented heal, greeting and farewell flag 2011-02-24 21:14:42 +01:00
Redecouverte f821e277de geter with default values for extended AreFlags data 2011-02-24 21:11:31 +01:00
Valentin Churavy 18c2164049 added basic support of region teleport in ProtectedRegion 2011-02-24 20:29:47 +01:00
DarkLiKally c9688a9c58 Fixed an issue with the mob spawn control flags 2011-02-24 17:56:36 +01:00
Valentin Churavy cd599849b2 55: Improved corner handling (Corners are now always inside a
PolygonalRegion)
2011-02-24 17:32:06 +01:00
DarkLiKally 423f0199d0 Updated mob spawn control flags 2011-02-24 16:36:47 +01:00
DarkLiKally 40299eeea4 Changed Logger back to private (I changed it to public for some test reasons) 2011-02-24 16:20:52 +01:00
DarkLiKally 38077275bc Added mob spawn control Flags and global settings 2011-02-24 16:11:44 +01:00
Redecouverte 23aa6dc743 getAreaFlag now respects region priority 2011-02-24 14:52:22 +01:00
Redecouverte b90fb6a2b0 polygonal regions are now recognized by /region command, added extended AreaFlags data functions to ApplicableRegionSet, fixed isFlagAllowed in ApplicableRegionSet can only be executed once problem, updated region managers to not just forward all regions to ApplicableRegionSet 2011-02-24 14:24:23 +01:00
Redecouverte 17c8ed9ebc fixed typo in getRegionManager 2011-02-24 12:42:20 +01:00
Redecouverte a091a32c26 updated imports and comments 2011-02-24 12:14:26 +01:00
Redecouverte 23970a4e36 extended AreaFlags data storage, fixed typo on renaming old regions.txt 2011-02-24 12:06:27 +01:00
Redecouverte f61a9ab5cc added multiworld support for regions and json region database 2011-02-24 11:19:35 +01:00
Redecouverte 4505bb6f4e now including json-simple via build.xml 2011-02-23 20:51:19 +01:00
sk89q bb836aea57 Updated for 4.0-alpha1. 2011-02-23 11:25:10 -08:00
sk89q d584fba31c Updated block damage event handling to work around issues. 2011-02-23 11:07:39 -08:00
Redecouverte feacf3af7b removed CraftBukkit dependency 2011-02-23 19:13:56 +01:00
Redecouverte 8c428bb399 added JSON.simple 1.1 lib 2011-02-23 19:13:55 +01:00
sk89q 8edb6976fb Changed usage of CraftItemStack to ItemStack. 2011-02-23 10:05:29 -08:00
DarkLiKally edd2f460a0 Updated reflowing of water on sponge removal/deactivation 2011-02-22 20:56:57 +01:00
DarkLiKally 8810647bb8 Added reflowing of water on sponge removal/deactivation and
Updated water clearing on sponge creation/activation
2011-02-22 20:44:16 +01:00
DarkLiKally 2204bd67a7 Fixed the water damage block Bug 2011-02-22 17:27:58 +01:00
DarkLiKally c9c747693d Added ability to change default values of region's flags in config.yml for: FLAG_LIGHTER, FLAG_TNT, FLAG_CREEPER_EXPLOSION, FLAG_MOB_DAMAGE 2011-02-22 15:06:25 +01:00
Redecouverte 135d92303d more fixed for cake protection, protected cake now is semi-proteced, only the first slice is not protected 2011-02-22 15:02:57 +01:00
Redecouverte c707434155 fixed cake protection in regions 2011-02-22 14:26:01 +01:00
Valentin Churavy 4b72805a69 55: ProtectedPolygonalRegion should now handle edges better. 2011-02-22 13:58:05 +01:00
Redecouverte d5a9b0c65f really fixed setUpCourtyardRegion().. 2011-02-22 13:33:30 +01:00
Redecouverte 2015604fe2 fixed ProtectedPolygonalRegion construction in setUpCourtyardRegion 2011-02-22 13:33:01 +01:00
Redecouverte 96a290b153 added ItemAcquireBlacklistEvent for onPlayerPickupItem, not implemented in craftbukkit. yet 2011-02-22 13:22:06 +01:00
Redecouverte 912fcfe88a added tests to netbeans project 2011-02-22 13:18:27 +01:00
Redecouverte 4dcf7489fa added NetBeans project files 2011-02-22 13:03:06 +01:00
Redecouverte 7f1552dff8 updated onPlayerDropItem for latest bukkit, updated WorldEdit API calls for latest WorldEdit 2011-02-22 12:04:44 +01:00
Redecouverte d2ca8bffc4 we are now ignoring canceled events 2011-02-22 02:49:20 +01:00
Redecouverte e15b01bac5 added blacklist on-drop event 2011-02-22 02:48:57 +01:00
Redecouverte dcd3cb80b8 switched to parameterless constructor (i guess this is that the bukkit devs intended with their fancy warning) 2011-02-22 02:15:06 +01:00
Redecouverte d0ddc7c271 - added .gitignore to ignore eclipse/etc build files
- events are now registered in onEnable()
2011-02-22 02:03:20 +01:00
DarkLiKally 2b55f3407c Fixed the skeleton damage bug in protected areas 2011-02-22 01:01:31 +01:00
DarkLiKally e84afb4808 Fixed the Skeleton damage bug in protected regions 2011-02-22 01:01:31 +01:00
Redecouverte 10c47eff7e fixed entity damage events for latest bukkit 2011-02-21 23:30:20 +01:00
sk89q aee81f918e Added polygonal regions. They don't save/load yet, nor can you make them in-game yet. They were tested to work a week ago though. 2011-02-20 12:10:42 -08:00
sk89q 95b2d9419f Fixed redstone listener for newer versions of Bukkit. 2011-02-12 19:14:14 -08:00
sk89q feb9ce6633 Re-added priority tree region manager implementation. Add and removal operations are not yet optimized. 2011-02-12 16:09:21 -08:00
sk89q 43489ca087 Changed how ApplicableRegionSet iterated over the region set, allowing it to be reused. 2011-02-12 15:49:55 -08:00
sk89q ce1a15e6ea Improved tick sync message suppression. 2011-02-05 14:00:06 -08:00
sk89q cc72d370ea Added suppress-tick-sync-warnings option. 2011-02-05 13:45:05 -08:00
sk89q d042185660 Added WorldGuardPlugin.canBuild(player, x, y, z) 2011-02-04 20:51:14 -08:00
sk89q e78b639018 Updated CHANGELOG.txt. 2011-02-02 23:37:40 -08:00
sk89q e8ea562b09 Changed 'release' target to also 'clean'. 2011-02-02 23:28:48 -08:00
sk89q 3b5a729ef3 Updated command handling for Bukkit. 2011-02-02 22:27:44 -08:00
sk89q ef7d487ec5 Updated burn event handling. 2011-02-02 22:21:44 -08:00
sk89q b379b8f022 Fixed suffocation disable option. 2011-02-02 21:03:33 -08:00
sk89q a31378c2c8 Changed disable-water-damage to disable-drowning-damage. 2011-02-02 20:51:52 -08:00
sk89q 0d2c2121bb 3.2.1 CHANGELOG.txt. 2011-01-31 14:36:33 -08:00
sk89q 21040b306a Updated for ItemStack change in Bukkit. 2011-01-31 14:35:46 -08:00
86 changed files with 9540 additions and 2988 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
/bin
/build
/dist
/release
/store
/test
/lib/Bukkit.jar
/lib/Craftbukkit.jar
/lib/truezip.jar
/lib/WorldEdit.jar
/nbproject/private
.classpath
.project
manifest.mf
/oldcmds
.settings
*.bat
+13
View File
@@ -1,3 +1,16 @@
4.0-alpha1:
- This release is only to fix WorldGuard for Bukkit. Ignore the 4.0
label. Just move along. Nothing to see.
3.2.2:
- Changed disable-water-damage to disable-drowning-damage.
- Fixed suffocation disable option.
- Fixed fire spread blocking.
- stopfire and allowfire now work in server console, just like in hMod.
3.2.1:
- Updated for recent Bukkit ItemStack change.
3.2:
- Added regions.default.pvp to control default PvP setting.
- Updated WorldGuard for the newer builds of Bukkit.
+39 -1
View File
@@ -1,3 +1,7 @@
----------------------------------------------------------------------------
WorldGuard License
----------------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
@@ -162,4 +166,38 @@ General Public License ever published by the Free Software Foundation.
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
Library.
----------------------------------------------------------------------------
PRTree License
----------------------------------------------------------------------------
Copyright (c) 2008-2010 Robert Olofsson.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
+2 -1
View File
@@ -37,7 +37,8 @@
# - on-acquire (an item enters a player's inventory via some method)
#
# Actions (for events):
# - deny (deny completely)
# - deny (deny completely, used blacklist mode)
# - allow (used in whitelist mode)
# - notify (notify admins)
# - log (log to console/file/database)
# - tell (tell a player that that's not allowed)
+4 -1
View File
@@ -6,6 +6,7 @@
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,
@@ -18,4 +19,6 @@ CREATE TABLE `blacklist_events` (
-- 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 `comment` VARCHAR( 255 ) NULL
ALTER TABLE `blacklist_events` ADD `world` VARCHAR( 32 ) NOT NULL
+11 -3
View File
@@ -10,7 +10,12 @@
<property name="docs.dir" location="docs"/>
<fileset id="libs" dir="${lib.dir}">
<include name="*.jar"/>
<include name="truezip.jar" />
<include name="Bukkit.jar" />
<include name="WorldEdit.jar" />
<include name="iConomy.jar" />
<include name="prtree.jar" />
<include name="snakeyaml.jar" />
</fileset>
<target name="init">
@@ -40,8 +45,11 @@
<replace file="${build.dir}/plugin.yml" token="WGVERSIONMACRO" value="${version}"/>
<mkdir dir="${build.dir}/defaults"/>
<copy tofile="${build.dir}/defaults/config.yml" file="config.yml"/>
<copy tofile="${build.dir}/defaults/config_world.yml" file="config_world.yml"/>
<copy tofile="${build.dir}/defaults/blacklist.txt" file="blacklist.txt"/>
<jar jarfile="${dist.dir}/WorldGuard.jar" basedir="${build.dir}" manifest="manifest.mf"/>
<jar jarfile="${dist.dir}/WorldGuard.jar" basedir="${build.dir}" manifest="manifest.mf">
<zipgroupfileset dir="lib" includes="prtree.jar" />
</jar>
</target>
<!-- Create the .jar -->
@@ -51,7 +59,7 @@
</target>
<!-- Build a release -->
<target name="release">
<target name="release" depends="clean">
<input message="Enter version:" addproperty="version"/>
<antcall target="jar"/>
<delete dir="${release.dir}"/>
+3 -74
View File
@@ -19,81 +19,10 @@
# if any features are currently broken in your version of Bukkit.
#
summary-on-start: on
protection:
enforce-single-session: on
item-durability: on
simulation:
sponge:
enable: on
redstone: off
radius: 3
physics:
no-physics-gravel: off
no-physics-sand: off
allow-portal-anywhere: off
disable-water-damage-blocks: []
ignition:
block-tnt: off
block-lighter: off
fire:
disable-all-fire-spread: off
disable-fire-spread-blocks: []
disable-lava-fire-spread: on
lava-spread-blocks: []
mobs:
block-creeper-explosions: off
block-creeper-block-damage: off
spawn:
login-protection: 3
spawn-protection: 0
kick-on-death: off
exact-respawn: off
teleport-to-home-on-death: off
player-damage:
disable-fall-damage: off
disable-lava-damage: off
disable-fire-damage: off
disable-drowning-damage: off
disable-suffocation-damage: off
disable-contact-damage: off
teleport-on-suffocation: off
regions:
enable: on
wand: 287
default:
build: true
chest-access: false
pvp: true
blacklist:
logging:
console:
enable: on
database:
enable: off
dsn: jdbc:mysql://localhost:3306/minecraft
user: root
password: pass
table: blacklist_events
file:
enable: on
path: worldguard/logs/%Y-%m-%d.log
open-files: 10
# See http://wiki.sk89q.com/wiki/WorldGuard/Permissions/Bukkit
# For permissions, see http://wiki.sk89q.com/wiki/WorldGuard/Permissions/Bukkit
permissions:
users:
sk89q:
permissions:
- /region
- /reloadwg
- worldguard.region.*
- worldgurad.god
+99
View File
@@ -0,0 +1,99 @@
#
# WorldGuard's configuration file.
#
# This is the a per-world configuration file. It only affects one
# corresponding world.
#
# About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
# you use an editor like Notepad++ (recommended for Windows users), you
# must configure it to "replace tabs with spaces." In Notepad++, this can
# be changed in Settings > Preferences > Language Menu.
# - Don't get rid of the indents. They are indented so some entries are
# in categories (like "enforce-single-session" is in the "protection"
# category.
# - If you want to check the format of this file before putting it
# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:".
# - Lines starting with # are comments and so they are ignored.
#
summary-on-start: on
pumpkin-scuba: off
protection:
item-durability: on
simulation:
sponge:
enable: on
redstone: off
radius: 3
physics:
no-physics-gravel: off
no-physics-sand: off
allow-portal-anywhere: off
disable-water-damage-blocks: []
ignition:
block-tnt: off
block-lighter: off
fire:
disable-all-fire-spread: off
disable-fire-spread-blocks: []
disable-lava-fire-spread: on
lava-spread-blocks: []
mobs:
block-creeper-explosions: off
block-creeper-block-damage: off
block-creature-spawn: []
anti-wolf-dumbness: false
spawn:
login-protection: 3
spawn-protection: 0
kick-on-death: off
exact-respawn: off
teleport-to-home-on-death: off
player-damage:
disable-fall-damage: off
disable-lava-damage: off
disable-fire-damage: off
disable-drowning-damage: off
disable-suffocation-damage: off
disable-contact-damage: off
teleport-on-suffocation: off
regions:
enable: on
wand: 287
max-claim-volume: 30000
claim-only-inside-existing-regions: off
max-region-count-per-player: 7
high-frequency-flags: off
iconomy:
enable: on
buy-on-claim: on
# Price per block for buying on claim
buy-on-claim-price: 2
blacklist:
use-as-whitelist: off
logging:
console:
enable: on
database:
enable: off
dsn: jdbc:mysql://localhost:3306/minecraft
user: root
password: pass
table: blacklist_events
file:
enable: on
path: worldguard/logs/%w-%Y-%m-%d.log
open-files: 10
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+68
View File
@@ -0,0 +1,68 @@
worldguard.god.other
worldguard.god.self
worldguard.slay.other
worldguard.slay.self
worldguard.heal.other
worldguard.heal.self
worldguard.stack
worldguard.stopfire
worldguard.allowfire
worldguard.locate
worldguard.region.flag.ownregions
worldguard.region.flag.memberregions
worldguard.region.flag.foreignregions
worldguard.region.info.ownregions
worldguard.region.info.memberregions
worldguard.region.info.foreignregions
worldguard.region.list
worldguard.region.load
worldguard.region.addowner.own
worldguard.region.addowner.all
worldguard.region.addmember.own
worldguard.region.addmember.all
worldguard.region.removeowner.own
worldguard.region.removeowner.all
worldguard.region.removemember.own
worldguard.region.removemember.all
worldguard.region.save
worldguard.region.setparent.own
worldguard.region.setparent.all
worldguard.region.priority.own
worldguard.region.priority.all
worldguard.region.bypass
worldguard.reloadwg
worldguard.region.delete.own
worldguard.region.delete.all
worldguard.region.define
worldguard.region.claim
worldguard.tpregion
worldguard.tpregion.spawn
worldguard.tpregion.override
worldguard.buyregion
worldguard.notify
worldguard.notify_onenter
+12 -8
View File
@@ -9,25 +9,29 @@ commands:
description: Re-enables fire spread if he has been disabled with /stopfire
usage: /<command>
god:
description: Toggles god mode
usage: /<command> [other player]
description: Enable god mode
usage: /<command> [player]
ungod:
description: Disable god mode
usage: /<command> [player]
heal:
description: Heal yourself or another
usage: /<command> [other player]
usage: /<command> [player]
slay:
description: Slay yourself or another
usage: /<command> [other player]
usage: /<command> [player]
stack:
description: Stacks items in the player's inventory
usage: /<command>
aliases: ;
region:
description: Adjust protected regions
usage: /<command> <define|claim|setparent|flag|delete|info|addowner|removeowner|addmember|removemember|list|save|load> ...
aliases: rg, regions
usage: /<command> <action> ...
aliases: [rg, regions]
locate:
description: Set your compass towards a person
usage: /<command> <target>
reloadwg:
description: Reload WorldGuard's configuration
worldguard:
description: WorldGuard commands
aliases: wg
usage: /<command>
@@ -72,6 +72,14 @@ public abstract class LocalPlayer {
*/
public abstract String[] getGroups();
/**
* Returns whether a player has permission.
*
* @param perm
* @return
*/
public abstract boolean hasPermission(String perm);
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LocalPlayer)) {
@@ -0,0 +1,35 @@
// $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;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class TickSyncDelayLoggerFilter implements Filter {
public boolean isLoggable(LogRecord record) {
if (record.getLevel() == Level.WARNING
&& record.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) {
return false;
}
return true;
}
}
@@ -60,6 +60,14 @@ public abstract class Blacklist {
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
private boolean useAsWhitelist;
public Blacklist(Boolean useAsWhitelist)
{
this.useAsWhitelist = useAsWhitelist;
}
/**
* Returns whether the list is empty.
*
@@ -71,11 +79,32 @@ public abstract class Blacklist {
/**
* Get the entries for an item or list.
*
* @param id
* @return
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
}
/**
* Get the number of individual items that have blacklist entries.
*
* @return
*/
public int getItemCount() {
return blacklist.size();
}
/**
* Returns whether the blacklist is used as a whitelist.
*
* @return
*/
public boolean isWhitelist() {
return useAsWhitelist;
}
/**
* Get the logger.
*
@@ -100,7 +129,7 @@ public abstract class Blacklist {
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.check(event, forceRepeat, silent)) {
if (!entry.check(useAsWhitelist, event, forceRepeat, silent)) {
ret = false;
}
}
@@ -111,7 +140,6 @@ public abstract class Blacklist {
* Load the blacklist.
*
* @param file
* @return
* @throws IOException
*/
public void load(File file) throws IOException {
@@ -234,6 +262,7 @@ public abstract class Blacklist {
* Notify administrators.
*
* @param event
* @param comment
*/
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
@@ -264,8 +293,6 @@ public abstract class Blacklist {
/**
* Forget all players.
*
* @param player
*/
public void forgetAllPlayers() {
lastAffected.clear();
@@ -107,7 +107,7 @@ public class BlacklistEntry {
}
/**
* @param action
* @param actions
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
@@ -266,12 +266,13 @@ public class BlacklistEntry {
/**
* Method to handle the event.
*
* @param useAsWhitelist
* @param event
* @param forceRepeat
* @param silent
* @return
*/
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
public boolean check(boolean useAsWhitelist, BlacklistEvent event, boolean forceRepeat, boolean silent) {
LocalPlayer player = event.getPlayer();
if (shouldIgnore(player)) {
@@ -293,11 +294,13 @@ public class BlacklistEntry {
}
String actions[] = getActions(event);
boolean ret = true;
boolean ret = useAsWhitelist ? false : true;
// Nothing to do
if (actions == null) {
return true;
return useAsWhitelist ? false : true;
}
for (String action : actions) {
@@ -309,6 +312,14 @@ public class BlacklistEntry {
ret = false;
// Allow
} else if (action.equalsIgnoreCase("allow")) {
if (silent) {
return true;
}
ret = true;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (silent) {
@@ -55,8 +55,6 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Add a handler.
*
* @param handler
*/
public void clearHandlers() {
handlers.clear();
@@ -65,7 +63,6 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param player
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
@@ -32,7 +32,7 @@ public class BlacklistTrackedEvent {
/**
* Construct the object.
*
* @param id
* @param event
* @param time
*/
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
@@ -32,6 +32,7 @@ public class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "break";
}
@@ -32,6 +32,7 @@ public class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "interact with";
}
@@ -32,6 +32,7 @@ public class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "place";
}
@@ -32,6 +32,7 @@ public class DestroyWithBlacklistEvent extends BlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "destroy with";
}
@@ -32,6 +32,7 @@ public class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "acquire";
}
@@ -32,6 +32,7 @@ public class ItemDropBlacklistEvent extends ItemBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "drop";
}
@@ -32,6 +32,7 @@ public class ItemUseBlacklistEvent extends ItemBlacklistEvent {
*
* @return
*/
@Override
public String getDescription() {
return "use";
}
@@ -34,65 +34,72 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private String worldName;
public ConsoleLoggerHandler(String worldName)
{
this.worldName = worldName;
}
/**
* Log an event.
*
* @param player
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
@@ -61,6 +61,10 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
* Table.
*/
private String table;
/**
* World name.
*/
private String worldName;
/**
* Database connection.
*/
@@ -72,12 +76,15 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
* @param dsn
* @param user
* @param pass
* @param table
* @param worldName
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table) {
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
}
/**
@@ -110,16 +117,17 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?)");
+ "(event, world, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
stmt.setString(2, player.getName());
stmt.setInt(3, pos.getBlockX());
stmt.setInt(4, pos.getBlockY());
stmt.setInt(5, pos.getBlockZ());
stmt.setInt(6, item);
stmt.setInt(7, (int)(System.currentTimeMillis() / 1000));
stmt.setString(8, comment);
stmt.setString(2, worldName);
stmt.setString(3, player.getName());
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setInt(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
@@ -130,7 +138,6 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param player
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
@@ -57,6 +57,10 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* Path pattern.
*/
private String pathPattern;
/**
* World name.
*/
private String worldName;
/**
* Cache of writers.
*/
@@ -67,9 +71,11 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* Construct the object.
*
* @param pathPattern
* @param worldName
*/
public FileLoggerHandler(String pathPattern) {
public FileLoggerHandler(String pathPattern, String worldName) {
this.pathPattern = pathPattern;
this.worldName = worldName;
}
/**
@@ -77,13 +83,15 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
*
* @param pathPattern
* @param cacheSize
* @param worldName
*/
public FileLoggerHandler(String pathPattern, int cacheSize) {
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
this.pathPattern = pathPattern;
this.cacheSize = cacheSize;
this.worldName = worldName;
}
/**
@@ -110,6 +118,12 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
rep = rep.substring(0, 32);
}
}else if (group.matches("%w")) {
rep = worldName.toLowerCase().replaceAll("[^A-Za-z0-9_]", "_");
if (rep.length() > 32) { // Actual max length is 16
rep = rep.substring(0, 32);
}
// Date and time
} else if (group.matches("%Y")) {
rep = String.valueOf(calendar.get(Calendar.YEAR));
@@ -224,7 +238,6 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param player
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
@@ -42,6 +42,7 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Construct the object.
*
* @param path
* @param writer
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
@@ -75,8 +76,6 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Update last use time.
*
* @return
*/
public void updateLastUse() {
lastUse = System.currentTimeMillis();
@@ -25,13 +25,15 @@ import com.sk89q.worldguard.blacklist.Blacklist;
public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(WorldGuardPlugin plugin) {
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist);
this.plugin = plugin;
}
@Override
public void broadcastNotification(String msg) {
for (Player player : plugin.getServer().getOnlinePlayers()) {
if (plugin.hasPermission(player, "/worldguardnotify")) {
if (plugin.hasPermission(player, "worldguard.notify")) {
player.sendMessage(msg);
}
}
@@ -69,4 +69,9 @@ public class BukkitPlayer extends LocalPlayer {
player.sendMessage(msg);
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
}
@@ -24,10 +24,13 @@ import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
public class BukkitUtil {
private BukkitUtil() {
}
@@ -50,4 +53,9 @@ public class BukkitUtil {
}
return players.get(0);
}
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
}
@@ -0,0 +1,193 @@
// $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 com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class ConfigurationManager {
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Holds configurations for different worlds.
*/
private Map<String, WorldConfiguration> worlds;
/**
* List of people with god mode.
*/
private Set<String> hasGodMode = new HashSet<String>();
/**
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
public boolean suppressTickSyncWarnings;
/**
* Construct the object.
*
* @param plugin
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.worlds = new HashMap<String, WorldConfiguration>();
}
/**
* Load the configuration.
*/
public void load() {
// Create the default configuration file
WorldGuardPlugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
Configuration config = plugin.getConfiguration();
config.load();
suppressTickSyncWarnings = config.getBoolean(
"suppress-tick-sync-warnings", false);
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
}
/**
* Unload the configuration.
*/
public void unload() {
worlds.clear();
}
/**
* Get the configuration for a world.
*
* @param world
* @return
*/
public WorldConfiguration get(World world) {
String worldName = world.getName();
WorldConfiguration config = worlds.get(worldName);
if (config == null) {
config = new WorldConfiguration(plugin, worldName);
worlds.put(worldName, config);
}
return config;
}
/**
* Forget a player.
*
* @param player
*/
public void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
// The blacklist needs to forget players
Blacklist bl = entry.getValue().getBlacklist();
if (bl != null) {
bl.forgetPlayer(player);
}
}
hasGodMode.remove(player.getName());
hasAmphibious.remove(player.getName());
}
/**
* Enable god mode for a player.
*
* @param player
*/
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
/**
* Disable god mode for a player.
*
* @param player
*/
public void disableGodMode(Player player) {
hasGodMode.remove(player.getName());
}
/**
* Check to see if god mode is enabled for a player.
*
* @param player
* @return
*/
public boolean hasGodMode(Player player) {
return hasGodMode.contains(player.getName());
}
/**
* Enable amphibious mode for a player.
*
* @param player
*/
public void enableAmphibiousMode(Player player) {
hasAmphibious.add(player.getName());
}
/**
* Disable amphibious mode for a player.
*
* @param player
*/
public void disableAmphibiousMode(Player player) {
hasAmphibious.remove(player.getName());
}
/**
* Check to see if amphibious mode is enabled for a player.
*
* @param player
* @return
*/
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
}
}
@@ -0,0 +1,152 @@
// $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 java.io.*;
import java.util.logging.Logger;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.CSVDatabase;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Utility methods for porting from legacy versions.
*
* @author sk89q
*/
public class LegacyWorldGuardMigration {
/**
* Logger for messages.
*/
protected static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Port over the blacklist.
*
* @param plugin
*/
public static void migrateBlacklist(WorldGuardPlugin plugin) {
World mainWorld = plugin.getServer().getWorlds().get(0);
String mainWorldName = mainWorld.getName();
String newPath = "worlds/" + mainWorldName + "/blacklist.txt";
File oldFile = new File(plugin.getDataFolder(), "blacklist.txt");
File newFile = new File(plugin.getDataFolder(), newPath);
if (!newFile.exists() && oldFile.exists()) {
logger.warning("WorldGuard: WorldGuard will now update your blacklist "
+ "from an older version of WorldGuard.");
// Need to make root directories
newFile.getParentFile().mkdirs();
if (copyFile(oldFile, newFile)) {
oldFile.renameTo(new File(plugin.getDataFolder(),
"blacklist.txt.old"));
} else {
logger.warning("WorldGuard: blacklist.txt has been converted " +
"for the main world at " + newPath + "");
logger.warning("WorldGuard: Your other worlds currently have no " +
"blacklist defined!");
}
}
}
/**
* Migrate region settings.
*
* @param plugin
*/
public static void migrateRegions(WorldGuardPlugin plugin) {
try {
File oldDatabase = new File(plugin.getDataFolder(), "regions.txt");
if (!oldDatabase.exists()) return;
logger.info("WorldGuard: The regions database has changed in 4.x. "
+ "Your old regions database will be converted to the new format "
+ "and set as your primarily world's database.");
World w = plugin.getServer().getWorlds().get(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
// First load up the old database using the CSV loader
CSVDatabase db = new CSVDatabase(oldDatabase);
db.load();
// Then save the new database
mgr.setRegions(db.getRegions());
mgr.save();
oldDatabase.renameTo(new File(plugin.getDataFolder(), "regions.txt.old"));
logger.info("WorldGuard: Regions database converted!");
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions: "
+ e.getMessage());
}
}
/**
* Copies a file.
*
* @param from
* @param to
* @return true if successful
*/
private static boolean copyFile(File from, File to) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (FileNotFoundException ex) {
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return false;
}
}
@@ -22,7 +22,7 @@ package com.sk89q.worldguard.bukkit;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.command.CommandSender;
/**
* Sends all logger messages to a player.
@@ -33,32 +33,35 @@ public class LoggerToChatHandler extends Handler {
/**
* Player.
*/
private Player player;
private CommandSender player;
/**
* Construct the object.
*
* @param player
*/
public LoggerToChatHandler(Player player) {
public LoggerToChatHandler(CommandSender player) {
this.player = player;
}
/**
* Close the handler.
*/
@Override
public void close() {
}
/**
* Flush the output.
*/
@Override
public void flush() {
}
/**
* Publish a log record.
*/
@Override
public void publish(LogRecord record) {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.WHITE + record.getMessage());
@@ -0,0 +1,287 @@
// $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 java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class ReportWriter {
private static final SimpleDateFormat dateFmt =
new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
private WorldGuardPlugin plugin;
private Date date = new Date();
private StringBuilder output = new StringBuilder();
public ReportWriter(WorldGuardPlugin plugin) {
this.plugin = plugin;
appendHeader(plugin);
appendServerInformation(plugin.getServer());
appendPluginInformation(plugin.getServer().getPluginManager().getPlugins());
appendWorldInformation(plugin.getServer().getWorlds());
appendGlobalConfiguration(plugin.getGlobalConfiguration());
appendWorldConfigurations(plugin, plugin.getServer().getWorlds(),
plugin.getGlobalRegionManager(), plugin.getGlobalConfiguration());
appendRule();
appendln("END OF REPORT");
appendln();
}
private void appendln(String text) {
output.append(text);
output.append("\r\n");
}
private void appendln(String text, Object ... args) {
output.append(String.format(text, args));
output.append("\r\n");
}
private void appendln() {
output.append("\r\n");
}
private void appendRule() {
output.append("--------------------------------------------------\r\n");
}
private void appendHeader(WorldGuardPlugin plugin) {
appendln("WorldGuard Configuration Report");
appendln("Generated " + dateFmt.format(date));
appendln();
appendln("Version: " + plugin.getDescription().getVersion());
appendln();
}
private void appendGlobalConfiguration(ConfigurationManager config) {
appendRule();
appendln("GLOBAL CONFIGURATION:");
appendRule();
appendln();
Class<? extends ConfigurationManager> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
appendln("%-30s: %s", field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
}
}
appendln();
}
private void appendServerInformation(Server server) {
appendRule();
appendln("SERVER:");
appendRule();
appendln();
appendln("%-15s: %s", "Server ID", server.getServerId());
appendln("%-15s: %s", "Server name", server.getServerName());
appendln("%-15s: %s", "Implementation", server.getVersion());
//appendln("%-15s: %s:%d", "Address", server.getIp(), server.getPort());
appendln("%-15s: %d/%d", "Player count",
server.getOnlinePlayers().length, server.getMaxPlayers());
appendln();
}
private void appendPluginInformation(Plugin[] plugins) {
appendRule();
appendln("PLUGINS (%d)", plugins.length);
appendRule();
appendln();
for (Plugin plugin : plugins) {
appendln("%s %s <%s>:", plugin.getDescription().getName(),
plugin.getDescription().getVersion(),
plugin.getDescription().getWebsite());
appendln(" %-15s: %s", "Entry point", plugin.getDescription().getMain());
appendln(" %-15s: %s", "Data folder", plugin.getDataFolder().getAbsoluteFile());
}
appendln();
}
private void appendWorldInformation(List<World> worlds) {
appendRule();
appendln("WORLDS (%d)", worlds.size());
appendRule();
appendln();
int i = 0;
for (World world : worlds) {
int loadedChunkCount = world.getLoadedChunks().length;
appendln("%d. %s:", i, world.getName());
appendln(" Information:");
appendln(" %-15s: %s", "ID", world.getId());
appendln(" %-15s: %s", "Environment", world.getEnvironment().toString());
appendln(" %-15s: %d", "Player #", world.getPlayers().size());
appendln(" %-15s: %d", "Entity #", world.getEntities().size());
appendln(" %-15s: %d", "Loaded chunk #", loadedChunkCount);
appendln(" Entities:");
Map<Class<? extends Entity>, Integer> entityCounts =
new HashMap<Class<? extends Entity>, Integer>();
// Collect entities
for (Entity entity : world.getEntities()) {
Class<? extends Entity> cls = entity.getClass();
if (entityCounts.containsKey(cls)) {
entityCounts.put(cls, entityCounts.get(cls) + 1);
} else {
entityCounts.put(cls, 1);
}
}
// Print entities
for (Map.Entry<Class<? extends Entity>, Integer> entry
: entityCounts.entrySet()) {
appendln(" %-25s: %d [%f]", entry.getKey().getSimpleName(),
entry.getValue(), (float) (entry.getValue() / (double) loadedChunkCount));
}
i++;
}
appendln();
}
private void appendWorldConfigurations(WorldGuardPlugin plugin, List<World> worlds,
GlobalRegionManager regionMgr, ConfigurationManager mgr) {
appendRule();
appendln("WORLD CONFIGURATIONS");
appendRule();
appendln();
int i = 0;
for (World world : worlds) {
appendln("%d. %s:", i, world.getName());
WorldConfiguration config = mgr.get(world);
appendln(" Configuration:");
appendln(" %-30s: %s", "File",
(new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/config.yml")).getAbsoluteFile());
Class<? extends WorldConfiguration> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
appendln(" %-30s: %s", field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
}
}
appendln(" Blacklist:");
appendln(" %-15s: %s", "File",
(new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/blacklist.txt")).getAbsoluteFile());
if (config.getBlacklist() == null) {
appendln(" DISABLED / NO ENTRIES");
} else {
appendln(" %-15s: %s", "Number of items",
config.getBlacklist().getItemCount());
appendln(" %-15s: %s", "Is whitelist",
config.getBlacklist().isWhitelist() ? "YES" : "NO");
}
appendln(" Region manager:");
appendln(" %-15s: %s", "File",
(new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/regions.yml")).getAbsoluteFile());
RegionManager worldRegions = regionMgr.get(world);
appendln(" %-15s: %s", "Type",
worldRegions.getClass().getCanonicalName());
appendln(" %-15s: %s", "Number of regions",
worldRegions.getRegions().size());
appendln(" Global region:");
ProtectedRegion globalRegion = worldRegions.getRegion("__global__");
if (globalRegion == null) {
appendln(" UNDEFINED");
} else {
appendln(" %-20s: %s", "Type",
globalRegion.getClass().getCanonicalName());
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (flag instanceof StateFlag) {
appendln(" %-20s: %s", flag.getName(),
globalRegion.getFlag(flag));
}
}
}
}
appendln();
}
public void write(File file) throws IOException {
FileWriter writer = null;
BufferedWriter out;
try {
writer = new FileWriter(file);
out = new BufferedWriter(writer);
out.write(output.toString());
out.close();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
@Override
public String toString() {
return output.toString();
}
}
@@ -0,0 +1,292 @@
// $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 com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
import com.sk89q.worldguard.blacklist.loggers.ConsoleLoggerHandler;
import com.sk89q.worldguard.blacklist.loggers.DatabaseLoggerHandler;
import com.sk89q.worldguard.blacklist.loggers.FileLoggerHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.CreatureType;
import org.bukkit.util.config.Configuration;
/**
* Holds the configuration for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class WorldConfiguration {
private static final Logger logger = Logger
.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
private String worldName;
private File configFile;
private File blacklistFile;
private Blacklist blacklist;
/* Configuration data start */
public boolean fireSpreadDisableToggle;
public boolean enforceOneSession;
public boolean itemDurability;
public boolean classicWater;
public boolean simulateSponge;
public int spongeRadius;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockTNT;
public boolean blockLighter;
public boolean disableFireSpread;
public Set<Integer> disableFireSpreadBlocks;
public boolean preventLavaFire;
public Set<Integer> allowedLavaSpreadOver;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public int loginProtection;
public int spawnProtection;
public boolean kickOnDeath;
public boolean exactRespawn;
public boolean teleportToHome;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
public boolean disableFireDamage;
public boolean disableDrowningDamage;
public boolean disableSuffocationDamage;
public boolean teleportOnSuffocation;
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand = 287;
public Set<CreatureType> blockCreatureSpawn;
public boolean useiConomy;
public boolean buyOnClaim;
public double buyOnClaimPrice;
public int maxClaimVolume;
public boolean claimOnlyInsideExistingRegions;
public int maxRegionCountPerPlayer;
public boolean antiWolfDumbness;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin
* @param worldName
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
this.plugin = plugin;
this.worldName = worldName;
WorldGuardPlugin.createDefaultConfiguration(configFile, "config_world.yml");
WorldGuardPlugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
loadConfiguration();
logger.info("WorldGuard: Loaded configuration for world '" + worldName + '"');
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
Configuration config = new Configuration(this.configFile);
config.load();
enforceOneSession = config.getBoolean("protection.enforce-single-session", true);
itemDurability = config.getBoolean("protection.item-durability", true);
classicWater = config.getBoolean("simulation.classic-water", false);
simulateSponge = config.getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = config.getBoolean("simulation.sponge.redstone", false);
pumpkinScuba = config.getBoolean("pumpkin-scuba", false);
noPhysicsGravel = config.getBoolean("physics.no-physics-gravel", false);
noPhysicsSand = config.getBoolean("physics.no-physics-sand", false);
allowPortalAnywhere = config.getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(config.getIntList("physics.disable-water-damage-blocks", null));
blockTNT = config.getBoolean("ignition.block-tnt", false);
blockLighter = config.getBoolean("ignition.block-lighter", false);
preventLavaFire = config.getBoolean("fire.disable-lava-fire-spread", true);
disableFireSpread = config.getBoolean("fire.disable-all-fire-spread", false);
disableFireSpreadBlocks = new HashSet<Integer>(config.getIntList("fire.disable-fire-spread-blocks", null));
allowedLavaSpreadOver = new HashSet<Integer>(config.getIntList("fire.lava-spread-blocks", null));
blockCreeperExplosions = config.getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = config.getBoolean("mobs.block-creeper-block-damage", false);
antiWolfDumbness = config.getBoolean("mobs.anti-wolf-dumbness", false);
loginProtection = config.getInt("spawn.login-protection", 3);
spawnProtection = config.getInt("spawn.spawn-protection", 0);
kickOnDeath = config.getBoolean("spawn.kick-on-death", false);
exactRespawn = config.getBoolean("spawn.exact-respawn", false);
teleportToHome = config.getBoolean("spawn.teleport-to-home-on-death", false);
disableFallDamage = config.getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = config.getBoolean("player-damage.disable-lava-damage", false);
disableFireDamage = config.getBoolean("player-damage.disable-fire-damage", false);
disableDrowningDamage = config.getBoolean("player-damage.disable-drowning-damage", false);
disableSuffocationDamage = config.getBoolean("player-damage.disable-suffocation-damage", false);
disableContactDamage = config.getBoolean("player-damage.disable-contact-damage", false);
teleportOnSuffocation = config.getBoolean("player-damage.teleport-on-suffocation", false);
useRegions = config.getBoolean("regions.enable", true);
highFreqFlags = config.getBoolean("regions.high-frequency-flags", false);
regionWand = config.getInt("regions.wand", 287);
maxClaimVolume = config.getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = config.getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = config.getInt("regions.max-region-count-per-player", 7);
useiConomy = config.getBoolean("iconomy.enable", false);
buyOnClaim = config.getBoolean("iconomy.buy-on-claim", false);
buyOnClaimPrice = config.getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<CreatureType>();
for (String creatureName : config.getStringList("mobs.block-creature-spawn", null)) {
CreatureType creature = CreatureType.fromName(creatureName);
if (creature == null) {
logger.warning("WorldGuard: Unknown mob type '" + creatureName + "'");
} else {
blockCreatureSpawn.add(creature);
}
}
boolean useBlacklistAsWhitelist = config.getBoolean("blacklist.use-as-whitelist", false);
// Console log configuration
boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true);
// Database log configuration
boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false);
String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = config.getString("blacklist.logging.database.user", "root");
String pass = config.getString("blacklist.logging.database.pass", "");
String table = config.getString("blacklist.logging.database.table", "blacklist_events");
// File log configuration
boolean logFile = config.getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10));
// Load the blacklist
try {
// If there was an existing blacklist, close loggers
if (blacklist != null) {
blacklist.getLogger().close();
}
// First load the blacklist data from worldguard-blacklist.txt
Blacklist blist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
blist.load(blacklistFile);
// If the blacklist is empty, then set the field to null
// and save some resources
if (blist.isEmpty()) {
this.blacklist = null;
} else {
this.blacklist = blist;
logger.log(Level.INFO, "WorldGuard: Blacklist loaded.");
BlacklistLogger blacklistLogger = blist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName));
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName);
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "WorldGuard blacklist does not exist.");
} catch (IOException e) {
logger.log(Level.WARNING, "Could not load WorldGuard blacklist: "
+ e.getMessage());
}
// Print an overview of settings
if (config.getBoolean("summary-on-start", true)) {
logger.log(Level.INFO, enforceOneSession
? "WorldGuard: (" + worldName + ") Single session is enforced."
: "WorldGuard: (" + worldName + ") Single session is NOT ENFORCED.");
logger.log(Level.INFO, blockTNT
? "WorldGuard: (" + worldName + ") TNT ignition is blocked."
: "WorldGuard: (" + worldName + ") TNT ignition is PERMITTED.");
logger.log(Level.INFO, blockLighter
? "WorldGuard: (" + worldName + ") Lighters are blocked."
: "WorldGuard: (" + worldName + ") Lighters are PERMITTED.");
logger.log(Level.INFO, preventLavaFire
? "WorldGuard: (" + worldName + ") Lava fire is blocked."
: "WorldGuard: (" + worldName + ") Lava fire is PERMITTED.");
if (disableFireSpread) {
logger.log(Level.INFO, "WorldGuard: (" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
logger.log(Level.INFO, "WorldGuard: (" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
logger.log(Level.INFO, "WorldGuard: (" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
}
}
public Blacklist getBlacklist() {
return this.blacklist;
}
public String getWorldName() {
return this.worldName;
}
}
@@ -15,17 +15,16 @@
*
* 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 java.util.Iterator;
import java.util.List;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginManager;
import org.bukkit.block.Block;
import org.bukkit.block.BlockDamageLevel;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.World;
import org.bukkit.event.block.*;
@@ -35,15 +34,15 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
public class WorldGuardBlockListener extends BlockListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
@@ -53,48 +52,66 @@ public class WorldGuardBlockListener extends BlockListener {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_BREAK, this, Priority.High, plugin);
pm.registerEvent(Event.Type.BLOCK_FROMTO, this, Priority.Normal, plugin);
pm.registerEvent(Event.Type.BLOCK_IGNITE, this, Priority.High, plugin);
pm.registerEvent(Event.Type.BLOCK_PHYSICS, this, Priority.Normal, plugin);
pm.registerEvent(Event.Type.BLOCK_PLACE, this, Priority.High, plugin);
pm.registerEvent(Event.Type.BLOCK_BURN, this, Priority.High, plugin);
pm.registerEvent(Event.Type.REDSTONE_CHANGE, this, Priority.High, plugin);
}
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalConfiguration().get(world);
}
protected WorldConfiguration getWorldConfig(Player player) {
return plugin.getGlobalConfiguration().get(player.getWorld());
}
/**
* Called when a block is damaged (or broken)
*
* @param event Relevant event details
* Called when a block is broken.
*/
@Override
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
if (!plugin.itemDurability && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getTypeId() > 0) {
held.setDamage((byte)-1);
held.setDurability((short) -1);
player.setItemInHand(held);
}
}
if (plugin.useRegions && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Vector pt = BukkitUtil.toVector(event.getBlock());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (plugin.blacklist != null && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
if (!plugin.blacklist.check(
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
event.getBlock().getTypeId()), false, false)) {
toVector(event.getBlock()),
event.getBlock().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
if (!plugin.blacklist.check(
if (!wcfg.getBlacklist().check(
new DestroyWithBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
player.getItemInHand().getTypeId()), false, false)) {
toVector(event.getBlock()),
player.getItemInHand().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
@@ -102,30 +119,35 @@ public class WorldGuardBlockListener extends BlockListener {
}
/**
* Called when a block flows (water/lava)
*
* @param event Relevant event details
* Called when fluids flow.
*/
@Override
public void onBlockFlow(BlockFromToEvent event) {
public void onBlockFromTo(BlockFromToEvent event) {
if (event.isCancelled()) {
return;
}
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
if (plugin.simulateSponge && isWater) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -plugin.spongeRadius; cx <= plugin.spongeRadius; cx++) {
for (int cy = -plugin.spongeRadius; cy <= plugin.spongeRadius; cy++) {
for (int cz = -plugin.spongeRadius; cz <= plugin.spongeRadius; cz++) {
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& (!plugin.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
}
@@ -135,116 +157,174 @@ public class WorldGuardBlockListener extends BlockListener {
}
/*if (plugin.classicWater && isWater) {
int blockBelow = blockFrom.getRelative(0, -1, 0).getTypeId();
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
blockFrom.setTypeId(9);
if (blockTo.getTypeId() == 0) {
blockTo.setTypeId(9);
}
return;
}
int blockBelow = blockFrom.getRelative(0, -1, 0).getTypeId();
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
blockFrom.setTypeId(9);
if (blockTo.getTypeId() == 0) {
blockTo.setTypeId(9);
}
return;
}
}*/
if (plugin.preventWaterDamage.size() > 0 && isWater) {
int targetId = world.getBlockTypeIdAt(
blockTo.getX(), blockTo.getY(), blockTo.getZ());
if (plugin.preventWaterDamage.contains(targetId)) {
// Check the fluid block (from) whether it is air.
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
if ((blockFrom.getTypeId() == 0 || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (plugin.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = world.getBlockTypeIdAt(
blockTo.getX(), blockTo.getY() - 1, blockTo.getZ());
if (!plugin.allowedLavaSpreadOver.contains(targetId)) {
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.highFreqFlags && isWater
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.WATER_FLOW,
blockFrom.getLocation())) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && isLava
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.LAVA_FLOW,
blockFrom.getLocation())) {
event.setCancelled(true);
return;
}
}
/**
* Called when a block gets ignited
* Called when a block gets ignited.
*/
@Override
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
}
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.blockLighter && cause == IgniteCause.FLINT_AND_STEEL) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
Vector pt = toVector(block);
Player player = event.getPlayer();
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (player != null && !plugin.getGlobalRegionManager().hasBypass(player, world)) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (cause == IgniteCause.FLINT_AND_STEEL
&& !set.canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FLINT_AND_STEEL
&& !set.allows(DefaultFlag.LIGHTER)) {
event.setCancelled(true);
return;
}
}
if (wcfg.highFreqFlags && isFireSpread && set.allows(DefaultFlag.FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && cause == IgniteCause.LAVA
&& !set.allows(DefaultFlag.LAVA_FIRE)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a block is destroyed from burning
*
* @param event Relevant event details
*/
@Override
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
//Player player = event.getPlayer();
World world = block.getWorld();
boolean isFireSpread = cause == IgniteCause.SLOW_SPREAD
|| cause == IgniteCause.SPREAD;
if (plugin.preventLavaFire && cause == IgniteCause.LAVA) {
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
if (plugin.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (plugin.blockLighter && cause == IgniteCause.FLINT_AND_STEEL) {
if (wcfg.fireSpreadDisableToggle) {
event.setCancelled(true);
return;
}
if (plugin.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (plugin.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
return;
}
}
/*if (plugin.useRegions) {
Vector pt = toVector(block);
if (player != null && !plugin.hasPermission(player, "/regionbypass")) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (cause == IgniteCause.FLINT_AND_STEEL
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FLINT_AND_STEEL
&& !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LIGHTER)) {
event.setCancelled(true);
return;
}
}
f (isFireSpread && !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.LAVA && !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LAVA_FIRE)) {
event.setCancelled(true);
return;
}
}*/
}
/**
@@ -254,65 +334,31 @@ public class WorldGuardBlockListener extends BlockListener {
*/
@Override
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
int id = event.getChangedTypeId();
if (id == 13 && plugin.noPhysicsGravel) {
if (id == 13 && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && plugin.noPhysicsSand) {
if (id == 12 && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && plugin.allowPortalAnywhere) {
if (id == 90 && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
}
/**
* Called when a block is interacted with
*
* @param event Relevant event details
*/
public void onBlockInteract(BlockInteractEvent event) {
Block block = event.getBlock();
LivingEntity entity = event.getEntity();
if (entity instanceof Player
&& (block.getType() == Material.CHEST
|| block.getType() == Material.DISPENSER
|| block.getType() == Material.FURNACE
|| block.getType() == Material.BURNING_FURNACE
|| block.getType() == Material.NOTE_BLOCK)) {
Player player = (Player)entity;
if (plugin.useRegions) {
Vector pt = toVector(block);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).allowsFlag(AreaFlags.FLAG_CHEST_ACCESS)
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
if (plugin.blacklist != null && entity instanceof Player) {
Player player = (Player)entity;
if (!plugin.blacklist.check(
new BlockInteractBlacklistEvent(plugin.wrapPlayer(player), toVector(block),
block.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a player places a block
@@ -321,36 +367,40 @@ public class WorldGuardBlockListener extends BlockListener {
*/
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
if (plugin.useRegions) {
Vector pt = toVector(blockPlaced);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockPlaced.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (plugin.blacklist != null) {
if (!plugin.blacklist.check(
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(blockPlaced),
blockPlaced.getTypeId()), false, false)) {
blockPlaced.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (plugin.simulateSponge && blockPlaced.getTypeId() == 19) {
if (plugin.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
if (wcfg.simulateSponge && blockPlaced.getTypeId() == 19) {
if (wcfg.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
return;
}
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
@@ -359,40 +409,6 @@ public class WorldGuardBlockListener extends BlockListener {
}
}
/**
* Called when a player right clicks a block
*
* @param event Relevant event details
*/
@Override
public void onBlockRightClick(BlockRightClickEvent event) {
Player player = event.getPlayer();
if (plugin.useRegions && event.getItemInHand().getTypeId() == plugin.regionWand) {
Vector pt = toVector(event.getBlock());
ApplicableRegionSet app = plugin.regionManager.getApplicableRegions(pt);
List<String> regions = plugin.regionManager.getApplicableRegionsIDs(pt);
if (regions.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (app.canBuild(plugin.wrapPlayer(player)) ? "Yes" : "No"));
StringBuilder str = new StringBuilder();
for (Iterator<String> it = regions.iterator(); it.hasNext(); ) {
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
player.sendMessage(ChatColor.YELLOW + "Applicable regions: " + str.toString());
} else {
player.sendMessage(ChatColor.YELLOW + "WorldGuard: No defined regions here!");
}
}
}
/**
* Called when redstone changes
* From: the source of the redstone change
@@ -401,15 +417,19 @@ public class WorldGuardBlockListener extends BlockListener {
* @param event Relevant event details
*/
@Override
public void onBlockRedstoneChange(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockTo = event.getToBlock();
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
if (plugin.simulateSponge && plugin.redstoneSponges) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -1; cx <= 1; cx++) {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
@@ -417,15 +437,18 @@ public class WorldGuardBlockListener extends BlockListener {
if (sponge.getTypeId() == 19
&& sponge.isBlockIndirectlyPowered()) {
clearSpongeWater(world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
&& !sponge.isBlockIndirectlyPowered()) {
addSpongeWater(world, ox + cx, oy + cy, oz + cz);
}
}
}
}
return;
}
}
/**
* Remove water around a sponge.
*
@@ -435,17 +458,127 @@ public class WorldGuardBlockListener extends BlockListener {
* @param oz
*/
private void clearSpongeWater(World world, int ox, int oy, int oz) {
for (int cx = -plugin.spongeRadius; cx <= plugin.spongeRadius; cx++) {
for (int cy = -plugin.spongeRadius; cy <= plugin.spongeRadius; cy++) {
for (int cz = -plugin.spongeRadius; cz <= plugin.spongeRadius; cz++) {
Block block = world.getBlockAt(ox + cx, oy + cy, oz + cz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
world.getBlockAt(ox + cx, oy + cy, oz + cz)
.setTypeId(0);
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water around a sponge.
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void addSpongeWater(World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
// The negative x edge
int cx = ox - wcfg.spongeRadius - 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx + 1, cy, cz);
}
}
}
// The positive x edge
cx = ox + wcfg.spongeRadius + 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx - 1, cy, cz);
}
}
}
// The negative y edge
int cy = oy - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy + 1, cz);
}
}
}
// The positive y edge
cy = oy + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy - 1, cz);
}
}
}
// The negative z edge
int cz = oz - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz + 1);
}
}
}
// The positive z edge
cz = oz + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz - 1);
}
}
}
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void setBlockToWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 0) {
block.setTypeId(8);
}
}
/**
* Checks if the given block is water
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private 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;
}
}
}
@@ -15,31 +15,39 @@
*
* 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.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
public class WorldGuardEntityListener extends EntityListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
@@ -49,99 +57,135 @@ public class WorldGuardEntityListener extends EntityListener {
this.plugin = plugin;
}
@Override
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(Event.Type.ENTITY_DAMAGE, this, Priority.High, plugin);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, this, Priority.High, plugin);
pm.registerEvent(Event.Type.CREATURE_SPAWN, this, Priority.High, plugin);
}
public void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
if (defender instanceof Player) {
Player player = (Player) defender;
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (plugin.disableLavaDamage && type == DamageCause.LAVA) {
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
}
}
@Override
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
if (defender instanceof Player) {
Player player = (Player) defender;
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (plugin.useRegions) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_PVP)) {
((Player)attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Monster) {
if (attacker instanceof Creeper && plugin.blockCreeperExplosions) {
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (plugin.useRegions) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_MOB_DAMAGE)) {
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_CREEPER_EXPLOSION)) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
public void onEntityDamageByProjectile(EntityDamageByProjectileEvent event) {
Entity defender = event.getEntity();
Entity attacker = event.getDamager();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
if (defender instanceof Player) {
Player player = (Player) defender;
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (plugin.useRegions) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_PVP)) {
((Player)attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Skeleton) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
@@ -151,52 +195,81 @@ public class WorldGuardEntityListener extends EntityListener {
}
@Override
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled()) {
return;
}
if (event instanceof EntityDamageByProjectileEvent) {
this.onEntityDamageByProjectile((EntityDamageByProjectileEvent) event);
return;
} else if (event instanceof EntityDamageByEntityEvent) {
this.onEntityDamageByEntity((EntityDamageByEntityEvent) event);
return;
} else if (event instanceof EntityDamageByBlockEvent) {
this.onEntityDamageByBlock((EntityDamageByBlockEvent) event);
return;
}
Entity defender = event.getEntity();
DamageCause type = event.getCause();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
if (defender instanceof Wolf) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (plugin.disableFallDamage && type == DamageCause.FALL) {
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(player)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& (player.getInventory().getHelmet().getType() == Material.PUMPKIN
|| player.getInventory().getHelmet().getType() == Material.JACK_O_LANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (plugin.disableFireDamage && (type == DamageCause.FIRE
if (wcfg.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (plugin.disableDrowningDamage && type == DamageCause.DROWNING) {
if (wcfg.disableDrowningDamage && type == DamageCause.DROWNING) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (plugin.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
findFreePosition(player);
event.setCancelled(true);
return;
}
if (plugin.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
if (plugin.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
if (type == DamageCause.DROWNING
&& plugin.amphibiousPlayers.contains(player.getName())) {
if (wcfg.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
@@ -205,44 +278,93 @@ public class WorldGuardEntityListener extends EntityListener {
@Override
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
if (event.getEntity() instanceof LivingEntity) {
if (plugin.blockCreeperBlockDamage) {
if (wcfg.blockCreeperBlockDamage) {
event.setCancelled(true);
return;
}
if (plugin.blockCreeperExplosions) {
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (plugin.useRegions) {
Vector pt = toVector(event.getEntity().getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_CREEPER_EXPLOSION)) {
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
} else { // Shall assume that this is TNT
if (plugin.blockTNT) {
if (wcfg.blockTNT) {
event.setCancelled(true);
return;
}
if (plugin.useRegions && event.getEntity() != null) {
Vector pt = toVector(event.getEntity().getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_TNT)) {
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
return;
}
}
}
}
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
//CreatureType creaType = (CreatureType) CreatureType.valueOf(event.getMobType().toString());
CreatureType creaType = event.getCreatureType();
Boolean cancelEvent = false;
if (wcfg.blockCreatureSpawn.contains(creaType)) {
cancelEvent = true;
}
// TODO: Monsters and stuff
/*
if (wcfg.useRegions) {
Vector pt = toVector(event.getEntity().getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(event.getEntity().getWorld().getName());
Boolean flagValue = mgr.getApplicableRegions(pt).getFlag(DefaultFlag.DENY_SPAWN).getValue("").contains(creaType.getName());
if (flagValue != null) {
if (flagValue) {
cancelEvent = true;
} else {
cancelEvent = false;
}
}
}*/
if (cancelEvent) {
event.setCancelled(true);
return;
}
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
@@ -273,7 +395,7 @@ public class WorldGuardEntityListener extends EntityListener {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
player.teleportTo(loc);
player.teleport(loc);
}
return;
@@ -15,30 +15,46 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.*;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Iterator;
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.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.*;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag.RegionGroup;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* Handles all events thrown in relation to a Player
*/
public class WorldGuardPlayerListener extends PlayerListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
@@ -48,26 +64,258 @@ public class WorldGuardPlayerListener extends PlayerListener {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_INTERACT, this, Priority.High, plugin);
pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, this, Priority.High, plugin);
pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, this, Priority.High, plugin);
pm.registerEvent(Event.Type.PLAYER_JOIN, this, Priority.Normal, plugin);
pm.registerEvent(Event.Type.PLAYER_LOGIN, this, Priority.Normal, plugin);
pm.registerEvent(Event.Type.PLAYER_QUIT, this, Priority.Normal, plugin);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, this, Priority.High, plugin);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, this, Priority.High, plugin);
pm.registerEvent(Event.Type.PLAYER_RESPAWN, this, Priority.High, plugin);
}
/**
* Called when a player interacts with an item.
*
* @param event Relevant event details
*/
@Override
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
handleBlockRightClick(event);
} else if (event.getAction() == Action.RIGHT_CLICK_AIR) {
handleAirRightClick(event);
}
}
/**
* Called when a block is damaged.
*
* @param event
*/
public void handleAirRightClick(PlayerInteractEvent event) {
/*if (event.isCancelled()) {
return;
}*/
Player player = event.getPlayer();
World world = player.getWorld();
ItemStack item = player.getItemInHand();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()),
item.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a block is damaged.
*
* @param event
*/
public void handleBlockRightClick(PlayerInteractEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getClickedBlock();
World world = block.getWorld();
Material type = block.getType();
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
Vector pt = toVector(block);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (item.getTypeId() == wcfg.regionWand) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (set.canBuild(localPlayer) ? "Yes" : "No"));
StringBuilder str = new StringBuilder();
for (Iterator<ProtectedRegion> it = set.iterator(); it.hasNext();) {
str.append(it.next().getId());
if (it.hasNext()) {
str.append(", ");
}
}
player.sendMessage(ChatColor.YELLOW + "Applicable regions: " + str.toString());
} else {
player.sendMessage(ChatColor.YELLOW + "WorldGuard: No defined regions here!");
}
event.setCancelled(true);
return;
}
if (item.getType() == Material.FLINT_AND_STEEL) {
if (!set.allows(DefaultFlag.LIGHTER)) {
event.setCancelled(true);
return;
}
}
if ((block.getType() == Material.CHEST
|| block.getType() == Material.DISPENSER
|| block.getType() == Material.FURNACE
|| block.getType() == Material.BURNING_FURNACE
|| block.getType() == Material.NOTE_BLOCK)) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.CHEST_ACCESS)
&& !set.canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (type == Material.LEVER || type == Material.STONE_BUTTON) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (type == Material.CAKE_BLOCK) {
if (!set.canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
event.setCancelled(true);
return;
}
}
if (type == Material.RAILS && item.getType() == Material.MINECART) {
if (!set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place vehicles here.");
event.setCancelled(true);
return;
}
}
if (item.getType() == Material.BOAT) {
if (!set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place vehicles here.");
event.setCancelled(true);
return;
}
}
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player), toVector(block),
item.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
if (!wcfg.getBlacklist().check(
new BlockInteractBlacklistEvent(plugin.wrapPlayer(player), toVector(block),
block.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
/*if (wcfg.useRegions && wcfg.useiConomy && cfg.getiConomy() != null
&& (type == Material.SIGN_POST || type == Material.SIGN || type == Material.WALL_SIGN)) {
BlockState block = blockClicked.getState();
if (((Sign)block).getLine(0).equalsIgnoreCase("[WorldGuard]")
&& ((Sign)block).getLine(1).equalsIgnoreCase("For sale")) {
String regionId = ((Sign)block).getLine(2);
//String regionComment = ((Sign)block).getLine(3);
if (regionId != null && regionId != "") {
RegionManager mgr = cfg.getWorldGuardPlugin().getGlobalRegionManager().get(player.getWorld().getName());
ProtectedRegion region = mgr.getRegion(regionId);
if (region != null) {
RegionFlags flags = region.getFlags();
if (flags.getBooleanFlag(DefaultFlag.BUYABLE).getValue(false)) {
if (iConomy.getBank().hasAccount(player.getName())) {
Account account = iConomy.getBank().getAccount(player.getName());
double balance = account.getBalance();
double regionPrice = flags.getDoubleFlag(DefaultFlag.PRICE).getValue();
if (balance >= regionPrice) {
account.subtract(regionPrice);
player.sendMessage(ChatColor.YELLOW + "You have bought the region " + regionId + " for " +
iConomy.getBank().format(regionPrice));
DefaultDomain owners = region.getOwners();
owners.addPlayer(player.getName());
region.setOwners(owners);
flags.getBooleanFlag(DefaultFlag.BUYABLE).setValue(false);
account.save();
} else {
player.sendMessage(ChatColor.YELLOW + "You have not enough money.");
}
} else {
player.sendMessage(ChatColor.YELLOW + "You have not enough money.");
}
} else {
player.sendMessage(ChatColor.RED + "Region: " + regionId + " is not buyable");
}
} else {
player.sendMessage(ChatColor.DARK_RED + "The region " + regionId + " does not exist.");
}
} else {
player.sendMessage(ChatColor.DARK_RED + "No region specified.");
}
}
}*/
}
/**
* Called when a player joins a server
*
* @param event Relevant event details
*/
@Override
public void onPlayerJoin(PlayerEvent event) {
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (plugin.fireSpreadDisableToggle) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.fireSpreadDisableToggle) {
player.sendMessage(ChatColor.YELLOW
+ "Fire spread is currently globally disabled.");
+ "Fire spread is currently globally disabled for this world.");
}
if (plugin.inGroup(player, "wg-invincible")) {
plugin.invinciblePlayers.add(player.getName());
cfg.enableGodMode(player);
}
if (plugin.inGroup(player, "wg-amphibious")) {
plugin.amphibiousPlayers.add(player.getName());
cfg.enableAmphibiousMode(player);
}
}
@@ -77,67 +325,81 @@ public class WorldGuardPlayerListener extends PlayerListener {
* @param event Relevant event details
*/
@Override
public void onPlayerQuit(PlayerEvent event) {
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
plugin.invinciblePlayers.remove(player.getName());
plugin.amphibiousPlayers.remove(player.getName());
if (plugin.blacklist != null) {
plugin.blacklist.forgetPlayer(plugin.wrapPlayer(player));
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
cfg.forgetPlayer(plugin.wrapPlayer(player));
}
/**
* Called when a player uses an item
*
* @param event Relevant event details
*/
*//*
@Override
public void onPlayerItem(PlayerItemEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Block block = event.getBlockClicked();
ItemStack item = event.getItem();
int itemId = item.getTypeId();
if (!plugin.itemDurability) {
GlobalConfiguration cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.getWorldConfig(player.getWorld().getName());
if (wcfg.useRegions
&& (itemId == 322 || itemId == 320 || itemId == 319 || itemId == 297 || itemId == 260
|| itemId == 350 || itemId == 349 || itemId == 354) ) {
return;
}
if (!wcfg.itemDurability) {
// Hoes
if (item.getTypeId() >= 290 && item.getTypeId() <= 294) {
item.setDamage((byte)-1);
item.setDurability((byte) -1);
player.setItemInHand(item);
}
}
if (plugin.useRegions && !event.isBlock() && block != null) {
if (wcfg.useRegions && !event.isBlock() && block != null) {
Vector pt = toVector(block.getRelative(event.getBlockFace()));
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
if (block.getType() == Material.WALL_SIGN) {
pt = pt.subtract(0, 1, 0);
}
if (!cfg.canBuild(player, pt)) {
player.sendMessage(ChatColor.DARK_RED
+ "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (plugin.blacklist != null && item != null && block != null) {
if (!plugin.blacklist.check(
if (wcfg.getBlacklist() != null && item != null && block != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(block.getRelative(event.getBlockFace())),
item.getTypeId()), false, false)) {
toVector(block.getRelative(event.getBlockFace())),
item.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (plugin.useRegions && item != null && block != null && item.getTypeId() == 259) {
if (wcfg.useRegions && item != null && block != null && item.getTypeId() == 259) {
Vector pt = toVector(block.getRelative(event.getBlockFace()));
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LIGHTER)) {
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld().getName());
if (!mgr.getApplicableRegions(pt).isStateFlagAllowed(DefaultFlag.LIGHTER)) {
event.setCancelled(true);
return;
}
}
}
}*/
/**
* Called when a player attempts to log in to the server
@@ -147,10 +409,13 @@ public class WorldGuardPlayerListener extends PlayerListener {
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
if (plugin.enforceOneSession) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.enforceOneSession) {
String name = player.getName();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (pl.getName().equalsIgnoreCase(name)) {
pl.kickPlayer("Logged in from another location.");
@@ -158,4 +423,151 @@ public class WorldGuardPlayerListener extends PlayerListener {
}
}
}
/**
* Called when a player attempts to drop an item
*
* @param event Relevant event details
*/
@Override
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
if (!wcfg.getBlacklist().check(
new ItemDropBlacklistEvent(plugin.wrapPlayer(event.getPlayer()),
toVector(ci.getLocation()), ci.getItemStack().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a player attempts to pickup an item
*
* @param event
* Relevant event details
*/
@Override
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
if (wcfg.getBlacklist() != null) {
Item ci = event.getItem();
if (!wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(plugin.wrapPlayer(event.getPlayer()),
toVector(ci.getLocation()), ci.getItemStack().getTypeId()), false, true)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a bucket is filled.
*/
@Override
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlockClicked())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), event.getBucket().getId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a bucket is empty.
*/
@Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlockClicked())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), event.getBucket().getId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
@Override
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.useRegions) {
Vector pt = toVector(location);
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
Vector spawn = set.getFlag(DefaultFlag.SPAWN_LOC);
if (spawn != null) {
RegionGroup group = set.getFlag(DefaultFlag.SPAWN_PERM);
Location spawnLoc = BukkitUtil.toLocation(player.getWorld(), spawn);
if (group != null) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (group == RegionGroup.OWNERS) {
if (set.isOwnerOfAll(localPlayer)) {
event.setRespawnLocation(spawnLoc);
}
} else if (group == RegionGroup.MEMBERS) {
if (set.isMemberOfAll(localPlayer)) {
event.setRespawnLocation(spawnLoc);
}
}
} else {
event.setRespawnLocation(spawnLoc);
}
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,316 @@
// $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.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldedit.blocks.ItemType;
public class GeneralCommands {
@Command(aliases = {"god"},
usage = "[player]",
desc = "Enable godmode on a player",
flags = "", min = 0, max = 1)
public static void god(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalConfiguration();
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
config.enableGodMode(player);
player.setFireTicks(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode enabled! Use /ungod to disable.");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God enabled by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players now have god mode.");
}
}
@Command(aliases = {"ungod"},
usage = "[player]",
desc = "Disable godmode on a player",
flags = "", min = 0, max = 1)
public static void ungod(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalConfiguration();
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
config.disableGodMode(player);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode disabled!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God disabled by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players now have god mode.");
}
}
@Command(aliases = {"heal"},
usage = "[player]",
desc = "Heal a player",
flags = "", min = 0, max = 1)
public static void heal(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal.other");
}
for (Player player : targets) {
player.setHealth(20);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Healed!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Healed by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players healed.");
}
}
@Command(aliases = {"slay"},
usage = "[player]",
desc = "Slay a player",
flags = "", min = 0, max = 1)
public static void slay(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay.other");
}
for (Player player : targets) {
player.setHealth(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Slayed!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Slayed by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players slayed.");
}
}
@Command(aliases = {"locate"},
usage = "[player]",
desc = "Locate a player",
flags = "", min = 0, max = 1)
@CommandPermissions({"worldguard.locate"})
public static void locate(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
if (args.argsLength() == 0) {
player.setCompassTarget(player.getWorld().getSpawnLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass reset to spawn.");
} else {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
player.setCompassTarget(target.getLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass repointed.");
}
}
@Command(aliases = {"stack"},
usage = "",
desc = "Stack items",
flags = "", min = 0, max = 0)
@CommandPermissions({"worldguard.stack"})
public static void stack(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
int affected = 0;
for (int i = 0; i < len; i++) {
ItemStack item = items[i];
// Avoid infinite stacks and stacks with durability
if (item == null || item.getAmount() <= 0
|| ItemType.shouldNotStack(item.getTypeId())) {
continue;
}
// Ignore buckets
if (item.getTypeId() >= 325 && item.getTypeId() <= 327) {
continue;
}
if (item.getAmount() < 64) {
int needed = 64 - item.getAmount(); // Number of needed items until 64
// Find another stack of the same type
for (int j = i + 1; j < len; j++) {
ItemStack item2 = items[j];
// Avoid infinite stacks and stacks with durability
if (item2 == null || item2.getAmount() <= 0
|| ItemType.shouldNotStack(item.getTypeId())) {
continue;
}
// Same type?
// Blocks store their color in the damage value
if (item2.getTypeId() == item.getTypeId() &&
(!ItemType.usesDamageValue(item.getTypeId())
|| item.getDurability() == item2.getDurability())) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(64);
item2.setAmount(item2.getAmount() - needed);
break;
// This stack will
} else {
items[j] = null;
item.setAmount(item.getAmount() + item2.getAmount());
needed = 64 - item.getAmount();
}
affected++;
}
}
}
}
if (affected > 0) {
player.getInventory().setContents(items);
}
player.sendMessage(ChatColor.YELLOW + "Items compacted into stacks!");
}
}
@@ -0,0 +1,40 @@
// $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.commands;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ProtectionCommands {
@Command(aliases = {"region"},
desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public static void region(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
}
@Command(aliases = {"worldguard"},
desc = "WorldGuard commands")
@NestedCommand({WorldGuardCommands.class})
public static void worldGuard(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
}
}
@@ -0,0 +1,857 @@
// $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.commands;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.*;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.*;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.RegionUtil;
public class RegionCommands {
@Command(aliases = {"define", "def", "d"},
usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Defines a region",
flags = "", min = 1, max = -1)
@CommandPermissions({"worldguard.region.define"})
public static void define(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new ProtectedCuboidRegion(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionUtil.parseDomainString(args.getSlice(1), 1));
}
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"redefine", "update", "move"},
usage = "<id>",
desc = "Re-defines the shape of a region",
flags = "", min = 1, max = 1)
public static void redefine(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
WorldEditPlugin worldEdit = plugin.getWorldEdit();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion existing = mgr.getRegion(id);
if (existing == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (existing.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.redefine.own");
} else if (existing.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.redefine.member");
} else {
plugin.checkPermission(sender, "worldguard.region.redefine");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new ProtectedCuboidRegion(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
region.setMembers(existing.getMembers());
region.setOwners(existing.getOwners());
region.setFlags(existing.getFlags());
region.setPriority(existing.getPriority());
try {
region.setParent(existing.getParent());
} catch (CircularInheritanceException e) {
}
mgr.addRegion(region);
sender.sendMessage(ChatColor.YELLOW + "Region updated with new area.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"claim"},
usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Claim a region",
flags = "", min = 1, max = -1)
@CommandPermissions({"worldguard.region.claim"})
public static void claim(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new ProtectedCuboidRegion(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionUtil.parseDomainString(args.getSlice(1), 1));
}
WorldConfiguration wcfg = plugin.getGlobalConfiguration().get(player.getWorld());
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
// Check whether the player has created too many regions
if (wcfg.maxRegionCountPerPlayer >= 0
&& mgr.getRegionCountOfPlayer(localPlayer) >= wcfg.maxRegionCountPerPlayer) {
throw new CommandException("You own too many regions, delete one first to claim a new one.");
}
ProtectedRegion existing = mgr.getRegion(id);
// Check for an existing region
if (existing != null) {
if (!existing.getOwners().contains(localPlayer)) {
throw new CommandException("This region already exists and you don't own it.");
}
}
ApplicableRegionSet regions = mgr.getApplicableRegions(region);
// Check if this region overlaps any other region
if (regions.size() > 0) {
if (!regions.isOwnerOfAll(localPlayer)) {
throw new CommandException("This region overlaps with someone else's region.");
}
} else {
if (wcfg.claimOnlyInsideExistingRegions) {
throw new CommandException("You may only claim regions inside " +
"existing regions that you or your group own.");
}
}
/*if (plugin.getGlobalConfiguration().getiConomy() != null && wcfg.useiConomy && wcfg.buyOnClaim) {
if (iConomy.getBank().hasAccount(player.getName())) {
Account account = iConomy.getBank().getAccount(player.getName());
double balance = account.getBalance();
double regionCosts = region.countBlocks() * wcfg.buyOnClaimPrice;
if (balance >= regionCosts) {
account.subtract(regionCosts);
player.sendMessage(ChatColor.YELLOW + "You have bought that region for "
+ iConomy.getBank().format(regionCosts));
account.save();
} else {
player.sendMessage(ChatColor.RED + "You have not enough money.");
player.sendMessage(ChatColor.RED + "The region you want to claim costs "
+ iConomy.getBank().format(regionCosts));
player.sendMessage(ChatColor.RED + "You have " + iConomy.getBank().format(balance));
return;
}
} else {
player.sendMessage(ChatColor.YELLOW + "You have not enough money.");
return;
}
}*/
if (region.volume() > wcfg.maxClaimVolume) {
player.sendMessage(ChatColor.RED + "This region is to large to claim.");
player.sendMessage(ChatColor.RED +
"Max. volume: " + wcfg.maxClaimVolume + ", your volume: " + region.volume());
return;
}
region.getOwners().addPlayer(player.getName());
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"select", "sel", "s"},
usage = "<id>",
desc = "Load a region as a WorldEdit selection",
flags = "", min = 1, max = 1)
public static void select(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
WorldEditPlugin worldEdit = plugin.getWorldEdit();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.select.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.select.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.select." + id.toLowerCase());
}
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
Vector pt1 = cuboid.getMinimumPoint();
Vector pt2 = cuboid.getMaximumPoint();
CuboidSelection selection = new CuboidSelection(world, pt1, pt2);
worldEdit.setSelection(player, selection);
sender.sendMessage(ChatColor.YELLOW + "Region selected as a cuboid.");
} else if (region instanceof ProtectedPolygonalRegion) {
ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
Polygonal2DSelection selection = new Polygonal2DSelection(world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(), poly2d.getMaximumPoint().getBlockY());
worldEdit.setSelection(player, selection);
sender.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
throw new CommandException("Can't select global regions.");
} else {
throw new CommandException("Unknown region type: " + region.getClass().getCanonicalName());
}
}
@Command(aliases = {"info", "i"},
usage = "[world] <id>",
desc = "Get information about a region",
flags = "", min = 1, max = 2)
public static void info(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = null;
LocalPlayer localPlayer = null;
World world;
String id;
// Get different values based on provided arguments
if (args.argsLength() == 1) {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
id = args.getString(0).toLowerCase();
} else {
world = plugin.matchWorld(sender, args.getString(0));
id = args.getString(1).toLowerCase();
}
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.hasRegion(id)) {
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
}
ProtectedRegion region = mgr.getRegion(id);
if (player != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.own");
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.member");
} else {
plugin.checkPermission(sender, "worldguard.region.info");
}
} else {
plugin.checkPermission(sender, "worldguard.region.info");
}
DefaultDomain owners = region.getOwners();
DefaultDomain members = region.getMembers();
sender.sendMessage(ChatColor.YELLOW + "Region: " + id
+ ChatColor.GRAY + " (type: " + region.getTypeName() + ")");
sender.sendMessage(ChatColor.BLUE + "Priority: " + region.getPriority());
StringBuilder s = new StringBuilder();
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object val = region.getFlag(flag);
if (val == null) {
continue;
}
if (s.length() > 0) {
s.append(", ");
}
s.append(flag.getName() + ": " + String.valueOf(val));
}
sender.sendMessage(ChatColor.BLUE + "Flags: " + s.toString());
sender.sendMessage(ChatColor.BLUE + "Parent: "
+ (region.getParent() == null ? "(none)" : region.getParent().getId()));
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Owners: "
+ owners.toUserFriendlyString());
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Members: "
+ members.toUserFriendlyString());
}
@Command(aliases = {"list"},
usage = "[page] [world]",
desc = "Get a list of regions",
flags = "", min = 0, max = 2)
@CommandPermissions({"worldguard.region.list"})
public static void list(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world;
int page = 0;
if (args.argsLength() > 0) {
page = Math.max(0, args.getInteger(0) - 1);
}
if (args.argsLength() > 1) {
world = plugin.matchWorld(sender, args.getString(1));
} else {
world = plugin.checkPlayer(sender).getWorld();
}
int listSize = 10;
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Map<String, ProtectedRegion> regions = mgr.getRegions();
int size = regions.size();
int pages = (int) Math.ceil(size / (float) listSize);
String[] regionIDList = new String[size];
int index = 0;
for (String id : regions.keySet()) {
regionIDList[index] = id;
index++;
}
Arrays.sort(regionIDList);
sender.sendMessage(ChatColor.RED + "Regions (page "
+ (page + 1) + " of " + pages + "):");
if (page < pages) {
for (int i = page * listSize; i < page * listSize + listSize; i++) {
if (i >= size) {
break;
}
sender.sendMessage(ChatColor.YELLOW.toString() + (i + 1) +
". " + regionIDList[i]);
}
}
}
@Command(aliases = {"flag", "f"},
usage = "<id> <flag> [value]",
desc = "Set flags",
flags = "", min = 2, max = -1)
public static void flag(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
String flagName = args.getString(1);
String value = null;
if (args.argsLength() >= 3) {
value = args.getJoinedStrings(2);
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
if (id.equalsIgnoreCase("__global__")) {
region = new GlobalProtectedRegion(id);
mgr.addRegion(region);
} else {
throw new CommandException("Could not find a region by that ID.");
}
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.flag." + id.toLowerCase());
}
Flag<?> foundFlag = null;
// Now time to find the flag!
for (Flag<?> flag : DefaultFlag.getFlags()) {
// Try to detect the flag
if (flag.getName().replace("-", "").equalsIgnoreCase(flagName.replace("-", ""))) {
foundFlag = flag;
break;
}
}
if (foundFlag == null) {
StringBuilder list = new StringBuilder();
// Need to build a list
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (list.length() > 0) {
list.append(", ");
}
if (region.isOwner(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".owner." + id.toLowerCase())) {
continue;
}
} else if (region.isMember(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".member." + id.toLowerCase())) {
continue;
}
} else {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + "." + id.toLowerCase())) {
continue;
}
}
list.append(flag.getName());
}
player.sendMessage(ChatColor.RED + "Unknown flag specified: " + flagName);
player.sendMessage(ChatColor.RED + "Available flags: " + list);
return;
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".owner." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + "." + id.toLowerCase());
}
if (value != null) {
try {
setFlag(region, foundFlag, plugin, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' set.");
} else {
// Clear the flag
region.setFlag(foundFlag, null);
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' cleared.");
}
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
public static <V> void setFlag(ProtectedRegion region,
Flag<V> flag, WorldGuardPlugin plugin, CommandSender sender, String value)
throws InvalidFlagFormat {
region.setFlag(flag, flag.parseInput(plugin, sender, value));
}
@Command(aliases = {"setpriority", "priority", "pri"},
usage = "<id> <priority>",
desc = "Set the priority of a region",
flags = "", min = 2, max = 2)
public static void setPriority(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
int priority = args.getInteger(1);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setpriority." + id.toLowerCase());
}
region.setPriority(priority);
sender.sendMessage(ChatColor.YELLOW
+ "Priority of '" + region.getId() + "' set to "
+ priority + ".");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"setparent", "parent", "par"},
usage = "<id> [parent-id]",
desc = "Set the parent of a region",
flags = "", min = 1, max = 2)
public static void setParent(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (args.argsLength() == 1) {
try {
region.setParent(null);
} catch (CircularInheritanceException e) {
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' cleared.");
} else {
String parentId = args.getString(1);
ProtectedRegion parent = mgr.getRegion(parentId);
if (region == null) {
throw new CommandException("Could not find a target region by that ID.");
}
if (parent == null) {
throw new CommandException("Could not find the parent region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
}
if (parent.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
} else if (parent.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
}
try {
region.setParent(parent);
} catch (CircularInheritanceException e) {
throw new CommandException("Circular inheritance detected!");
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' set to '"
+ parent.getId() + "'.");
}
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"remove", "delete", "del", "rem"},
usage = "<id>",
desc = "Remove a region",
flags = "", min = 1, max = 1)
public static void remove(CommandContext args, WorldGuardPlugin plugin,
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);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.remove." + id.toLowerCase());
}
mgr.removeRegion(id);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' removed.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"load", "reload"},
usage = "[world]",
desc = "Reload regions from file",
flags = "", min = 0, max = 1)
public static void load(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.load();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' load.");
} catch (IOException e) {
throw new CommandException("Failed to read regions file: "
+ e.getMessage());
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.load();
} catch (IOException e) {
throw new CommandException("Failed to read regions file: "
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases loaded.");
}
}
@Command(aliases = {"save", "write"},
usage = "[world]",
desc = "Re-save regions to file",
flags = "", min = 0, max = 1)
public static void save(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' saved.");
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases saved.");
}
}
}
@@ -0,0 +1,219 @@
// $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.commands;
import java.io.IOException;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.RegionUtil;
// @TODO: A lot of code duplication here! Need to fix.
public class RegionMemberCommands {
@Command(aliases = {"addmember", "addmember"},
usage = "<id> <members...>",
desc = "Add a member to a region",
flags = "", min = 2, max = -1)
public static void addMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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());
}
RegionUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"},
usage = "<id> <owners...>",
desc = "Add an owner to a region",
flags = "", min = 2, max = -1)
public static void addOwner(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
RegionUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeMember(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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());
}
RegionUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"},
usage = "<id> <owners...>",
desc = "Remove an owner to a region",
flags = "", min = 2, max = -1)
public static void removeOwner(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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());
}
RegionUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (IOException e) {
throw new CommandException("Failed to write regions file: "
+ e.getMessage());
}
}
}
@@ -0,0 +1,90 @@
// $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.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ToggleCommands {
@Command(aliases = {"stopfire"},
usage = "[<world>]", desc = "Disables all fire spread temporarily",
flags = "", min = 0, max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void stopFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalConfiguration().get(world);
if (!wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(
ChatColor.YELLOW
+ "Fire spread has been globally disabled for '" + world.getName() + "' by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(
ChatColor.YELLOW
+ "Fire spread was already globally disabled.");
}
wcfg.fireSpreadDisableToggle = true;
}
@Command(aliases = {"allowfire"},
usage = "[<world>]", desc = "Allows all fire spread temporarily",
flags = "", min = 0, max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public static void allowFire(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalConfiguration().get(world);
if (wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "Fire spread has been globally for '" + world.getName() + "' re-enabled by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(ChatColor.YELLOW
+ "Fire spread was already globally enabled.");
}
wcfg.fireSpreadDisableToggle = false;
}
}
@@ -0,0 +1,127 @@
// $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.commands;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.LoggerToChatHandler;
import com.sk89q.worldguard.bukkit.ReportWriter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
public class WorldGuardCommands {
@Command(aliases = {"version"},
usage = "",
desc = "Get the WorldGuard version",
flags = "", min = 0, max = 0)
public static void version(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
sender.sendMessage(ChatColor.YELLOW
+ "WorldGuard " + plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "http://www.sk89q.com");
}
@Command(aliases = {"reload"},
usage = "",
desc = "Reload WorldGuard configuration",
flags = "", min = 0, max = 0)
@CommandPermissions({"worldguard.reload"})
public static void relload(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
if (sender instanceof Player) {
handler = new LoggerToChatHandler(sender);
handler.setLevel(Level.ALL);
minecraftLogger = Logger.getLogger("Minecraft");
minecraftLogger.addHandler(handler);
}
try {
plugin.getGlobalConfiguration().unload();
plugin.getGlobalRegionManager().unload();
plugin.getGlobalConfiguration().load();
plugin.getGlobalRegionManager().preload();
sender.sendMessage("WorldGuard configuration reloaded.");
} catch (Throwable t) {
sender.sendMessage("Error while reloading: "
+ t.getMessage());
} finally {
if (minecraftLogger != null) {
minecraftLogger.removeHandler(handler);
}
}
}
@Command(aliases = {"report"},
usage = "",
desc = "Writes a report on WorldGuard",
flags = "p", min = 0, max = 0)
@CommandPermissions({"worldguard.report"})
public static void report(CommandContext args, WorldGuardPlugin plugin,
final CommandSender sender) throws CommandException {
File dest = new File(plugin.getDataFolder(), "report.txt");
ReportWriter report = new ReportWriter(plugin);
try {
report.write(dest);
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report written to "
+ dest.getAbsolutePath());
} catch (IOException e) {
throw new CommandException("Failed to write report: " + e.getMessage());
}
if (args.hasFlag('p')) {
plugin.checkPermission(sender, "worldguard.report.pastebin");
sender.sendMessage(ChatColor.YELLOW + "Now uploading to Pastebin...");
PastebinPoster.paste(report.toString(), new PasteCallback() {
@Override
public void handleSuccess(String url) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report (1 hour): " + url);
}
@Override
public void handleError(String err) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report pastebin error: " + err);
}
});
}
}
}
@@ -15,39 +15,42 @@
*
* 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;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.AreaFlags.State;
/**
* Represents a set of regions and their rules as applied to one point.
* Represents a setFlag of regions and their rules as applied to one point or
* region.
*
* @author sk89q
*/
public class ApplicableRegionSet {
private GlobalFlags global;
private Vector pt;
private SortedMap<String,ProtectedRegion> regions;
private Collection<ProtectedRegion> applicable;
private ProtectedRegion globalRegion;
/**
* Construct the object.
*
* @param pt
* @param regions
* @param global
* @param applicable
* @param globalRegion
*/
public ApplicableRegionSet(Vector pt, SortedMap<String,ProtectedRegion> regions,
GlobalFlags global) {
this.pt = pt;
this.regions = regions;
this.global = global;
public ApplicableRegionSet(Collection<ProtectedRegion> applicable,
ProtectedRegion globalRegion) {
this.applicable = applicable;
this.globalRegion = globalRegion;
}
/**
@@ -57,40 +60,95 @@ public class ApplicableRegionSet {
* @return
*/
public boolean canBuild(LocalPlayer player) {
return isFlagAllowed(AreaFlags.FLAG_BUILD, global.canBuild, player);
return internalGetState(DefaultFlag.BUILD, player);
}
/**
* Checks a flag.
* Checks if a player can build in an area.
*
* @param player
* @return
*/
public boolean allowsFlag(String flag) {
boolean def = true;
if (flag.equals(AreaFlags.FLAG_CHEST_ACCESS)) {
def = global.canAccessChests;
} else if (flag.equals(AreaFlags.FLAG_PVP)) {
def = global.canPvP;
}
return isFlagAllowed(flag, def, null);
public boolean canUse(LocalPlayer player) {
return internalGetState(DefaultFlag.USE, player);
}
/**
* Checks to see if a flag is permitted.
* Gets the state of a state flag. This cannot be used for the build flag.
*
* @param def default state if there are no regions defined
* @param player null to not check owners and members
* @param flag
* @return
*/
private boolean isFlagAllowed(String flag, boolean def, LocalPlayer player) {
public boolean allows(StateFlag flag) {
return internalGetState(flag, null);
}
/**
* Indicates whether a player is an owner of all regions in this set.
*
* @param player
* @return
*/
public boolean isOwnerOfAll(LocalPlayer player) {
for (ProtectedRegion region : applicable) {
if (!region.isOwner(player)) {
return false;
}
}
return true;
}
/**
* Indicates whether a player is an owner or member of all regions in
* this set.
*
* @param player
* @return
*/
public boolean isMemberOfAll(LocalPlayer player) {
for (ProtectedRegion region : applicable) {
if (!region.isMember(player)) {
return false;
}
}
return true;
}
/**
* Checks to see if a flag is permitted.
*
* @param def
* default state if there are no regions defined
* @param player
* null to not check owners and members
* @return
*/
private boolean internalGetState(StateFlag flag, LocalPlayer player) {
boolean found = false;
boolean allowed = false; // Used for ALLOW override
if (player == null) {
allowed = def;
boolean def = flag.getDefault();
// Handle defaults
if (globalRegion != null) {
State globalState = globalRegion.getFlag(flag);
// The global region has this flag set
if (globalState != null) {
def = (globalState == State.ALLOW);
}
}
// The player argument is used if and only if the flag is the build
// flag -- in which case, if there are any regions in this area, we
// default to FALSE, otherwise true if there are no defined regions.
// However, other flags are different -- if there are regions defined,
// we default to the global region value.
if (player == null) {
allowed = def;
}
int lastPriority = 0;
// The algorithm is as follows:
@@ -107,39 +165,44 @@ public class ApplicableRegionSet {
// permission should not be given. If a parent has multiple children
// and one child does not allow permissions, then it will be placed into
// needsClear just like as if was a parent.
Set<ProtectedRegion> needsClear = new HashSet<ProtectedRegion>();
Set<ProtectedRegion> hasCleared = new HashSet<ProtectedRegion>();
Iterator<ProtectedRegion> it = applicable.iterator();
for (ProtectedRegion region : regions.values()) {
// Ignore non-build regions
if (player != null && region.getFlags().get(AreaFlags.FLAG_PASSTHROUGH) == State.ALLOW) {
continue;
}
// Forget about regions that are not covered
if (!region.contains(pt)) {
continue;
}
// Allow DENY to override everything
if (region.getFlags().get(flag) == State.DENY) {
return false;
}
// Forget about regions that allow it, although make sure the
// default state is now to allow
if (region.getFlags().get(flag) == State.ALLOW) {
allowed = true;
found = true;
continue;
}
while (it.hasNext()) {
ProtectedRegion region = it.next();
// Ignore lower priority regions
if (found && region.getPriority() < lastPriority) {
break;
}
// Ignore non-build regions
if (player != null
&& region.getFlag(DefaultFlag.PASSTHROUGH) == State.ALLOW) {
continue;
}
State v = region.getFlag(flag);
// Allow DENY to override everything
if (v == State.DENY) {
return false;
}
// Forget about regions that allow it, although make sure the
// default state is now to allow
if (v == State.ALLOW) {
allowed = true;
found = true;
continue;
}
// For the build flag, the flags are conditional and are based
// on membership, so we have to check for parent-child
// relationships
if (player != null) {
if (hasCleared.contains(region)) {
// Already cleared, so do nothing
@@ -152,15 +215,15 @@ public class ApplicableRegionSet {
}
}
}
found = true;
lastPriority = region.getPriority();
}
return (found == false ? def : allowed)
|| (player != null && needsClear.size() == 0);
return found == false ? def :
(allowed || (player != null && needsClear.size() == 0));
}
/**
* Clear a region's parents for isFlagAllowed().
*
@@ -171,13 +234,95 @@ public class ApplicableRegionSet {
private void clearParents(Set<ProtectedRegion> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (!needsClear.remove(parent)) {
hasCleared.add(parent);
}
parent = parent.getParent();
}
}
/**
* Gets the value of a flag. Do not use this for state flags.
*
* @param flag
* @param <T>
* @param <V>
* @return
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
int lastPriority = 0;
boolean found = false;
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();
// Ignore lower priority regions
if (found && region.getPriority() < lastPriority) {
break;
}
if (hasCleared.contains(region)) {
// Already cleared, so do nothing
} else if (region.getFlag(flag) != null){
clearParents(needsClear, hasCleared, region);
needsClear.put(region, region.getFlag(flag));
}
found = true;
lastPriority = region.getPriority();
}
try {
return needsClear.values().iterator().next();
} catch (NoSuchElementException e) {
return null;
}
}
/**
* Clear a region's parents for getFlag().
*
* @param needsClear
* @param hasCleared
* @param region
*/
private void clearParents(Map<ProtectedRegion, ?> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (needsClear.remove(parent) == null) {
hasCleared.add(parent);
}
parent = parent.getParent();
}
}
/**
* Get the number of regions that are included.
*
* @return
*/
public int size() {
return applicable.size();
}
/**
* Get an iterator of affected regions.
*
* @return
*/
public Iterator<ProtectedRegion> iterator() {
return applicable.iterator();
}
}
@@ -1,145 +0,0 @@
// $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;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Holds the flags for a region.
*
* @author sk89q
*/
public class AreaFlags {
public enum State {
NONE,
ALLOW,
DENY,
};
public static final String FLAG_PASSTHROUGH = "z";
public static final String FLAG_BUILD = "b";
public static final String FLAG_PVP = "p";
public static final String FLAG_MOB_DAMAGE = "m";
public static final String FLAG_CREEPER_EXPLOSION = "c";
public static final String FLAG_TNT = "t";
public static final String FLAG_LIGHTER = "l";
public static final String FLAG_FIRE_SPREAD = "f";
public static final String FLAG_LAVA_FIRE = "F";
public static final String FLAG_CHEST_ACCESS = "C";
/**
* Get the user-friendly name of a flag. If a name isn't known, then
* the flag is returned unchanged.
*
* @param flag
* @return
*/
public static String getFlagName(String flag) {
if (flag.equals(FLAG_PASSTHROUGH)) {
return "passthrough";
} else if (flag.equals(FLAG_BUILD)) {
return "build";
} else if (flag.equals(FLAG_PVP)) {
return "PvP";
} else if (flag.equals(FLAG_MOB_DAMAGE)) {
return "mob damage";
} else if (flag.equals(FLAG_CREEPER_EXPLOSION)) {
return "creeper explosion";
} else if (flag.equals(FLAG_TNT)) {
return "TNT";
} else if (flag.equals(FLAG_LIGHTER)) {
return "lighter";
} else if (flag.equals(FLAG_FIRE_SPREAD)) {
return "fire spread";
} else if (flag.equals(FLAG_LAVA_FIRE)) {
return "lava fire spread";
} else if (flag.equals(FLAG_CHEST_ACCESS)) {
return "chest access";
} else {
return flag;
}
}
/**
* Gets a flag from an alias. May return null.
*
* @param name
* @return
*/
public static String fromAlias(String name) {
if (name.equalsIgnoreCase("passthrough")) {
return FLAG_PASSTHROUGH;
} else if (name.equalsIgnoreCase("build")) {
return FLAG_BUILD;
} else if (name.equalsIgnoreCase("pvp")) {
return FLAG_PVP;
} else if (name.equalsIgnoreCase("mobdamage")) {
return FLAG_MOB_DAMAGE;
} else if (name.equalsIgnoreCase("creeper")) {
return FLAG_CREEPER_EXPLOSION;
} else if (name.equalsIgnoreCase("tnt")) {
return FLAG_TNT;
} else if (name.equalsIgnoreCase("lighter")) {
return FLAG_LIGHTER;
} else if (name.equalsIgnoreCase("firespread")) {
return FLAG_FIRE_SPREAD;
} else if (name.equalsIgnoreCase("lavafirespread")) {
return FLAG_LAVA_FIRE;
} else if (name.equalsIgnoreCase("chest")) {
return FLAG_CHEST_ACCESS;
} else {
return null;
}
}
private Map<String, State> states = new HashMap<String, State>();
public State get(String flag) {
State state = states.get(flag);
if (state == null) {
return State.NONE;
}
return state;
}
public void set(String flag, State state) {
if (state == State.NONE) {
states.remove(flag);
} else {
states.put(flag, state);
}
}
public Set<Map.Entry<String, State>> entrySet() {
return states.entrySet();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AreaFlags)) {
return false;
}
AreaFlags other = (AreaFlags)obj;
return other.states.equals(this);
}
}
@@ -1,183 +0,0 @@
// $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;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* A very simple implementation of the region manager that uses a flat list
* and iterates through the list to identify applicable regions. This method
* is not very efficient.
*
* @author sk89q
*/
public class FlatRegionManager implements RegionManager {
/**
* List of protected regions.
*/
private SortedMap<String,ProtectedRegion> regions;
/**
* Global flags.
*/
private GlobalFlags global;
/**
* Construct the manager.
*/
public FlatRegionManager(GlobalFlags global) {
regions = new TreeMap<String,ProtectedRegion>();
this.global = global;
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = new TreeMap<String,ProtectedRegion>(regions);
}
/**
* Adds a region.
*
* @param id
* @param region
*/
public void addRegion(ProtectedRegion region) {
regions.put(region.getId(), region);
}
/**
* Removes a region and its children.
*
* @param id
*/
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id);
regions.remove(id);
if (region != null) {
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().getParent() == region) {
removeRegion(entry.getKey());
}
}
}
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
public boolean hasRegion(String id) {
return regions.containsKey(id);
}
/**
* Get a region by its ID.
*
* @param id
*/
public ProtectedRegion getRegion(String id) {
return regions.get(id);
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
public ApplicableRegionSet getApplicableRegions(Vector pt) {
return new ApplicableRegionSet(pt, regions, global);
}
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
for (Map.Entry<String,ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().contains(pt)) {
applicable.add(entry.getKey());
}
}
return applicable;
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param region
* @param player
* @return
*/
public boolean overlapsUnownedRegion(ProtectedRegion region, LocalPlayer player) {
for (ProtectedRegion other : regions.values()) {
if (other.getOwners().contains(player)) {
continue;
}
try {
if (ProtectedRegion.intersects(region, other)) {
return true;
}
} catch (UnsupportedIntersectionException e) {
// TODO: Maybe do something here
}
}
return false;
}
/**
* Get the number of regions.
*
* @return
*/
public int size() {
return regions.size();
}
}
@@ -0,0 +1,276 @@
// $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;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
/**
* This class keeps track of region information for every world. It loads
* world region information as needed.
*
* @author sk89q
* @author Redecouverte
*/
public class GlobalRegionManager {
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Reference to the global configuration.
*/
private ConfigurationManager config;
/**
* Map of managers per-world.
*/
private HashMap<String, RegionManager> managers;
/**
* Stores the list of modification dates for the world files. This allows
* WorldGuard to reload files as needed.
*/
private HashMap<String, Long> lastModified;
/**
* Construct the object.
*
* @param plugin
*/
public GlobalRegionManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
config = plugin.getGlobalConfiguration();
managers = new HashMap<String, RegionManager>();
lastModified = new HashMap<String, Long>();
}
/**
* Unload region information.
*/
public void unload() {
managers.clear();
lastModified.clear();
}
/**
* Get the path for a world's regions file.
*
* @param name
* @return
*/
protected File getPath(String name) {
return new File(plugin.getDataFolder(),
"worlds" + File.separator + name + File.separator + "regions.yml");
}
/**
* Unload region information for a world.
*
* @param name
*/
public void unload(String name) {
RegionManager manager = managers.get(name);
if (manager != null) {
managers.remove(name);
lastModified.remove(name);
}
}
/**
* Unload all region information.
*/
public void unloadAll() {
managers.clear();
lastModified.clear();
}
/**
* Load region information for a world.
*
* @param world
*/
public void load(World world) {
String name = world.getName();
File file = getPath(name);
try {
// Create a manager
RegionManager manager = new FlatRegionManager(new YAMLDatabase(file));
managers.put(name, manager);
manager.load();
logger.info("WorldGuard: " + manager.getRegions().size()
+ " regions loaded for '" + name + "'");
// Store the last modification date so we can track changes
lastModified.put(name, file.lastModified());
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions from file "
+ file.getAbsolutePath() + " : " + e.getMessage());
}
}
/**
* Preloads region managers for all worlds.
*/
public void preload() {
// Load regions
for (World world : plugin.getServer().getWorlds()) {
load(world);
}
}
/**
* Reloads the region information from file when region databases
* have changed.
*/
public void reloadChanged() {
for (String name : managers.keySet()) {
File file = getPath(name);
Long oldDate = lastModified.get(name);
if (oldDate == null) {
oldDate = 0L;
}
try {
if (file.lastModified() > oldDate) {
World world = plugin.getServer().getWorld(name);
if (world != null) {
load(world);
}
}
} catch (Exception e) {
}
}
}
/**
* Get the region manager for a particular world.
*
* @param world
* @return
*/
public RegionManager get(World world) {
RegionManager manager = managers.get(world.getName());
if (manager == null) {
load(world);
}
return manager;
}
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
*/
public boolean hasBypass(Player player, World world) {
return plugin.hasPermission(player, "worldguard.region.bypass."
+ world.getName());
}
/**
* Check if a player has permission to build at a block.
*
* @param player
* @param block
* @return
*/
public boolean canBuild(Player player, Block block) {
return canBuild(player, block.getLocation());
}
/**
* Check if a player has permission to build at a location.
*
* @param player
* @param loc
* @return
*/
public boolean canBuild(Player player, Location loc) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!hasBypass(player, world)) {
RegionManager mgr = get(world);
if (!mgr.getApplicableRegions(BukkitUtil.toVector(loc))
.canBuild(localPlayer)) {
return false;
}
}
return true;
}
/**
* Checks to see whether a flag is allowed.
*
* @param flag
* @param loc
* @return
*/
public boolean allows(StateFlag flag, Location loc) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
return mgr.getApplicableRegions(toVector(loc)).allows(flag);
}
}
@@ -1,110 +0,0 @@
// $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;
import com.sk89q.worldedit.*;
/**
* Represents a cuboid region that can be protected.
*
* @author sk89q
*/
public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Store the first point.
*/
private BlockVector min;
/**
* Store the second point.
*/
private BlockVector max;
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param pos1
* @param pos2
* @param priority
*/
public ProtectedCuboidRegion(String id, BlockVector min, BlockVector max) {
super(id);
this.min = min;
this.max = max;
}
/**
* Get the lower point of the cuboid.
*
* @return min point
*/
public BlockVector getMinimumPoint() {
return min;
}
/**
* Set the lower point of the cuboid.
*
* @param pt
*/
public void setMinimumPoint(BlockVector pt) {
min = pt;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
public BlockVector getMaximumPoint() {
return max;
}
/**
* Set the upper point of the cuboid.
*
* @param pt
*/
public void setMaximumPoint(BlockVector pt) {
max = pt;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
int x = pt.getBlockX();
int y = pt.getBlockY();
int z = pt.getBlockZ();
return x >= min.getBlockX() && x <= max.getBlockX()
&& y >= min.getBlockY() && y <= max.getBlockY()
&& z >= min.getBlockZ() && z <= max.getBlockZ();
}
/**
* Return the type of region as a user-friendly name.
*
* @return type of region
*/
public String getTypeName() {
return "cuboid";
}
}
@@ -1,112 +0,0 @@
// $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;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* An interface for getting, setting, and looking up regions. The most
* simple implementation uses a flat list and iterates through the entire
* list to look for applicable regions, but a more complicated (and more
* efficient) implementation may use space partitioning techniques.
*
* @author sk89q
*/
public interface RegionManager {
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String, ProtectedRegion> getRegions();
/**
* Set a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions);
/**
* Adds a region.
*
* @param id
* @param region
*/
public void addRegion(ProtectedRegion region);
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
public boolean hasRegion(String id);
/**
* Get a region by its ID.
*
* @param id
*/
public ProtectedRegion getRegion(String id);
/**
* Removes a region, including inheriting children.
*
* @param id
*/
public void removeRegion(String id);
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
public ApplicableRegionSet getApplicableRegions(Vector pt);
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
public List<String> getApplicableRegionsIDs(Vector pt);
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param region
* @param player
* @return
*/
public boolean overlapsUnownedRegion(ProtectedRegion region, LocalPlayer player);
/**
* Get the number of regions.
*
* @return
*/
public int size();
}
@@ -1,40 +1,41 @@
// $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;
import java.util.Comparator;
class DescendingPriorityComparator implements Comparator<ProtectedRegion> {
/**
* Compares two regions.
*
* @param other
* @return
*/
public int compare(ProtectedRegion r1, ProtectedRegion r2) {
if (r1.getPriority() == r2.getPriority()) {
return 0;
} else if (r1.getPriority() > r2.getPriority()) {
return -1;
} else {
return 1;
}
}
}
// $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;
/**
*
* @author Redecouverte
*/
public class TimedFlagPlayerInfo {
public long lastHealTick;
public Long sheduledHealTick;
public int sheduledHealAmount;
public String lastRegion;
public String lastFarewellMsg;
public TimedFlagPlayerInfo()
{
this.sheduledHealTick = null;
this.lastRegion = null;
this.lastFarewellMsg = null;
}
}
@@ -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.protection;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
/**
* Timer for handling flags that require a constant timer..
*
* @author Michael
*/
public class TimedFlagsTimer implements Runnable {
private WorldGuardPlugin plugin;
private Map<String, TimedFlagPlayerInfo> playerData;
/**
* Construct the object.
*
* @param plugin
*/
public TimedFlagsTimer(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.playerData = new HashMap<String, TimedFlagPlayerInfo>();
}
private TimedFlagPlayerInfo getPlayerInfo(String name) {
TimedFlagPlayerInfo ret = playerData.get(name);
if (ret == null) {
ret = new TimedFlagPlayerInfo();
playerData.put(name, ret);
}
return ret;
}
public void run() {
/*
// get players
Player[] players = plugin.getServer().getOnlinePlayers();
for (Player player : players) {
TimedFlagPlayerInfo nfo = getPlayerInfo(player.getName());
long now = System.currentTimeMillis();
// check healing flag
if (nfo.sheduledHealTick != null && now >= nfo.sheduledHealTick) {
player.setHealth(player.getHealth() + nfo.sheduledHealAmount);
nfo.sheduledHealTick = null;
nfo.lastHealTick = now;
}
if (player.getWorld().getName() == null) {
continue;
}
RegionManager mgr = plugin.getGlobalRegionManager().get(
player.getWorld().getName());
ApplicableRegionSet regions = mgr
.getApplicableRegions(toVector(player.getLocation()));
Integer healDelay = regions.getFlag(DefaultFlag.HEAL_DELAY);
if (healDelay > 0) {
healDelay *= 1000;
int healAmount = regions.getIntegerFlag(
DefaultFlag.HEAL_AMOUNT, true).getValue(1);
if (now - nfo.lastHealTick > healDelay) {
if (player.getHealth() < 20) {
if (player.getHealth() + healAmount > 20) {
player.setHealth(20);
} else {
player.setHealth(player.getHealth() + healAmount);
}
}
} else {
nfo.sheduledHealTick = now + healDelay;
nfo.sheduledHealAmount = healAmount;
}
}
// check greeting/farewell flag
String newRegionName = regions.getAffectedRegionId();
if (newRegionName != null) {
if (nfo.lastRegion == null
|| !newRegionName.equals(nfo.lastRegion)) {
String newGreetMsg = regions.getStringFlag(
DefaultFlag.GREET_MESSAGE, true).getValue();
String farewellMsg = regions.getStringFlag(
DefaultFlag.FAREWELL_MESSAGE, true).getValue();
if (nfo.lastFarewellMsg != null) {
player.sendMessage(nfo.lastFarewellMsg);
nfo.lastFarewellMsg = null;
}
if (newGreetMsg != null) {
player.sendMessage(newGreetMsg);
}
if (regions.getBooleanFlag(DefaultFlag.NOTIFY_GREET, false)
.getValue(false)) {
broadcastNotification(ChatColor.YELLOW + "Player "
+ player.getName() + " entered region "
+ newRegionName);
}
nfo.lastFarewellMsg = farewellMsg;
nfo.lastRegion = newRegionName;
}
} else {
if (nfo.lastRegion != null) {
if (nfo.lastFarewellMsg != null) {
player.sendMessage(nfo.lastFarewellMsg);
nfo.lastFarewellMsg = null;
}
if (regions.getBooleanFlag(DefaultFlag.NOTIFY_FAREWELL,
false).getValue(false)) {
broadcastNotification(ChatColor.YELLOW + "Player "
+ player.getName() + " left region "
+ nfo.lastRegion);
}
nfo.lastRegion = null;
}
}
// check passthrough flag
LocalPlayer lplayer = BukkitPlayer.wrapPlayer(plugin, player);
if (!regions.isStateFlagAllowed(DefaultFlag.PASSTHROUGH, lplayer)) {
Location newLoc = player.getLocation().clone();
newLoc.setX(newLoc.getBlockX() - 30);
newLoc.setY(newLoc.getWorld().getHighestBlockYAt(newLoc) + 1);
player.teleportTo(newLoc);
}
}*/
}
public void broadcastNotification(String msg) {
for (Player player : plugin.getServer().getOnlinePlayers()) {
if (plugin.hasPermission(player, "notify_onenter")) {
player.sendMessage(msg);
}
}
}
}
@@ -0,0 +1,47 @@
// $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.databases;
import java.io.IOException;
import com.sk89q.worldguard.protection.managers.RegionManager;
public abstract class AbstractProtectionDatabase implements ProtectionDatabase {
/**
* Load the list of regions into a region manager.
*
* @throws IOException
*/
public void load(RegionManager manager) throws IOException {
load();
manager.setRegions(getRegions());
}
/**
* Save the list of regions from a region manager.
*
* @throws IOException
*/
public void save(RegionManager manager) throws IOException {
setRegions(manager.getRegions());
save();
}
}
@@ -17,8 +17,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
package com.sk89q.worldguard.protection.databases;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -27,12 +31,11 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
import com.sk89q.worldguard.protection.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.ArrayReader;
/**
@@ -40,7 +43,7 @@ import com.sk89q.worldguard.util.ArrayReader;
*
* @author sk89q
*/
public class CSVDatabase implements ProtectionDatabase {
public class CSVDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
@@ -67,46 +70,7 @@ public class CSVDatabase implements ProtectionDatabase {
*/
@Override
public void save() throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(file));
try {
for (Map.Entry<String,ProtectedRegion> entry : regions.entrySet()) {
String id = entry.getKey();
ProtectedRegion region = entry.getValue();
if (!(region instanceof ProtectedCuboidRegion)) {
logger.warning("The CSV database only supports cuboid regions.");
continue;
}
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion)region;
BlockVector min = cuboid.getMinimumPoint();
BlockVector max = cuboid.getMaximumPoint();
writer.writeNext(new String[] {
id,
"cuboid.2",
String.valueOf(min.getBlockX()),
String.valueOf(min.getBlockY()),
String.valueOf(min.getBlockZ()),
String.valueOf(max.getBlockX()),
String.valueOf(max.getBlockY()),
String.valueOf(max.getBlockZ()),
String.valueOf(cuboid.getPriority()),
cuboid.getParent() != null ? cuboid.getParent().getId() : "",
writeDomains(cuboid.getOwners()),
writeDomains(cuboid.getMembers()),
writeFlags(cuboid.getFlags()),
cuboid.getEnterMessage() != null ? cuboid.getEnterMessage() : "",
cuboid.getLeaveMessage() != null ? cuboid.getLeaveMessage() : "",
});
}
} finally {
try {
writer.close();
} catch (IOException e) {
}
}
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
@@ -130,7 +94,7 @@ public class CSVDatabase implements ProtectionDatabase {
continue;
}
String id = line[0].toLowerCase();
String id = line[0].toLowerCase().replace(".", "");
String type = line[1];
ArrayReader<String> entries = new ArrayReader<String>(line);
@@ -155,13 +119,12 @@ public class CSVDatabase implements ProtectionDatabase {
int priority = entries.get(8) == null ? 0 : Integer.parseInt(entries.get(8));
String ownersData = entries.get(9);
String flagsData = entries.get(10);
String enterMessage = nullEmptyString(entries.get(11));
//String enterMessage = nullEmptyString(entries.get(11));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
region.setFlags(parseFlags(flagsData));
parseFlags(region, flagsData);
region.setOwners(this.parseDomains(ownersData));
region.setEnterMessage(enterMessage);
regions.put(id, region);
} else if (type.equalsIgnoreCase("cuboid.2")) {
Vector pt1 = new Vector(
@@ -181,16 +144,14 @@ public class CSVDatabase implements ProtectionDatabase {
String ownersData = entries.get(10);
String membersData = entries.get(11);
String flagsData = entries.get(12);
String enterMessage = nullEmptyString(entries.get(13));
String leaveMessage = nullEmptyString(entries.get(14));
//String enterMessage = nullEmptyString(entries.get(13));
//String leaveMessage = nullEmptyString(entries.get(14));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
region.setFlags(parseFlags(flagsData));
parseFlags(region, flagsData);
region.setOwners(this.parseDomains(ownersData));
region.setMembers(this.parseDomains(membersData));
region.setEnterMessage(enterMessage);
region.setLeaveMessage(leaveMessage);
regions.put(id, region);
// Link children to parents later
@@ -222,26 +183,6 @@ public class CSVDatabase implements ProtectionDatabase {
this.regions = regions;
}
/**
* Load the list of regions into a region manager.
*
* @throws IOException
*/
public void load(RegionManager manager) throws IOException {
load();
manager.setRegions(regions);
}
/**
* Save the list of regions from a region manager.
*
* @throws IOException
*/
public void save(RegionManager manager) throws IOException {
regions = manager.getRegions();
save();
}
/**
* Used to parse the specified domain in the CSV file.
@@ -290,14 +231,12 @@ public class CSVDatabase implements ProtectionDatabase {
* Used to parse the list of flags.
*
* @param data
* @return
*/
private AreaFlags parseFlags(String data) {
private void parseFlags(ProtectedRegion region, String data) {
if (data == null) {
return new AreaFlags();
return;
}
AreaFlags flags = new AreaFlags();
State curState = State.ALLOW;
for (int i = 0; i < data.length(); i++) {
@@ -307,31 +246,38 @@ public class CSVDatabase implements ProtectionDatabase {
} else if (k == '-') {
curState = State.DENY;
} else {
String flag;
String flagStr;
if (k == '_') {
if (i == data.length() - 1) {
logger.warning("_ read ahead fail");
break;
}
flag = "_" + data.charAt(i + 1);
flagStr = "_" + data.charAt(i + 1);
i++;
logger.warning("_? custom flags are no longer supported");
continue;
} else {
flag = String.valueOf(k);
flagStr = String.valueOf(k);
}
StateFlag flag = DefaultFlag.getLegacyFlag(flagStr);
if (flag != null) {
region.setFlag(flag, curState);
} else {
logger.warning("Legacy flag '" + flagStr + "' is unsupported");
}
flags.set(flag, curState);
}
}
return flags;
}
/**
* Used to write the list of domains.
*
* @param domain
* @return
*/
private String writeDomains(DefaultDomain domain) {
/* private String writeDomains(DefaultDomain domain) {
StringBuilder str = new StringBuilder();
for (String player : domain.getPlayers()) {
@@ -344,7 +290,7 @@ public class CSVDatabase implements ProtectionDatabase {
return str.length() > 0 ?
str.toString().substring(0, str.length() - 1) : "";
}
}*/
/**
* Helper method to prepend '+' or '-' in front of a flag according
@@ -354,6 +300,7 @@ public class CSVDatabase implements ProtectionDatabase {
* @param flag
* @return
*/
/*
private String writeFlag(State state, String flag) {
if (state == State.ALLOW) {
return "+" + flag;
@@ -363,14 +310,15 @@ public class CSVDatabase implements ProtectionDatabase {
return "";
}
*/
/**
* Returns a null if a string is null or empty.
*
* @param str
* @return
*/
private String nullEmptyString(String str) {
protected String nullEmptyString(String str) {
if (str == null) {
return null;
} else if (str.length() == 0) {
@@ -379,20 +327,6 @@ public class CSVDatabase implements ProtectionDatabase {
return str;
}
}
/**
* Used to write the list of flags.
*
* @param flags
* @return
*/
private String writeFlags(AreaFlags flags) {
StringBuilder str = new StringBuilder();
for (Map.Entry<String, State> entry : flags.entrySet()) {
str.append(writeFlag(entry.getValue(), entry.getKey()));
}
return str.toString();
}
/**
* Get a list of protected regions.
@@ -405,8 +339,6 @@ public class CSVDatabase implements ProtectionDatabase {
/**
* Get a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = regions;
@@ -1,68 +1,72 @@
// $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;
import java.io.IOException;
import java.util.Map;
/**
* Represents a database to read and write lists of regions from and to.
*
* @author sk89q
*/
public interface ProtectionDatabase {
/**
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws IOException
*/
public void load() throws IOException;
/**
* Save the list of regions.
*
* @throws IOException
*/
public void save() throws IOException;
/**
* Load the list of regions into a region manager.
*
* @throws IOException
*/
public void load(RegionManager manager) throws IOException;
/**
* Save the list of regions from a region manager.
*
* @throws IOException
*/
public void save(RegionManager manager) throws IOException;
/**
* Get a list of regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions();
/**
* Set the list of regions.
*
* @param regions
*/
public void setRegions(Map<String,ProtectedRegion> regions);
}
// $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.databases;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.io.IOException;
import java.util.Map;
/**
* Represents a database to read and write lists of regions from and to.
*
* @author sk89q
*/
public interface ProtectionDatabase {
/**
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws IOException
*/
public void load() throws IOException;
/**
* Save the list of regions.
*
* @throws IOException
*/
public void save() throws IOException;
/**
* Load the list of regions into a region manager.
*
* @param manager
* @throws IOException
*/
public void load(RegionManager manager) throws IOException;
/**
* Save the list of regions from a region manager.
*
* @param manager
* @throws IOException
*/
public void save(RegionManager manager) throws IOException;
/**
* Get a list of regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions();
/**
* Set the list of regions.
*
* @param regions
*/
public void setRegions(Map<String,ProtectedRegion> regions);
}
@@ -0,0 +1,100 @@
// $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.databases;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldguard.domains.DefaultDomain;
/**
* Various utility functions for parsing region databases.
*
* @author sk89q
*/
public class RegionDBUtil {
private static Pattern groupPattern = Pattern.compile("^[gG]:(.+)$");
private RegionDBUtil() {
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
*/
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);
}
}
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
*/
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);
}
}
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
*/
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;
}
}
@@ -0,0 +1,287 @@
// $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.databases;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.yaml.Configuration;
import com.sk89q.worldguard.util.yaml.ConfigurationNode;
public class YAMLDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private Configuration config;
private Map<String, ProtectedRegion> regions;
public YAMLDatabase(File file) {
config = new Configuration(file);
}
@Override
public void load() throws IOException {
config.load();
Map<String, ConfigurationNode> regionData = config.getNodes("regions");
// No regions are even configured
if (regionData == null) {
this.regions = new HashMap<String, ProtectedRegion>();
return;
}
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
for (Map.Entry<String, ConfigurationNode> entry : regionData.entrySet()) {
String id = entry.getKey().toLowerCase().replace(".", "");
ConfigurationNode node = entry.getValue();
String type = node.getString("type");
ProtectedRegion region;
try {
if (type == null) {
logger.warning("Undefined region type for region '" + id + '"');
continue;
} else if (type.equals("cuboid")) {
Vector pt1 = checkNonNull(node.getVector("min"));
Vector pt2 = checkNonNull(node.getVector("max"));
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
region = new ProtectedCuboidRegion(id, min, max);
} else if (type.equals("poly2d")) {
Integer minY = checkNonNull(node.getInt("min-y"));
Integer maxY = checkNonNull(node.getInt("max-y"));
List<BlockVector2D> points = node.getBlockVector2dList("points", null);
region = new ProtectedPolygonalRegion(id, points, minY, maxY);
} else if (type.equals("global")) {
region = new GlobalProtectedRegion(id);
} else {
logger.warning("Unknown region type for region '" + id + '"');
continue;
}
Integer priority = checkNonNull(node.getInt("priority"));
region.setPriority(priority);
setFlags(region, node.getNode("flags"));
region.setOwners(parseDomain(node.getNode("owners")));
region.setMembers(parseDomain(node.getNode("members")));
regions.put(id, region);
String parentId = node.getString("parent");
if (parentId != null) {
parentSets.put(region, parentId);
}
} catch (NullPointerException e) {
logger.warning("Missing data for region '" + id + '"');
}
}
// Relink parents
for (Map.Entry<ProtectedRegion, String> entry : parentSets.entrySet()) {
ProtectedRegion parent = regions.get(entry.getValue());
if (parent != null) {
try {
entry.getKey().setParent(parent);
} catch (CircularInheritanceException e) {
logger.warning("Circular inheritance detect with '"
+ entry.getValue() + "' detected as a parent");
}
} else {
logger.warning("Unknown region parent: " + entry.getValue());
}
}
this.regions = regions;
}
private <V> V checkNonNull(V val) throws NullPointerException {
if (val == null) {
throw new NullPointerException();
}
return val;
}
private void setFlags(ProtectedRegion region, ConfigurationNode flagsData) {
if (flagsData == null) {
return;
}
// @TODO: Make this better
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object o = flagsData.getProperty(flag.getName());
if (o != null) {
setFlag(region, flag, o);
}
}
}
private <T> void setFlag(ProtectedRegion region, Flag<T> flag, Object rawValue) {
T val = flag.unmarshal(rawValue);
if (val == null) {
logger.warning("Failed to parse flag '" + flag.getName()
+ "' with value '" + rawValue.toString() + "'");
return;
}
region.setFlag(flag, val);
}
private DefaultDomain parseDomain(ConfigurationNode node) {
if (node == null) {
return new DefaultDomain();
}
DefaultDomain domain = new DefaultDomain();
for (String name : node.getStringList("players", null)) {
domain.addPlayer(name);
}
for (String name : node.getStringList("groups", null)) {
domain.addGroup(name);
}
return domain;
}
@Override
public void save() throws IOException {
config.clear();
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
ProtectedRegion region = entry.getValue();
ConfigurationNode node = config.addNode("regions." + entry.getKey());
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
node.setProperty("type", "cuboid");
node.setProperty("min", cuboid.getMinimumPoint());
node.setProperty("max", cuboid.getMaximumPoint());
} else if (region instanceof ProtectedPolygonalRegion) {
ProtectedPolygonalRegion poly = (ProtectedPolygonalRegion) region;
node.setProperty("type", "poly2d");
node.setProperty("min-y", poly.getMinimumPoint().getBlockY());
node.setProperty("max-y", poly.getMaximumPoint().getBlockY());
List<Map<String, Object>> points = new ArrayList<Map<String,Object>>();
for (BlockVector2D point : poly.getPoints()) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("x", point.getBlockX());
data.put("z", point.getBlockZ());
points.add(data);
}
node.setProperty("points", points);
} else if (region instanceof GlobalProtectedRegion) {
node.setProperty("type", "global");
} else {
node.setProperty("type", region.getClass().getCanonicalName());
}
node.setProperty("priority", region.getPriority());
node.setProperty("flags", getFlagData(region));
node.setProperty("owners", getDomainData(region.getOwners()));
node.setProperty("members", getDomainData(region.getMembers()));
ProtectedRegion parent = region.getParent();
if (parent != null) {
node.setProperty("parent", parent.getId());
}
}
config.save();
}
private Map<String, Object> getFlagData(ProtectedRegion region) {
Map<String, Object> flagData = new HashMap<String, Object>();
for (Map.Entry<Flag<?>, Object> entry : region.getFlags().entrySet()) {
Flag<?> flag = entry.getKey();
addMarshalledFlag(flagData, flag, entry.getValue());
}
return flagData;
}
@SuppressWarnings("unchecked")
private <V> void addMarshalledFlag(Map<String, Object> flagData,
Flag<V> flag, Object val) {
if (val == null) {
return;
}
flagData.put(flag.getName(), flag.marshal((V) val));
}
private Map<String, Object> getDomainData(DefaultDomain domain) {
Map<String, Object> domainData = new HashMap<String, Object>();
setDomainData(domainData, "players", domain.getPlayers());
setDomainData(domainData, "groups", domain.getGroups());
return domainData;
}
private void setDomainData(Map<String, Object> domainData,
String key, Set<String> domain) {
if (domain.size() == 0) {
return;
}
List<String> list = new ArrayList<String>();
for (String str : domain) {
list.add(str);
}
domainData.put(key, list);
}
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = regions;
}
}
@@ -0,0 +1,70 @@
// $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 org.bukkit.command.CommandSender;
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) {
super(name);
}
@Override
public Boolean parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes")
|| input.equalsIgnoreCase("on")
|| input.equalsIgnoreCase("1")) {
return true;
} else if (input.equalsIgnoreCase("false") || input.equalsIgnoreCase("no")
|| input.equalsIgnoreCase("off")
|| input.equalsIgnoreCase("0")) {
return false;
} else {
throw new InvalidFlagFormat("Not a yes/no value: " + input);
}
}
@Override
public Boolean unmarshal(Object o) {
if (o instanceof Boolean) {
return (Boolean) o;
} else {
return null;
}
}
@Override
public Object marshal(Boolean o) {
return o;
}
}
@@ -0,0 +1,86 @@
// $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;
/**
*
* @author sk89q
*/
public final class DefaultFlag {
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", 'z', false);
public static final StateFlag BUILD = new StateFlag("build", 'b', true);
public static final StateFlag PVP = new StateFlag("pvp", 'p', true);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", 'm', true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", 'c', 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 CHEST_ACCESS = new StateFlag("chest-access", 'C', 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", false);
public static final StateFlag PLACE_VEHICLE = new StateFlag("vehicle-place", false);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_GREET = new BooleanFlag("notify-greet");
public static final BooleanFlag NOTIFY_FAREWELL = new BooleanFlag("notify-farewell");
public static final StringFlag DENY_SPAWN = new StringFlag("deny-spawn");
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final VectorFlag TELE_LOC = new VectorFlag("teleport");
public static final RegionGroupFlag TELE_PERM = new RegionGroupFlag("teleport-group");
public static final VectorFlag SPAWN_LOC = new VectorFlag("spawn");
public static final RegionGroupFlag SPAWN_PERM = new RegionGroupFlag("spawn-group");
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, PVP, MOB_DAMAGE, CREEPER_EXPLOSION,
TNT, LIGHTER, FIRE_SPREAD, LAVA_FIRE, CHEST_ACCESS, WATER_FLOW, LAVA_FLOW,
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_GREET,
NOTIFY_FAREWELL, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE
};
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;
}
}
@@ -0,0 +1,63 @@
// $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 org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class DoubleFlag extends Flag<Double> {
public DoubleFlag(String name, char legacyCode) {
super(name, legacyCode);
}
public DoubleFlag(String name) {
super(name);
}
@Override
public Double parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
throw new InvalidFlagFormat("Not a number: " + input);
}
}
@Override
public Double unmarshal(Object o) {
if (o instanceof Double) {
return (Double) o;
} else {
return null;
}
}
@Override
public Object marshal(Double o) {
return o;
}
}
@@ -0,0 +1,58 @@
// $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 org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
* @param <T>
*/
public abstract class Flag<T> {
private String name;
private Character legacyCode;
public Flag(String name, char legacyCode) {
this.name = name;
this.legacyCode = legacyCode;
}
public Flag(String name) {
this.name = name;
this.legacyCode = null;
}
public String getName() {
return name;
}
public Character getLegacyCode() {
return legacyCode;
}
public abstract T parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat;
public abstract T unmarshal(Object o);
public abstract Object marshal(T o);
}
@@ -0,0 +1,63 @@
// $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 org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class IntegerFlag extends Flag<Integer> {
public IntegerFlag(String name, char legacyCode) {
super(name, legacyCode);
}
public IntegerFlag(String name) {
super(name);
}
@Override
public Integer parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new InvalidFlagFormat("Not a number: " + input);
}
}
@Override
public Integer unmarshal(Object o) {
if (o instanceof Integer) {
return (Integer) o;
} else {
return null;
}
}
@Override
public Object marshal(Integer o) {
return o;
}
}
@@ -17,15 +17,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
package com.sk89q.worldguard.protection.flags;
/**
* Used for default flags.
*
* @author sk89q
*/
public class GlobalFlags {
public boolean canBuild = true;
public boolean canAccessChests = false;
public boolean canPvP = true;
public class InvalidFlagFormat extends Exception {
private static final long serialVersionUID = 8101615074524004172L;
public InvalidFlagFormat(String msg) {
super(msg);
}
}
@@ -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.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static enum RegionGroup {
MEMBERS,
OWNERS
}
public RegionGroupFlag(String name, char legacyCode) {
super(name, legacyCode);
}
public RegionGroupFlag(String name) {
super(name);
}
@Override
public RegionGroup parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (input.equalsIgnoreCase("members") || input.equalsIgnoreCase("member")) {
return RegionGroup.MEMBERS;
} else if (input.equalsIgnoreCase("owners") || input.equalsIgnoreCase("owner")) {
return RegionGroup.OWNERS;
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
}
}
@Override
public RegionGroup unmarshal(Object o) {
String str = o.toString();
if (str.equalsIgnoreCase("members")) {
return RegionGroup.MEMBERS;
} else if (str.equalsIgnoreCase("owners")) {
return RegionGroup.OWNERS;
} else {
return null;
}
}
@Override
public Object marshal(RegionGroup o) {
if (o == RegionGroup.MEMBERS) {
return "members";
} else if (o == RegionGroup.OWNERS) {
return "owners";
} else {
return null;
}
}
}
@@ -0,0 +1,90 @@
// $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 org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class StateFlag extends Flag<StateFlag.State> {
public enum State {
ALLOW,
DENY
}
private boolean def;
public StateFlag(String name, char legacyCode, boolean def) {
super(name, legacyCode);
this.def = def;
}
public StateFlag(String name, boolean def) {
super(name);
this.def = def;
}
public boolean getDefault() {
return def;
}
@Override
public State parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (input.equalsIgnoreCase("allow")) {
return State.ALLOW;
} else if (input.equalsIgnoreCase("deny")) {
return State.DENY;
} else if (input.equalsIgnoreCase("none")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
}
}
@Override
public State unmarshal(Object o) {
String str = o.toString();
if (str.equalsIgnoreCase("allow")) {
return State.ALLOW;
} else if (str.equalsIgnoreCase("deny")) {
return State.DENY;
} else {
return null;
}
}
@Override
public Object marshal(State o) {
if (o == State.ALLOW) {
return "allow";
} else if (o == State.DENY) {
return "deny";
} else {
return null;
}
}
}
@@ -0,0 +1,58 @@
// $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 org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class StringFlag extends Flag<String> {
public StringFlag(String name, char legacyCode) {
super(name, legacyCode);
}
public StringFlag(String name) {
super(name);
}
@Override
public String parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
return input;
}
@Override
public String unmarshal(Object o) {
if (o instanceof String) {
return (String) o;
} else {
return null;
}
}
@Override
public Object marshal(String o) {
return o;
}
}
@@ -0,0 +1,96 @@
// $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.command.CommandSender;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.BukkitUtil;
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) {
super(name);
}
@Override
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());
}
}
@Override
public Vector unmarshal(Object o) {
if (o instanceof Map) {
Map<?, ?> map = (Map<?, ?>) o;
Object rawX = map.get("x");
Object rawY = map.get("y");
Object rawZ = map.get("z");
if (rawX == null || rawY == null || rawZ == null) {
return null;
}
return new Vector(toNumber(rawX), toNumber(rawY), toNumber(rawZ));
}
return null;
}
@Override
public Object marshal(Vector o) {
Map<String, Object> vec = new HashMap<String, Object>();
vec.put("x", o.getX());
vec.put("y", o.getY());
vec.put("z", o.getZ());
return vec;
}
private double toNumber(Object o) {
if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof Long) {
return (Long) o;
} else if (o instanceof Float) {
return (Float) o;
} else if (o instanceof Double) {
return (Double) o;
} else {
return 0;
}
}
}
@@ -0,0 +1,266 @@
// $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.managers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import java.util.Iterator;
/**
* A very simple implementation of the region manager that uses a flat list
* and iterates through the list to identify applicable regions. This method
* is not very efficient.
*
* @author sk89q
*/
public class FlatRegionManager extends RegionManager {
/**
* List of protected regions.
*/
private Map<String, ProtectedRegion> regions;
/**
* Construct the manager.
*
* @param 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());
regions.remove(id.toLowerCase());
if (region != null) {
List<String> removeRegions = new ArrayList<String>();
Iterator<ProtectedRegion> iter = regions.values().iterator();
while (iter.hasNext()) {
ProtectedRegion curRegion = iter.next();
if (curRegion.getParent() == region) {
removeRegions.add(curRegion.getId().toLowerCase());
}
}
for (String remId : removeRegions) {
removeRegion(remId);
}
}
}
/**
* 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) {
PriorityQueue<ProtectedRegion> appRegions =
new PriorityQueue<ProtectedRegion>();
for (ProtectedRegion region : regions.values()) {
if (region.contains(pt)) {
appRegions.add(region);
}
}
return new ApplicableRegionSet(appRegions, regions.get("__global__"));
}
/**
* Get an object for a region for rules to be applied with.
*
* @return
*/
/*@Override
public ApplicableRegionSet getApplicableRegions(ProtectedRegion checkRegion) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
appRegions.addAll(regions.values());
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (Exception e) {
intersectRegions = new ArrayList<ProtectedRegion>();
}
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>();
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().contains(pt)) {
applicable.add(entry.getKey());
}
}
return applicable;
}
/**
* Get an object for a region for rules to be applied with.
*
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(ProtectedRegion checkRegion) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
appRegions.addAll(regions.values());
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (Exception e) {
intersectRegions = new ArrayList<ProtectedRegion>();
}
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>();
for (ProtectedRegion other : regions.values()) {
if (other.getOwners().contains(player)) {
continue;
}
appRegions.add(other);
}
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (UnsupportedIntersectionException e) {
intersectRegions = new ArrayList<ProtectedRegion>();
}
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
}
@Override
public int getRegionCountOfPlayer(LocalPlayer player) {
int count = 0;
for (ProtectedRegion region : regions.values()) {
if (region.getOwners().contains(player)) {
count++;
}
}
return count;
}
}
@@ -0,0 +1,260 @@
// $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.managers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
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.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegionMBRConverter;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import java.io.IOException;
import java.util.Iterator;
public class PRTreeRegionManager extends RegionManager {
private static final int BRANCH_FACTOR = 30;
/**
* List of protected regions.
*/
private Map<String, ProtectedRegion> regions;
/**
* Converter to get coordinates of the tree.
*/
private MBRConverter<ProtectedRegion> converter = new ProtectedRegionMBRConverter();
/**
* Priority R-tree.
*/
private PRTree<ProtectedRegion> tree;
/**
* Construct the manager.
*
* @param regionloader
* @throws IOException
*/
public PRTreeRegionManager(ProtectionDatabase regionloader) throws IOException {
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);
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
tree.load(regions.values());
}
/**
* Adds a region.
*
* @param region
*/
@Override
public void addRegion(ProtectedRegion region) {
regions.put(region.getId().toLowerCase(), region);
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
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());
regions.remove(id.toLowerCase());
if (region != null) {
List<String> removeRegions = new ArrayList<String>();
Iterator<ProtectedRegion> iter = regions.values().iterator();
while (iter.hasNext()) {
ProtectedRegion curRegion = iter.next();
if (curRegion.getParent() == region) {
removeRegions.add(curRegion.getId().toLowerCase());
}
}
for (String remId : removeRegions) {
removeRegion(remId);
}
}
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) {
PriorityQueue<ProtectedRegion> appRegions =
new PriorityQueue<ProtectedRegion>();
int x = pt.getBlockX();
int z = pt.getBlockZ();
for (ProtectedRegion region : tree.find(x, z, x, z)) {
if (region.contains(pt)) {
appRegions.add(region);
}
}
return new ApplicableRegionSet(appRegions, regions.get("__global__"));
}
@Override
public ApplicableRegionSet getApplicableRegions(ProtectedRegion checkRegion) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
appRegions.addAll(regions.values());
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (Exception e) {
intersectRegions = new ArrayList<ProtectedRegion>();
}
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>();
int x = pt.getBlockX();
int z = pt.getBlockZ();
for (ProtectedRegion region : tree.find(x, z, x, z)) {
if (region.contains(pt)) {
applicable.add(region.getId());
}
}
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>();
for (ProtectedRegion other : regions.values()) {
if (other.getOwners().contains(player)) {
continue;
}
appRegions.add(other);
}
List<ProtectedRegion> intersectRegions;
try {
intersectRegions = checkRegion.getIntersectingRegions(appRegions);
} catch (Exception e) {
intersectRegions = new ArrayList<ProtectedRegion>();
}
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
}
@Override
public int getRegionCountOfPlayer(LocalPlayer player) {
int count = 0;
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().getOwners().contains(player)) {
count++;
}
}
return count;
}
}
@@ -0,0 +1,164 @@
// $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.managers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* An abstract class for getting, setting, and looking up regions. The most
* simple implementation uses a flat list and iterates through the entire list
* to look for applicable regions, but a more complicated (and more efficient)
* implementation may use space partitioning techniques.
*
* @author sk89q
*/
public abstract class RegionManager {
protected ProtectionDatabase loader;
/**
* Construct the object.
*
* @param loader
*/
public RegionManager(ProtectionDatabase loader) {
this.loader = loader;
}
/**
* Load the list of regions.
*
* @throws IOException
*/
public void load() throws IOException {
loader.load(this);
}
/**
* Save the list of regions.
*
* @throws IOException
*/
public void save() throws IOException {
loader.save(this);
}
/**
* Get a list of protected regions.
*
* @return
*/
public abstract Map<String, ProtectedRegion> getRegions();
/**
* Set a list of protected regions.
*
* @param regions
*/
public abstract void setRegions(Map<String, ProtectedRegion> regions);
/**
* Adds a region.
*
* @param region
*/
public abstract void addRegion(ProtectedRegion region);
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
public abstract boolean hasRegion(String id);
/**
* Get a region by its ID.
*
* @param id
* @return
*/
public abstract ProtectedRegion getRegion(String id);
/**
* Removes a region, including inheriting children.
*
* @param id
*/
public abstract void removeRegion(String id);
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
public abstract ApplicableRegionSet getApplicableRegions(Vector pt);
/**
* Get an object for a point for rules to be applied with.
*
* @param region
* @return
*/
public abstract ApplicableRegionSet getApplicableRegions(
ProtectedRegion region);
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
public abstract List<String> getApplicableRegionsIDs(Vector pt);
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param region
* @param player
* @return
*/
public abstract boolean overlapsUnownedRegion(ProtectedRegion region,
LocalPlayer player);
/**
* Get the number of regions.
*
* @return
*/
public abstract int size();
/**
* Get the number of regions for a player.
*
* @param player
* @return
*/
public abstract int getRegionCountOfPlayer(LocalPlayer player);
}
@@ -0,0 +1,66 @@
// $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.regions;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
public class GlobalProtectedRegion extends ProtectedRegion {
public GlobalProtectedRegion(String id) {
super(id);
}
@Override
public BlockVector getMinimumPoint() {
return new BlockVector(0, 0, 0);
}
@Override
public BlockVector getMaximumPoint() {
return new BlockVector(0, 0, 0);
}
@Override
public int volume() {
return 0;
}
@Override
public boolean contains(Vector pt) {
return false;
}
@Override
public String getTypeName() {
return "global";
}
@Override
public List<ProtectedRegion> getIntersectingRegions(
List<ProtectedRegion> regions)
throws UnsupportedIntersectionException {
return new ArrayList<ProtectedRegion>();
}
}
@@ -0,0 +1,283 @@
// $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.regions;
import com.sk89q.worldedit.*;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a cuboid region that can be protected.
*
* @author sk89q
*/
public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Store the first point.
*/
private BlockVector min;
/**
* Store the second point.
*/
private BlockVector max;
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param min
* @param max
*/
public ProtectedCuboidRegion(String id, BlockVector min, BlockVector max) {
super(id);
this.min = min;
this.max = max;
}
/**
* Get the lower point of the cuboid.
*
* @return min point
*/
@Override
public BlockVector getMinimumPoint() {
return min;
}
/**
* Set the lower point of the cuboid.
*
* @param pt
*/
public void setMinimumPoint(BlockVector pt) {
min = pt;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
@Override
public BlockVector getMaximumPoint() {
return max;
}
/**
* Set the upper point of the cuboid.
*
* @param pt
*/
public void setMaximumPoint(BlockVector pt) {
max = pt;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
int x = pt.getBlockX();
int y = pt.getBlockY();
int z = pt.getBlockZ();
return x >= min.getBlockX() && x <= max.getBlockX()
&& y >= min.getBlockY() && y <= max.getBlockY()
&& z >= min.getBlockZ() && z <= max.getBlockZ();
}
/*
public boolean intersectsWith(ProtectedRegion region) throws UnsupportedIntersectionException {
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion r1 = (ProtectedCuboidRegion) this;
ProtectedCuboidRegion r2 = (ProtectedCuboidRegion) region;
BlockVector min1 = r1.getMinimumPoint();
BlockVector max1 = r1.getMaximumPoint();
BlockVector min2 = r2.getMinimumPoint();
BlockVector max2 = r2.getMaximumPoint();
return !(min1.getBlockX() > max2.getBlockX()
|| min1.getBlockY() > max2.getBlockY()
|| min1.getBlockZ() > max2.getBlockZ()
|| max1.getBlockX() < min2.getBlockX()
|| max1.getBlockY() < min2.getBlockY()
|| max1.getBlockZ() < min2.getBlockZ());
} else if (region instanceof ProtectedPolygonalRegion) {
throw new UnsupportedIntersectionException();
} else {
throw new UnsupportedIntersectionException();
}
}
*/
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the regions points are inside the other region
if (region.contains(new Vector(min.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), min.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(min.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), max.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), max.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), min.getBlockZ()))
|| region.contains(new Vector(max.getBlockX(), min.getBlockY(), max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i < ((ProtectedPolygonalRegion)region).getPoints().size(); i++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
List<BlockVector2D> points = new ArrayList<BlockVector2D>();
points.add(new BlockVector2D(min.getBlockX(), min.getBlockZ()));
points.add(new BlockVector2D(min.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), max.getBlockZ()));
points.add(new BlockVector2D(max.getBlockX(), min.getBlockZ()));
for (i2 = 0; i2 < points.size(); i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (points.size() - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = min.getBlockY(); i3 <= max.getBlockY(); i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
}
}
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;
}
}
@@ -0,0 +1,309 @@
// $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.regions;
import java.util.List;
import java.util.ArrayList;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
public class ProtectedPolygonalRegion extends ProtectedRegion {
protected List<BlockVector2D> points;
protected int minY;
protected int maxY;
private BlockVector min;
private BlockVector max;
public ProtectedPolygonalRegion(String id, List<BlockVector2D> points, int minY, int maxY) {
super(id);
this.points = points;
this.minY = minY;
this.maxY = maxY;
int minX = points.get(0).getBlockX();
int minZ = points.get(0).getBlockZ();
int maxX = points.get(0).getBlockX();
int maxZ = points.get(0).getBlockZ();
for (BlockVector2D v : points) {
int x = v.getBlockX();
int z = v.getBlockZ();
if (x < minX) {
minX = x;
}
if (z < minZ) {
minZ = z;
}
if (x > maxX) {
maxX = x;
}
if (z > maxZ) {
maxZ = z;
}
}
min = new BlockVector(minX, minY, minZ);
max = new BlockVector(maxX, maxY, maxZ);
}
public List<BlockVector2D> getPoints() {
return points;
}
@Override
public BlockVector getMinimumPoint() {
return min;
}
@Override
public BlockVector getMaximumPoint() {
return max;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
int targetX = pt.getBlockX(); //wide
int targetY = pt.getBlockY(); //height
int targetZ = pt.getBlockZ(); //depth
if (targetY < minY || targetY > maxY) {
return false;
}
//Quick and dirty check.
if (targetX < min.getBlockX() || targetX > max.getBlockX() || targetZ < min.getBlockZ() || targetZ > max.getBlockZ()) {
return false;
}
boolean inside = false;
int npoints = points.size();
int xNew, zNew;
int xOld, zOld;
int x1, z1;
int x2, z2;
int i;
xOld = points.get(npoints - 1).getBlockX();
zOld = points.get(npoints - 1).getBlockZ();
for (i = 0; i < npoints; i++) {
xNew = points.get(i).getBlockX();
zNew = points.get(i).getBlockZ();
//Check for corner
if (xNew == targetX && zNew == targetZ) {
return true;
}
if (xNew > xOld) {
x1 = xOld;
x2 = xNew;
z1 = zOld;
z2 = zNew;
} else {
x1 = xNew;
x2 = xOld;
z1 = zNew;
z2 = zOld;
}
if ((xNew < targetX) == (targetX <= xOld)
&& ((long) targetZ - (long) z1) * (long) (x2 - x1) <= ((long) z2 - (long) z1)
* (long) (targetX - x1)) {
inside = !inside;
}
xOld = xNew;
zOld = zNew;
}
return inside;
}
@Override
public List<ProtectedRegion> getIntersectingRegions(List<ProtectedRegion> regions) throws UnsupportedIntersectionException {
int numRegions = regions.size();
int numPoints = points.size();
List<ProtectedRegion> intersectingRegions = new ArrayList<ProtectedRegion>();
int i, i2, i3;
for (i = 0; i < numRegions; i++) {
ProtectedRegion region = regions.get(i);
BlockVector rMinPoint = region.getMinimumPoint();
BlockVector rMaxPoint = region.getMaximumPoint();
// Check whether the region is outside the min and max vector
if ((rMinPoint.getBlockX() < min.getBlockX() && rMaxPoint.getBlockX() < min.getBlockX())
|| (rMinPoint.getBlockX() > max.getBlockX() && rMaxPoint.getBlockX() > max.getBlockX())
&& ((rMinPoint.getBlockY() < min.getBlockY() && rMaxPoint.getBlockY() < min.getBlockY())
|| (rMinPoint.getBlockY() > max.getBlockY() && rMaxPoint.getBlockY() > max.getBlockY()))
&& ((rMinPoint.getBlockZ() < min.getBlockZ() && rMaxPoint.getBlockZ() < min.getBlockZ())
|| (rMinPoint.getBlockZ() > max.getBlockZ() && rMaxPoint.getBlockZ() > max.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
// Check whether the regions points are inside the other region
for (i2 = 0; i < numPoints; i++) {
Vector pt = new Vector(points.get(i2).getBlockX(), minY, points.get(i2).getBlockZ());
Vector pt2 = new Vector(points.get(i2).getBlockX(), maxY, points.get(i2).getBlockZ());
if (region.contains(pt) || region.contains(pt2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
// Check whether the other regions points are inside the current region
if (region instanceof ProtectedPolygonalRegion) {
for (i2 = 0; i < ((ProtectedPolygonalRegion)region).getPoints().size(); i++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
continue;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
// Check whether the current regions edges collide with the regions edges
boolean regionIsIntersecting = false;
for (i2 = 0; i2 < numPoints; i2++) {
boolean checkNextPoint = false;
BlockVector2D currPoint = points.get(i2);
BlockVector2D nextPoint;
if (i2 == (numPoints - 1)) {
nextPoint = points.get(0);
} else {
nextPoint = points.get(i2 + 1);
}
int currX = currPoint.getBlockX();
int currZ = currPoint.getBlockZ();
while (!checkNextPoint) {
for(i3 = this.minY; i3 <= this.maxY; i3++) {
if (region.contains(new Vector(currX, i3, currZ))) {
intersectingRegions.add(regions.get(i));
regionIsIntersecting = true;
break;
}
}
if (currX == nextPoint.getBlockX() || currZ == nextPoint.getBlockZ() || regionIsIntersecting) {
checkNextPoint = true;
}
if (nextPoint.getBlockX() > currPoint.getBlockX()) {
currX++;
} else {
currX--;
}
if (nextPoint.getBlockZ() > currPoint.getBlockZ()) {
currZ++;
} else {
currZ--;
}
}
if (regionIsIntersecting) {
break;
}
}
}
return intersectingRegions;
}
/**
* Return the type of region as a user-friendly name.
*
* @return type of region
*/
@Override
public String getTypeName() {
return "polygon";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int volume = 0;
int numPoints = points.size();
if (numPoints < 3) {
return 0;
}
double area = 0;
int xa, za, z1, z2;
for (int i = 0; i <= numPoints - 1; i++) {
xa = points.get(i).getBlockX();
za = points.get(i).getBlockZ();
if (points.get(i + 1) == null) {
z1 = points.get(0).getBlockZ();
} else {
z1 = points.get(i + 1).getBlockZ();
}
if (points.get(i - 1) == null) {
z2 = points.get(numPoints - 1).getBlockZ();
} else {
z2 = points.get(i - 1).getBlockZ();
}
area = area + (xa * (z1 - z2));
}
xa = points.get(0).getBlockX();
za = points.get(0).getBlockZ();
area = area + (xa * (points.get(1).getBlockZ() - points.get(numPoints - 1).getBlockZ()));
volume = (Math.abs(maxY - minY) + 1) * (int) Math.ceil((Math.abs(area) / 2));
return volume;
}
}
@@ -1,320 +1,339 @@
// $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;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
/**
* Represents a region of any shape and size that can be protected.
*
* @author sk89q
*/
public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Holds the region's ID.
*/
private String id;
/**
* Priority.
*/
private int priority = 0;
/**
* Parent region.
*/
private ProtectedRegion parent;
/**
* List of owners.
*/
private DefaultDomain owners = new DefaultDomain();
/**
* List of members.
*/
private DefaultDomain members = new DefaultDomain();
/**
* Area flags.
*/
private AreaFlags flags = new AreaFlags();
/**
* Area message.
*/
private String enterMessage;
/**
* Area message.
*/
private String leaveMessage;
/**
* Construct a new instance of this region.
*
* @param id
*/
public ProtectedRegion(String id) {
this.id = id;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the priority
*/
public int getPriority() {
return priority;
}
/**
* @param priority the priority to set
*/
public void setPriority(int priority) {
this.priority = priority;
}
/**
* @return the parent
*/
public ProtectedRegion getParent() {
return parent;
}
/**
* Set the parent. This checks to make sure that it will not result
* in circular inheritance.
*
* @param parent the parent to set
* @throws CircularInheritanceException
*/
public void setParent(ProtectedRegion parent) throws CircularInheritanceException {
if (parent == null) {
this.parent = null;
return;
}
if (parent == this) {
throw new CircularInheritanceException();
}
ProtectedRegion p = parent.getParent();
while (p != null) {
if (p == this) {
throw new CircularInheritanceException();
}
p = p.getParent();
}
this.parent = parent;
}
/**
* Se flags.
* @param flags
*/
public void setFlags(AreaFlags flags) {
this.flags = flags;
}
/**
* @return the enterMessage
*/
public String getEnterMessage() {
return enterMessage;
}
/**
* @param enterMessage the enterMessage to set
*/
public void setEnterMessage(String enterMessage) {
this.enterMessage = enterMessage;
}
/**
* @return the leaveMessage
*/
public String getLeaveMessage() {
return leaveMessage;
}
/**
* @param leaveMessage the leaveMessage to set
*/
public void setLeaveMessage(String leaveMessage) {
this.leaveMessage = leaveMessage;
}
/**
* @return the owners
*/
public DefaultDomain getOwners() {
return owners;
}
/**
* @param owners the owners to set
*/
public void setOwners(DefaultDomain owners) {
this.owners = owners;
}
/**
* @return the members
*/
public DefaultDomain getMembers() {
return members;
}
/**
* @param owners the owners to set
*/
public void setMembers(DefaultDomain members) {
this.members = members;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param player
* @return
*/
public boolean isOwner(LocalPlayer player) {
if (owners.contains(player)) {
return true;
}
ProtectedRegion parent = getParent();
while (parent != null) {
if (parent.getOwners().contains(player)) {
return true;
}
parent = parent.getParent();
}
return false;
}
/**
* Checks whether a player is a member of the region or any of its parents.
*
* @param player
* @return
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
return true;
}
ProtectedRegion parent = getParent();
while (parent != null) {
if (parent.getOwners().contains(player)
|| parent.getMembers().contains(player)) {
return true;
}
parent = parent.getParent();
}
return false;
}
/**
* Get flags.
*
* @return
*/
public AreaFlags getFlags() {
return flags;
}
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
*/
public abstract boolean contains(Vector pt);
/**
* Compares to another region.
*
* @param other
* @return
*/
public int compareTo(ProtectedRegion other) {
if (priority == other.priority) {
return 0;
} else if (priority > other.priority) {
return -1;
} else {
return 1;
}
}
/**
* Return the type of region as a user-friendly, lowercase name.
*
* @return type of region
*/
public abstract String getTypeName();
/**
* Checks if two region intersects.
*
* @param region1
* @param region2
* @throws UnsupportedIntersectionException
* @return
*/
public static boolean intersects(ProtectedRegion region1, ProtectedRegion region2)
throws UnsupportedIntersectionException {
if (region1 instanceof ProtectedCuboidRegion
&& region2 instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion r1 = (ProtectedCuboidRegion)region1;
ProtectedCuboidRegion r2 = (ProtectedCuboidRegion)region2;
BlockVector min1 = r1.getMinimumPoint();
BlockVector max1 = r1.getMaximumPoint();
BlockVector min2 = r2.getMinimumPoint();
BlockVector max2 = r2.getMaximumPoint();
return !(min1.getBlockX() > max2.getBlockX()
|| min1.getBlockY() > max2.getBlockY()
|| min1.getBlockZ() > max2.getBlockZ()
|| max1.getBlockX() < min2.getBlockX()
|| max1.getBlockY() < min2.getBlockY()
|| max1.getBlockZ() < min2.getBlockZ());
} else {
throw new UnsupportedIntersectionException();
}
}
/**
* Thrown when setting a parent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
}
}
// $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.regions;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.flags.Flag;
import java.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.
*
* @author sk89q
*/
public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
private static final Pattern idPattern = Pattern.compile("^[A-Za-z0-9_,'\\-\\+/]{1,}$");
/**
* Holds the region's ID.
*/
private String id;
/**
* Priority.
*/
private int priority = 0;
/**
* Holds the curParent.
*/
private ProtectedRegion parent;
/**
* List of owners.
*/
private DefaultDomain owners = new DefaultDomain();
/**
* List of members.
*/
private DefaultDomain members = new DefaultDomain();
/**
* List of flags.
*/
private Map<Flag<?>, Object> flags = new HashMap<Flag<?>, Object>();
/**
* Construct a new instance of this region.
*
* @param id
*/
public ProtectedRegion(String id) {
this.id = id;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* Get the lower point of the cuboid.
*
* @return min point
*/
public abstract BlockVector getMinimumPoint();
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
public abstract BlockVector getMaximumPoint();
/**
* @return the priority
*/
public int getPriority() {
return priority;
}
/**
* @param priority the priority to setFlag
*/
public void setPriority(int priority) {
this.priority = priority;
}
/**
* @return the curParent
*/
public ProtectedRegion getParent() {
return parent;
}
/**
* Set the curParent. This checks to make sure that it will not result
* in circular inheritance.
*
* @param parent the curParent to setFlag
* @throws CircularInheritanceException
*/
public void setParent(ProtectedRegion parent) throws CircularInheritanceException {
if (parent == null) {
this.parent = null;
return;
}
if (parent == this) {
throw new CircularInheritanceException();
}
ProtectedRegion p = parent.getParent();
while (p != null) {
if (p == this) {
throw new CircularInheritanceException();
}
p = p.getParent();
}
this.parent = parent;
}
/**
* @return the owners
*/
public DefaultDomain getOwners() {
return owners;
}
/**
* @param owners the owners to setFlag
*/
public void setOwners(DefaultDomain owners) {
this.owners = owners;
}
/**
* @return the members
*/
public DefaultDomain getMembers() {
return members;
}
/**
* @param members the members to setFlag
*/
public void setMembers(DefaultDomain members) {
this.members = members;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param player
* @return
*/
public boolean isOwner(LocalPlayer player) {
if (owners.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is a member of the region or any of its parents.
*
* @param player
* @return
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)
|| curParent.getMembers().contains(player)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Get a flag's value.
*
* @param <T>
* @param <V>
* @param flag
* @return value or null if isn't defined
*/
@SuppressWarnings("unchecked")
public <T extends Flag<V>, V> V getFlag(T flag) {
Object obj = flags.get(flag);
V val;
if (obj != null) {
val = (V) obj;
} else {
return null;
}
return val;
}
/**
* Set a flag's value.
*
* @param <T>
* @param <V>
* @param flag
* @param val
*/
public <T extends Flag<V>, V> void setFlag(T flag, V val) {
if (val == null) {
flags.remove(flag);
} else {
flags.put(flag, val);
}
}
/**
* Get the map of flags.
*
* @return
*/
public Map<Flag<?>, Object> getFlags() {
return flags;
}
/**
* Get the map of flags.
*
* @param flags
*/
public void setFlags(Map<Flag<?>, Object> flags) {
this.flags = flags;
}
/**
* Get the number of blocks in this region
*
* @return
*/
public abstract int volume();
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
*/
public abstract boolean contains(Vector pt);
/**
* Compares to another region.
*
* @param other
* @return
*/
public int compareTo(ProtectedRegion other) {
if (priority == other.priority) {
return 0;
} else if (priority > other.priority) {
return -1;
} else {
return 1;
}
}
/**
* Return the type of region as a user-friendly, lowercase name.
*
* @return type of region
*/
public abstract String getTypeName();
public abstract List<ProtectedRegion> getIntersectingRegions(
List<ProtectedRegion> regions)
throws UnsupportedIntersectionException;
/**
* Checks to see if the given ID is accurate.
*
* @param id
* @return
*/
public static boolean isValidId(String id) {
return idPattern.matcher(id).matches();
}
/**
* Thrown when setting a curParent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
}
}
@@ -0,0 +1,41 @@
// $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.regions;
import org.khelekore.prtree.MBRConverter;
public class ProtectedRegionMBRConverter implements MBRConverter<ProtectedRegion> {
public double getMinX(ProtectedRegion t) {
return t.getMinimumPoint().getBlockX();
}
public double getMinY(ProtectedRegion t) {
return t.getMinimumPoint().getBlockZ();
}
public double getMaxX(ProtectedRegion t) {
return t.getMaximumPoint().getBlockX();
}
public double getMaxY(ProtectedRegion t) {
return t.getMaximumPoint().getBlockZ();
}
}
@@ -0,0 +1,132 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class PastebinPoster {
private static final int CONNECT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 5000;
public static void paste(String code, PasteCallback callback) {
PasteProcessor processor = new PasteProcessor(code, callback);
Thread thread = new Thread(processor);
thread.start();
}
public static interface PasteCallback {
public void handleSuccess(String url);
public void handleError(String err);
}
private static class PasteProcessor implements Runnable {
private String code;
private PasteCallback callback;
public PasteProcessor(String code, PasteCallback callback) {
this.code = code;
this.callback = callback;
}
@Override
public void run() {
HttpURLConnection conn = null;
OutputStream out = null;
InputStream in = null;
try {
URL url = new URL("http://pastebin.com/api/api_post.php");
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-type",
"application/x-www-form-urlencoded");
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
out = conn.getOutputStream();
out.write(("api_option=paste"
+ "&api_dev_key=" + URLEncoder.encode("4867eae74c6990dbdef07c543cf8f805", "utf-8")
+ "&api_paste_code=" + URLEncoder.encode(code, "utf-8")
+ "&api_paste_private=" + URLEncoder.encode("0", "utf-8")
+ "&api_paste_name=" + URLEncoder.encode("", "utf-8")
+ "&api_paste_expire_date=" + URLEncoder.encode("1H", "utf-8")
+ "&api_paste_format=" + URLEncoder.encode("text", "utf-8")
+ "&api_user_key=" + URLEncoder.encode("", "utf-8")).getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200) {//Get Response
in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append("\r\n");
}
reader.close();
String result = response.toString().trim();
if (result.matches("^https?://.*")) {
callback.handleSuccess(result.trim());
} else {
String err =result.trim();
if (err.length() > 100) {
err = err.substring(0, 100);
}
callback.handleError(err);
}
} else {
callback.handleError("didn't get a 200 response code!");
}
} catch (IOException e) {
callback.handleError(e.getMessage());
} finally {
if (conn != null) {
conn.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
}
}
@@ -0,0 +1,100 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldguard.domains.DefaultDomain;
/**
* Various utility functions for regions.
*
* @author sk89q
*/
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
*/
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);
}
}
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
*/
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);
}
}
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
*/
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;
}
}
@@ -0,0 +1,156 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import com.sk89q.worldguard.util.yaml.ConfigurationException;
import com.sk89q.worldguard.util.yaml.ConfigurationNode;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.representer.Representer;
/**
* YAML configuration loader. To use this class, construct it with path to
* a file and call its load() method. For specifying node paths in the
* various get*() methods, they support SK's path notation, allowing you to
* select child nodes by delimiting node names with periods.
*
* <p>
* For example, given the following configuration file:</p>
*
* <pre>members:
* - Hollie
* - Jason
* - Bobo
* - Aya
* - Tetsu
* worldguard:
* fire:
* spread: false
* blocks: [cloth, rock, glass]
* sturmeh:
* cool: false
* eats:
* babies: true</pre>
*
* <p>Calling code could access sturmeh's baby eating state by using
* <code>getBoolean("sturmeh.eats.babies", false)</code>. For lists, there are
* methods such as <code>getStringList</code> that will return a type safe list.
*
* <p>This class is currently incomplete. It is not yet possible to get a node.
* </p>
*
* @author sk89q
*/
public class Configuration extends ConfigurationNode {
private Yaml yaml;
private File file;
public Configuration(File file) {
super(new HashMap<String, Object>());
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
yaml = new Yaml(new SafeConstructor(), new Representer(), options);
this.file = file;
}
/**
* Loads the configuration file.
*
* @throws IOException
*/
public void load() throws IOException {
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
read(yaml.load(new UnicodeReader(stream)));
} catch (ConfigurationException e) {
root = new HashMap<String, Object>();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
}
}
}
/**
* Saves the configuration to disk.
*
* @throws IOException
*/
public void save() throws IOException {
FileOutputStream stream = null;
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
try {
stream = new FileOutputStream(file);
yaml.dump(root, new OutputStreamWriter(stream, "UTF-8"));
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
}
}
}
@SuppressWarnings("unchecked")
private void read(Object input) throws ConfigurationException {
try {
if ( null == input ) {
root = new HashMap<String, Object>();
} else {
root = (Map<String, Object>)input;
}
} catch (ClassCastException e) {
throw new ConfigurationException("Root document must be an key-value structure");
}
}
/**
* This method returns an empty ConfigurationNode for using as a
* default in methods that select a node from a node list.
* @return
*/
public static ConfigurationNode getEmptyNode() {
return new ConfigurationNode(new HashMap<String, Object>());
}
}
@@ -0,0 +1,37 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
/**
* Configuration exception.
*
* @author sk89q
*/
public class ConfigurationException extends Exception {
private static final long serialVersionUID = -2442886939908724203L;
public ConfigurationException() {
super();
}
public ConfigurationException(String msg) {
super(msg);
}
}
@@ -0,0 +1,795 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.util.yaml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.Vector2D;
import com.sk89q.worldguard.util.yaml.ConfigurationNode;
/**
* Represents a configuration node.
*
* @author sk89q
*/
public class ConfigurationNode {
protected Map<String, Object> root;
protected ConfigurationNode(Map<String, Object> root) {
this.root = root;
}
/**
* Clear all nodes.
*/
public void clear() {
root.clear();
}
/**
* Gets a property at a location. This will either return an Object
* or null, with null meaning that no configuration value exists at
* that location. This could potentially return a default value (not yet
* implemented) as defined by a plugin, if this is a plugin-tied
* configuration.
*
* @param path path to node (dot notation)
* @return object or null
*/
@SuppressWarnings("unchecked")
public Object getProperty(String path) {
if (!path.contains(".")) {
Object val = root.get(path);
if (val == null) {
return null;
}
return val;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
if (o == null) {
return null;
}
if (i == parts.length - 1) {
return o;
}
try {
node = (Map<String, Object>)o;
} catch (ClassCastException e) {
return null;
}
}
return null;
}
/**
* Prepare a value for serialization, in case it's not a native type
* (and we don't want to serialize objects as YAML objects).
*
* @param value
* @return
*/
private Object prepareSerialization(Object value) {
if (value instanceof Vector) {
Map<String, Double> out = new HashMap<String, Double>();
Vector vec = (Vector) value;
out.put("x", vec.getX());
out.put("y", vec.getY());
out.put("z", vec.getZ());
return out;
}
return value;
}
/**
* Set the property at a location. This will override existing
* configuration data to have it conform to key/value mappings.
*
* @param path
* @param value
*/
@SuppressWarnings("unchecked")
public void setProperty(String path, Object value) {
value = prepareSerialization(value);
if (!path.contains(".")) {
root.put(path, value);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.put(parts[i], value);
return;
}
if (o == null || !(o instanceof Map)) {
// This will override existing configuration data!
o = new HashMap<String, Object>();
node.put(parts[i], o);
}
node = (Map<String, Object>)o;
}
}
/**
* Adds a new node to the given path. The returned object is a reference
* to the new node. This method will replace an existing node at
* the same path. See <code>setProperty</code>.
*
* @param path
* @return
*/
public ConfigurationNode addNode(String path) {
Map<String, Object> map = new HashMap<String, Object>();
ConfigurationNode node = new ConfigurationNode(map);
setProperty(path, map);
return node;
}
/**
* Gets a string at a location. This will either return an String
* or null, with null meaning that no configuration value exists at
* that location. If the object at the particular location is not actually
* a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or null
*/
public String getString(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
}
return o.toString();
}
/**
* Gets a vector at a location. This will either return an Vector
* or a null. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or default
*/
public Vector getVector(String path) {
ConfigurationNode o = getNode(path);
if (o == null) {
return null;
}
Double x = o.getDouble("x");
Double y = o.getDouble("y");
Double z = o.getDouble("z");
if (x == null || y == null || z == null) {
return null;
}
return new Vector(x, y, z);
}
/**
* Gets a 2D vector at a location. This will either return an Vector
* or a null. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or default
*/
public Vector2D getVector2d(String path) {
ConfigurationNode o = getNode(path);
if (o == null) {
return null;
}
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
return null;
}
return new Vector2D(x, z);
}
/**
* Gets a string at a location. This will either return an Vector
* or the default value. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @param def default value
* @return string or default
*/
public Vector getVector(String path, Vector def) {
Vector v = getVector(path);
if (v == null) {
setProperty(path, def);
return def;
}
return v;
}
/**
* Gets a string at a location. This will either return an String
* or the default value. If the object at the particular location is not
* actually a string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @param def default value
* @return string or default
*/
public String getString(String path, String def) {
String o = getString(path);
if (o == null) {
setProperty(path, def);
return def;
}
return o;
}
/**
* Gets an integer at a location. This will either return an integer
* or null. If the object at the particular location is not
* actually a integer, the default value will be returned. However, other
* number types will be casted to an integer.
*
* @param path path to node (dot notation)
* @return integer or null
*/
public Integer getInt(String path) {
Integer o = castInt(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets an integer at a location. This will either return an integer
* or the default value. If the object at the particular location is not
* actually a integer, the default value will be returned. However, other
* number types will be casted to an integer.
*
* @param path path to node (dot notation)
* @param def default value
* @return int or default
*/
public int getInt(String path, int def) {
Integer o = castInt(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Gets a double at a location. This will either return an double
* or null. If the object at the particular location is not
* actually a double, the default value will be returned. However, other
* number types will be casted to an double.
*
* @param path path to node (dot notation)
* @return double or null
*/
public Double getDouble(String path) {
Double o = castDouble(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets a double at a location. This will either return an double
* or the default value. If the object at the particular location is not
* actually a double, the default value will be returned. However, other
* number types will be casted to an double.
*
* @param path path to node (dot notation)
* @param def default value
* @return double or default
*/
public double getDouble(String path, double def) {
Double o = castDouble(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Gets a boolean at a location. This will either return an boolean
* or null. If the object at the particular location is not
* actually a boolean, the default value will be returned.
*
* @param path path to node (dot notation)
* @return boolean or null
*/
public Boolean getBoolean(String path) {
Boolean o = castBoolean(getProperty(path));
if (o == null) {
return null;
} else {
return o;
}
}
/**
* Gets a boolean at a location. This will either return an boolean
* or the default value. If the object at the particular location is not
* actually a boolean, the default value will be returned.
*
* @param path path to node (dot notation)
* @param def default value
* @return boolean or default
*/
public boolean getBoolean(String path, boolean def) {
Boolean o = castBoolean(getProperty(path));
if (o == null) {
setProperty(path, def);
return def;
} else {
return o;
}
}
/**
* Get a list of keys at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return list of keys
*/
@SuppressWarnings("unchecked")
public List<String> getKeys(String path) {
if (path == null) return new ArrayList<String>(root.keySet());
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
return new ArrayList<String>(((Map<String,Object>)o).keySet());
} else {
return null;
}
}
/**
* Gets a list of objects at a location. If the list is not defined,
* null will be returned. The node must be an actual list.
*
* @param path path to node (dot notation)
* @return boolean or default
*/
@SuppressWarnings("unchecked")
public List<Object> getList(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof List) {
return (List<Object>)o;
} else {
return null;
}
}
/**
* Gets a list of strings. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. If an item in the list
* is not a string, it will be converted to a string. The node must be
* an actual list and not just a string.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of strings
*/
public List<String> getStringList(String path, List<String> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<String>();
}
List<String> list = new ArrayList<String>();
for (Object o : raw) {
if (o == null) {
continue;
}
list.add(o.toString());
}
return list;
}
/**
* Gets a list of integers. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and not just an integer.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Integer> getIntList(String path, List<Integer> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Integer>();
}
List<Integer> list = new ArrayList<Integer>();
for (Object o : raw) {
Integer i = castInt(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of doubles. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and cannot be just a double.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Double> getDoubleList(String path, List<Double> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Double>();
}
List<Double> list = new ArrayList<Double>();
for (Object o : raw) {
Double i = castDouble(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of booleans. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual list and cannot be just a boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Boolean> getBooleanList(String path, List<Boolean> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Boolean>();
}
List<Boolean> list = new ArrayList<Boolean>();
for (Object o : raw) {
Boolean tetsu = castBoolean(o);
if (tetsu != null) {
list.add(tetsu);
}
}
return list;
}
/**
* Gets a list of vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Vector> getVectorList(
String path, List<Vector> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<Vector> list = new ArrayList<Vector>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double y = o.getDouble("y");
Double z = o.getDouble("z");
if (x == null || y == null || z == null) {
continue;
}
list.add(new Vector(x, y, z));
}
return list;
}
/**
* Gets a list of 2D vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Vector2D> getVector2dList(
String path, List<Vector2D> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<Vector2D> list = new ArrayList<Vector2D>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
continue;
}
list.add(new Vector2D(x, z));
}
return list;
}
/**
* Gets a list of 2D vectors. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a vector,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<BlockVector2D> getBlockVector2dList(
String path, List<BlockVector2D> def) {
List<ConfigurationNode> raw = getNodeList(path, null);
List<BlockVector2D> list = new ArrayList<BlockVector2D>();
for (ConfigurationNode o : raw) {
Double x = o.getDouble("x");
Double z = o.getDouble("z");
if (x == null || z == null) {
continue;
}
list.add(new BlockVector2D(x, z));
}
return list;
}
/**
* Gets a list of nodes. Non-valid entries will not be in the list.
* There will be no null slots. If the list is not defined, the
* default will be returned. 'null' can be passed for the default
* and an empty list will be returned instead. The node must be
* an actual node and cannot be just a boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
@SuppressWarnings("unchecked")
public List<ConfigurationNode> getNodeList(String path, List<ConfigurationNode> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<ConfigurationNode>();
}
List<ConfigurationNode> list = new ArrayList<ConfigurationNode>();
for (Object o : raw) {
if (o instanceof Map) {
list.add(new ConfigurationNode((Map<String, Object>)o));
}
}
return list;
}
/**
* Get a configuration node at a path. If the node doesn't exist or the
* path does not lead to a node, null will be returned. A node has
* key/value mappings.
*
* @param path
* @return node or null
*/
@SuppressWarnings("unchecked")
public ConfigurationNode getNode(String path) {
Object raw = getProperty(path);
if (raw instanceof Map) {
return new ConfigurationNode((Map<String, Object>)raw);
}
return null;
}
/**
* Get a list of nodes at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return map of nodes
*/
@SuppressWarnings("unchecked")
public Map<String, ConfigurationNode> getNodes(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
Map<String, ConfigurationNode> nodes =
new HashMap<String, ConfigurationNode>();
for (Map.Entry<String, Object> entry : ((Map<String, Object>)o).entrySet()) {
if (entry.getValue() instanceof Map) {
nodes.put(entry.getKey(),
new ConfigurationNode((Map<String, Object>) entry.getValue()));
}
}
return nodes;
} else {
return null;
}
}
/**
* Casts a value to an integer. May return null.
*
* @param o
* @return
*/
private static Integer castInt(Object o) {
if (o == null) {
return null;
} else if (o instanceof Byte) {
return (int)(Byte)o;
} else if (o instanceof Integer) {
return (Integer)o;
} else if (o instanceof Double) {
return (int)(double)(Double)o;
} else if (o instanceof Float) {
return (int)(float)(Float)o;
} else if (o instanceof Long) {
return (int)(long)(Long)o;
} else {
return null;
}
}
/**
* Casts a value to a double. May return null.
*
* @param o
* @return
*/
private static Double castDouble(Object o) {
if (o == null) {
return null;
} else if (o instanceof Float) {
return (double)(Float)o;
} else if (o instanceof Double) {
return (Double)o;
} else if (o instanceof Byte) {
return (double)(Byte)o;
} else if (o instanceof Integer) {
return (double)(Integer)o;
} else if (o instanceof Long) {
return (double)(Long)o;
} else {
return null;
}
}
/**
* Casts a value to a boolean. May return null.
*
* @param o
* @return
*/
private static Boolean castBoolean(Object o) {
if (o == null) {
return null;
} else if (o instanceof Boolean) {
return (Boolean)o;
} else {
return null;
}
}
/**
* Remove the property at a location. This will override existing
* configuration data to have it conform to key/value mappings.
*
* @param path
*/
@SuppressWarnings("unchecked")
public void removeProperty(String path) {
if (!path.contains(".")) {
root.remove(path);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.remove(parts[i]);
return;
}
node = (Map<String, Object>)o;
}
}
}
@@ -75,4 +75,9 @@ public class TestPlayer extends LocalPlayer {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean hasPermission(String perm) {
return true;
}
}
@@ -19,14 +19,21 @@
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.TestPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
import java.util.ArrayList;
public class ApplicableRegionSetTest {
static String COURTYARD_ID = "courtyard";
@@ -40,6 +47,7 @@ public class ApplicableRegionSetTest {
Vector outside = new Vector(15, 15, 15);
Vector inNoFire = new Vector(150, 150, 150);
RegionManager manager;
ProtectedRegion globalRegion;
ProtectedRegion courtyard;
ProtectedRegion fountain;
TestPlayer player1;
@@ -47,7 +55,9 @@ public class ApplicableRegionSetTest {
@Before
public void setUp() throws Exception {
manager = new FlatRegionManager(new GlobalFlags());
setUpGlobalRegion();
manager = new FlatRegionManager(null);
setUpPlayers();
setUpCourtyardRegion();
@@ -64,16 +74,23 @@ public class ApplicableRegionSetTest {
player2.addGroup(MEMBER_GROUP);
}
void setUpGlobalRegion() {
globalRegion = new GlobalProtectedRegion("__global__");
}
void setUpCourtyardRegion() {
DefaultDomain domain = new DefaultDomain();
domain.addGroup(COURTYARD_GROUP);
ProtectedRegion region = new ProtectedCuboidRegion(COURTYARD_ID,
new BlockVector(0, 0, 0), new BlockVector(10, 10, 10));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_BUILD, State.NONE);
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
region.setFlags(flags);
ArrayList<BlockVector2D> points = new ArrayList<BlockVector2D>();
points.add(new BlockVector2D(0, 0));
points.add(new BlockVector2D(10, 0));
points.add(new BlockVector2D(10, 10));
points.add(new BlockVector2D(0, 10));
//ProtectedRegion region = new ProtectedCuboidRegion(COURTYARD_ID, new BlockVector(0, 0, 0), new BlockVector(10, 10, 10));
ProtectedRegion region = new ProtectedPolygonalRegion(COURTYARD_ID, points, 0, 10);
region.setOwners(domain);
manager.addRegion(region);
@@ -86,9 +103,6 @@ public class ApplicableRegionSetTest {
ProtectedRegion region = new ProtectedCuboidRegion(FOUNTAIN_ID,
new BlockVector(0, 0, 0), new BlockVector(5, 5, 5));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.DENY);
region.setFlags(flags);
region.setMembers(domain);
manager.addRegion(region);
@@ -99,29 +113,26 @@ public class ApplicableRegionSetTest {
void setUpNoFireRegion() throws Exception {
ProtectedRegion region = new ProtectedCuboidRegion(NO_FIRE_ID,
new BlockVector(100, 100, 100), new BlockVector(200, 200, 200));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.DENY);
region.setFlags(flags);
manager.addRegion(region);
}
@Test
public void testNonBuildFlag() {
ApplicableRegionSet appl;
/*ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
//assertTrue(appl.isStateFlagAllowed(AreaFlags.FLAG_FIRE_SPREAD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
//assertTrue(appl.isStateFlagAllowed(AreaFlags.FLAG_FIRE_SPREAD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertFalse(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
//assertFalse(appl.isStateFlagAllowed(AreaFlags.FLAG_FIRE_SPREAD));
// Inside no fire zone
appl = manager.getApplicableRegions(inNoFire);
assertFalse(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
//assertFalse(appl.isStateFlagAllowed(AreaFlags.FLAG_FIRE_SPREAD));*/
}
@Test
@@ -19,16 +19,18 @@
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.databases.CSVDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
public class CSVDatabaseTest {
@Before
@@ -63,13 +65,14 @@ public class CSVDatabaseTest {
}
private void checkTestRegion1(ProtectedRegion region) {
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.DENY);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
/* AreaFlags flags = new AreaFlags();
flags.setFlag(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.setFlag(AreaFlags.FLAG_PVP, State.DENY);
flags.setFlag(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
assertEquals(region.getFlags(), flags);
*/
}
private ProtectedRegion getTestRegion1() {
@@ -78,12 +81,12 @@ public class CSVDatabaseTest {
ProtectedRegion region = new ProtectedCuboidRegion("test2", min, max);
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.DENY);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
/* AreaFlags flags = new AreaFlags();
flags.setFlag(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.setFlag(AreaFlags.FLAG_PVP, State.DENY);
flags.setFlag(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
*/
DefaultDomain domain = new DefaultDomain();
domain.addGroup("members");
domain.addGroup("sturmehs");
@@ -92,7 +95,6 @@ public class CSVDatabaseTest {
domain.addPlayer("tetsu");
region.setOwners(domain);
region.setEnterMessage("hello there!");
region.setPriority(444);
return region;
@@ -103,12 +105,13 @@ public class CSVDatabaseTest {
BlockVector max = new BlockVector(10, 11, 12);
ProtectedRegion region = new ProtectedCuboidRegion("test2", min, max);
/*
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.ALLOW);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
flags.setFlag(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.setFlag(AreaFlags.FLAG_PVP, State.ALLOW);
flags.setFlag(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
*/
DefaultDomain domain = new DefaultDomain();
domain.addGroup("admins");
@@ -116,8 +119,7 @@ public class CSVDatabaseTest {
domain.addPlayer("ester");
domain.addPlayer("amy");
region.setOwners(domain);
region.setEnterMessage("Testing");
region.setPriority(555);
return region;