Compare commits

...
519 Commits
Author SHA1 Message Date
sk89q c75b9c2328 [maven-release-plugin] prepare release 5.2.2 2011-06-27 12:09:47 -07:00
sk89q 0863db8cf0 Changed configuration saving so empty lists will be added to the configuration files. 2011-06-27 12:09:03 -07:00
sk89q 53d6a272e6 [maven-release-plugin] prepare for next development iteration 2011-06-27 11:47:48 -07:00
sk89q 71467a7ae7 [maven-release-plugin] prepare release 5.2.1 2011-06-27 11:47:37 -07:00
sk89q 56fa3458ab Updated CHANGELOG.txt for 5.2.1. 2011-06-27 11:37:22 -07:00
sk89q 82e04ac4e5 Changed /region {add|rem}{member|owner} to allow putting owners/members on the global region. 2011-06-27 11:23:33 -07:00
sk89q 564d4442fc Added a bunch of unit tests for regions. 2011-06-27 11:10:20 -07:00
sk89q df8fdd086b Fixed some flag algorithm issues, added the possibility of owners and members on the global region in order to affect build. 2011-06-27 11:10:20 -07:00
sk89q a31476251e Fixed DefaultDomain.size() not counting players. 2011-06-27 11:10:19 -07:00
sk89q 360a655627 Added the ability to add owners/members to the global region for handling guest groups. 2011-06-27 11:10:19 -07:00
sk89q 3b871b9c00 Added more region unit tests. 2011-06-27 11:10:19 -07:00
sk89q 65834a2087 Undeprecated ApplicableRegionSet.allows(StateFlag) 2011-06-27 11:10:19 -07:00
e9d85da691 Merge pull request #107 from Moo0/infobounds
Add region bounds to "/region info"
2011-06-27 09:31:02 -07:00
sk89q cfa78af654 [maven-release-plugin] prepare for next development iteration 2011-06-27 00:00:47 -07:00
sk89q 45d9119150 [maven-release-plugin] prepare release 5.2 2011-06-27 00:00:38 -07:00
sk89q ea487eb6a4 Fixed the %online% macro requiring a player. 2011-06-26 23:41:30 -07:00
sk89q 4e295ea1eb Updated for 5.2. 2011-06-26 23:20:43 -07:00
sk89q 32265414bd Added Javadocs, cleaned up comments. 2011-06-26 23:19:49 -07:00
sk89q 80e706e962 Improved the API. 2011-06-26 22:50:21 -07:00
sk89q 110838715b Gave the ability to use color colors and macros in greeting and farewell messages. 2011-06-26 21:49:34 -07:00
sk89q b90334c8a8 Made WorldGuard catch setHeader() not being yet defined. 2011-06-26 21:49:33 -07:00
sk89q 3ce0530d5f Updated for 5.2. 2011-06-26 21:49:33 -07:00
sk89q 7eaa84d5b1 Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread, disable-snow-melting, disable-ice-formation. 2011-06-26 21:49:32 -07:00
sk89q ad325dfedb Added paintings to blacklist support. 2011-06-26 21:49:32 -07:00
sk89q 5bb7eb6f01 Added default.disable-health-regain. 2011-06-26 21:49:32 -07:00
sk89q 342cfc0801 Added auto-invincible-permission setting, which lets you use the permission 'worldguard.auto-invincible' to become invincible. 2011-06-26 21:49:31 -07:00
sk89q f5c6a9f507 Flames won't appear if you are /god'ed now. 2011-06-26 21:49:31 -07:00
e843ff372e Merge pull request #113 from Moo0/limitoverride
Region limit override permission.
2011-06-26 19:35:40 -07:00
sk89q ed27ffed65 Updated the blacklist with a new ignore-perms option. No more groups! Use permissions! 2011-06-26 18:36:06 -07:00
sk89q 7995ecd867 Updated CHANGELOG.txt. 2011-06-26 17:33:59 -07:00
sk89q fcef6679c4 Updated README.html. 2011-06-26 16:48:51 -07:00
sk89q 742b6a2e27 Made negative healing possible. 2011-06-26 16:39:41 -07:00
sk89q 258fbc8870 Improved the entry/exit flags so that it's harder to break it. Thanks to Siriuo. 2011-06-26 16:29:28 -07:00
sk89q 0fa43ee287 Added a warning about modifying region database files manually. 2011-06-26 15:11:05 -07:00
sk89q fb39261dc7 Fixed floating point inaccuracy in onPlayerMove(). 2011-06-26 14:38:56 -07:00
sk89q 7fce4bf53e Added exit flag to deny exiting a region. 2011-06-26 14:11:11 -07:00
sk89q 13840cf61b Changed the configuration header messages to be more helpful to new users. 2011-06-26 12:59:20 -07:00
sk89q e26f6b5e8d Added 'entry' flag to deny entry. 2011-06-26 12:32:01 -07:00
sk89q 767c49f9fa Added region command whitelisting and the bypass for command checks. 2011-06-26 10:45:12 -07:00
sk89q c9178da608 Added command blocking. 2011-06-26 10:40:08 -07:00
sk89q 855bc59a53 [maven-release-plugin] prepare for next development iteration 2011-06-26 03:15:25 -07:00
sk89q 798c22e94b [maven-release-plugin] prepare release 5.1.1 2011-06-26 03:15:15 -07:00
sk89q ea3be11294 Blanked default configuration files. 2011-06-26 03:13:34 -07:00
sk89q 335073b3b0 [maven-release-plugin] prepare for next development iteration 2011-06-26 03:02:11 -07:00
sk89q 2b6ee344b7 [maven-release-plugin] prepare release 5.1 2011-06-26 03:02:02 -07:00
sk89q 8f55b82e2f Updated for 5.1. 2011-06-26 02:52:40 -07:00
sk89q ba9cd1f3e2 Updated the README.html. 2011-06-26 02:52:13 -07:00
sk89q e0e7ae98e7 Changed configuration files to save and also to inherit from the main configuration. 2011-06-26 02:24:50 -07:00
sk89q b05e439da9 Cleaned up pom.xml and updated maven-assembly-plugin to 2.2.1. 2011-06-26 01:31:59 -07:00
sk89q fb5dbbdf58 Removed .gitignore. 2011-06-26 01:28:24 -07:00
sk89q 9cb9dd0a58 Updated the README.html. 2011-06-26 01:27:55 -07:00
sk89q 276d42561e Added more aggressive TNT flag check. 2011-06-26 00:47:58 -07:00
sk89q 44b98165ba Added region protection to sign change event. 2011-06-26 00:24:09 -07:00
sk89q b5088340fd Fixed deny-spawn. 2011-06-25 23:27:01 -07:00
sk89q b7dd63ebd9 Changed event registration to catch errors. 2011-06-25 21:46:14 -07:00
Wizjany ba376a6326 Registering some other new events 'safely' 2011-06-22 21:29:22 -04:00
sk89q 87a43e8e8f Made SNOW_FORM be registered programatically so it can be used on CraftBukkit versions lacking that. 2011-06-22 08:46:37 -07:00
sk89q b62ada53c3 Re-ordered plugin enable process. 2011-06-22 08:43:10 -07:00
sk89q 4f3198b1bd wiz makes a good point -- PROBABLY should not delete players. 2011-06-20 19:35:14 -07:00
sk89q c9f99e0903 Added /stoplag or /halt-activity to cease all intensive operations (such as fire spread, water flow, mob spawning, etc.) and to remove mobs (except wolves) and item drops proactively for those situations when you (or someone else) messes up really badly. 2011-06-20 19:25:05 -07:00
Moo0 3b4c58b721 Add region limit override permission. 2011-06-20 17:22:33 +01:00
Wizjany 6496bbd87f Added config option to disable mob damage for people not using regions 2011-06-15 13:02:59 -04:00
Wizjany 4ad8d362f7 Reverted change to use flag 2011-06-12 14:36:26 -04:00
Wizjany d9aeb6afaa Fixed NPE in last commit 2011-06-11 16:24:06 -04:00
Wizjany d971389746 Prevent players from using bonemeal on grass if they aren't allowed to build in a region 2011-06-11 14:13:46 -04:00
sk89q 233a2bdbe7 Fixed an important bug with the algorithm for handling region priorities. 2011-06-11 01:21:08 -07:00
sk89q 2277183330 Added some more region priority unit tests. 2011-06-11 01:21:08 -07:00
Wizjany b2cd3d31fd Standardizing override permission nodes (with backwards compatibility) 2011-06-10 16:00:14 -04:00
Wizjany 02f6b3be42 Fixed USE flag being DENY in undefined regions 2011-06-10 15:50:03 -04:00
Wizjany 22e84321fc Removed duplicate handling of lighter fire 2011-06-10 01:41:59 -04:00
Wizjany c472dc89ad Changed the way some flags were handled and canceled 2011-06-09 17:02:19 -04:00
Wizjany b89d9d44b0 Now with 99.9% less Unknown Paste ID 2011-06-09 00:12:06 -04:00
Wizjany a2c21f8ceb Made anti-dumb wolf checks only apply to tamed wolves 2011-06-08 23:55:07 -04:00
sk89q e35596b0fa Allowed blocking weapon usage with the blacklist. 2011-06-07 16:08:50 -07:00
Wizjany b95a7f063b Fixed disabling durability resetting things which use durability otherwise 2011-06-07 16:32:43 -04:00
sk89q e4bbd36d47 <= 0 health? It's too late bby 2011-06-06 16:53:11 -07:00
sk89q 9790ab29a2 Now a very proactive (but not still reserved) infinite stack checker. 2011-06-06 14:46:06 -07:00
sk89q 24cc2d3b36 Changed the proactive infinite stack check to occur on inventory open. 2011-06-06 14:35:57 -07:00
sk89q 12779699e3 Improved the infinite item stack remover by making it a bit more proactive. 2011-06-06 14:31:17 -07:00
sk89q 2188690d20 Changed leave messages to be printed BEFORE enter messages. Suggested by Protected. 2011-06-06 11:30:00 -07:00
sk89q 7059fdfd9e Removed old/redundant code. 2011-06-06 11:29:11 -07:00
sk89q 9e1bde4b00 Merge remote-tracking branch 'remotes/origin/master' 2011-06-06 11:15:40 -07:00
sk89q 45790b60b0 Restored the configuration class name change so plugins don't have to be updated. 2011-06-06 11:08:38 -07:00
sk89q c5f3a27d6b Rewrote greeting/farewell and notify-enter/notify-leave flags. 2011-06-05 17:18:27 -07:00
sk89q d9136aa407 Optimized flags scheduler. 2011-06-05 16:38:28 -07:00
sk89q 183f48a998 Rewrote how healing flags were handled. 2011-06-05 16:31:42 -07:00
Wizjany 3c5bc507a5 Added trap doors to USE flag 2011-06-03 18:05:28 -04:00
Wizjany 548dd0365c Fixed another infinite sign... 2011-06-02 19:34:29 -04:00
Wizjany 4591fc603f Added permission nodes as an alternative to wg-invincible and -amphibious groups. 2011-05-31 19:58:12 -04:00
Wizjany 26946feecc Merge leafdecay flag from zml2008 2011-05-27 19:06:38 -04:00
sk89q dd14f3c469 Fixed priorities and parent-child regions, I believe. More testing is required. Removed dated CSVDatabaseTest. 2011-05-26 21:55:23 -07:00
Moo0 69af41f1e5 Remove permission. 2011-05-24 16:25:45 +01:00
sk89q 474562455d Abstracted chest protection. 2011-05-23 23:32:45 -07:00
sk89q c75d612541 Cleaned up code. The configuration classes were also renamed as they did much more than just configuration. 2011-05-23 23:32:44 -07:00
sk89q 8de6ce9868 Cleaned up code from a merge. 2011-05-23 23:30:54 -07:00
sk89q 97bde50708 Fixed some chest protection issues. 2011-05-23 23:30:54 -07:00
sk89q b23e35cf26 Improved chest-sign protection. 2011-05-23 23:30:53 -07:00
sk89q b58e04707d Timer flags timer removed. It will be restored when it gets rewritten to not leak memory and to handle messages better. 2011-05-23 23:30:53 -07:00
MonsieurApple 846cf63268 Merge pull request #109 from wizjany/master
Ghast fireballs and explosion cancelling
2011-05-23 20:04:24 -07:00
Wizjany 4850bdefdf Added config option to disable explosion-caused damage to players. 2011-05-23 22:26:02 -04:00
Wizjany 424b580eb9 Added ghast fireball handling (instead of grouping with tnt) and fixed god mode player ignition. 2011-05-23 22:25:56 -04:00
MonsieurApple 7f8ad468ca Merge pull request #108 from Moo0/derp
Bug in ProtectedCuboidRegion/getIntersectingRegions.
2011-05-23 13:55:05 -07:00
Moo0 e07e2bd7d1 Someone used the wrong variable in a for. 2011-05-23 21:44:02 +01:00
Moo0 7074963fb1 Add region bounds to "/region info" 2011-05-23 19:48:02 +01:00
MonsieurApple 88acbe655d Merge pull request #106 from kuyanatan/master
Fixed config misspell
2011-05-21 11:15:51 -07:00
Natan 903ebc68a4 Worldgurad != worldguard. 2011-05-21 10:48:07 -07:00
MonsieurApple 49bdccf020 Merge pull request #103 from wizjany/master
Fixed some derpy fire handling
2011-05-17 07:05:09 -07:00
MonsieurApple ba3818884d Merge pull request #99 from Moo0/listbyname
Filter "/region list" by user.
2011-05-16 17:11:13 -07:00
MonsieurApple 64ce904ec1 Merge pull request #104 from wizjany/opPerms
Added config for op permissions
2011-05-16 17:09:59 -07:00
Wizjany 8c5f7ef020 Added config for op permissions 2011-05-16 20:03:45 -04:00
Wizjany 98426f6dcc Added config for op permissions 2011-05-16 19:43:04 -04:00
Wizjany f3ec873ac2 Fixed some derpy fire handling. 2011-05-16 16:27:17 -04:00
MonsieurApple 30961483e1 Merge pull request #101 from wizjany/master
Fixed some commands not accepting flags they should
2011-05-14 11:42:01 -07:00
Wizjany 33e0750959 General commands now use flags as intended 2011-05-14 13:19:02 -04:00
MonsieurApple e59a07e232 Merge pull request #100 from wizjany/master
Painting events and snow fall flag
2011-05-13 05:20:20 -07:00
Wizjany 3b05b9be11 Added support for painting and added a flag for snow falling. 2011-05-13 00:37:48 -04:00
Moo0 943bbd9889 Show regions user is member of, as well as those user is owner of. 2011-05-08 18:55:48 +01:00
Moo0 763cf8dbda Add ability to filter '/region list' by user. 2011-05-08 18:44:08 +01:00
sk89q 5117518d8f Cleaned up code, removed OpenCSV code from WorldGuard. Now it's a dependency (that's compiled into the .jar). 2011-05-03 15:36:04 -07:00
sk89q 936996da17 Moved the unit tests to their proper place as recommended by the Maven gods. 2011-05-03 02:07:21 -07:00
sk89q 019a7e59b7 Alright, here's a surprise. Everything is now on Maven. 2011-05-03 02:04:55 -07:00
sk89q 428a47f889 Merge branch 'master' of https://github.com/wizjany/worldguard 2011-05-03 01:31:49 -07:00
Steven Mattera 2be2cb19b2 Uncommented line 445 on WorldGuardEntityListener 2011-05-03 01:30:07 -07:00
Steven Mattera 66ee09d050 Fixed TimedFlagsTimer to enable HEAL_DELAY,HEAL_AMOUNT,GREETING,FAREWELL,NOTIFY_GREET,NOTIFY_FAREWELL, and PASSTHROUGH Flags. 2011-05-03 01:30:07 -07:00
Steven Mattera 906dab28c1 Added MOB_SPAWNING state flag. 2011-05-03 01:30:06 -07:00
6db8e1d842 Merge pull request #94 from yetanotherx/chest-blacklist.
Don't deny placing a blacklisted item if the block clicked is a chest.
2011-05-03 01:32:00 -07:00
Yetanotherx a665e86096 Don't deny placing a blacklisted item if the block clicked is a chest. People often complain that "i was just trying to open my chest" when they were holding water. 2011-04-30 12:26:39 -04:00
sk89q b7481dbd2e Updated config. 2011-04-24 13:14:12 -07:00
Wizjany b1e509c6f8 Updated for 1.5 and added existing lightning protection. 2011-04-25 04:08:28 +08:00
Wizjany 1f69622a34 Added a lot of missing things to player listener. 2011-04-25 04:06:48 +08:00
Wizjany 215b2b5f75 Added config to stop players from trampling crops. Animals don't work yet (blame CraftBukkit) 2011-04-25 04:04:48 +08:00
Wizjany 1e8c91e92f Added override for flint and steel blocking. 2011-04-25 04:04:47 +08:00
Wizjany 19d447d67d Added handling for weather events. Depends on my craftbukkit pull request. 2011-04-24 15:55:26 -04:00
Wizjany 925fa2ee1b Updated for 1.5 and added existing lightning protection. 2011-04-24 15:53:32 -04:00
Wizjany 1cedf0e9a0 Added a lot of missing things to player listener. 2011-04-23 19:50:58 -04:00
Wizjany ca8bb7f5f0 Added config to stop players from trampling crops. Animals don't work yet (blame CraftBukkit) 2011-04-15 00:20:15 -04:00
Wizjany 9e15a4a557 Added override for flint and steel blocking. 2011-04-14 21:17:11 -04:00
sk89q af5d0c4b0e Re-added cake eat blocking on left click. 2011-04-13 03:11:05 -07:00
sk89q 08ab359534 Fixed region priorities, but it needs a test. 2011-04-13 03:07:17 -07:00
Steven Mattera 28c44e0b2f Added MOB_SPAWNING state flag. 2011-04-13 18:07:13 +08:00
Moo0 7038f49a1a Fix for "/region claim" claiming overlapping region when none exists. 2011-04-13 18:05:12 +08:00
sk89q af25c15286 Merge branch 'master' of https://github.com/wizjany/worldguard 2011-04-13 03:00:27 -07:00
sk89q ffc5281d59 Added protection.remove-infinite-stacks. 2011-04-11 12:34:11 -07:00
sk89q ad659cd32e Fixed a major bug with the sign chest protection. It replaced the second line of the sign with "[Lock]". 2011-04-11 11:55:12 -07:00
sk89q afd3cbd311 Added sign chest protection (needed it for my server). Just put [Lock] on the first line and names on the next three. The first name line must be the sign creator's, so you can track who made what. Friend lists are not yet supported. People with names longer than 15 characters (I believe 16 is the max.) are out of luck. 2011-04-11 10:13:42 -07:00
sk89q a5a5f7e24a Made /wg report look better. 2011-04-09 02:25:47 -07:00
sk89q 1e203b58c3 Fixed a bug, partially, regarding unloaded worlds. 2011-04-07 00:22:15 -07:00
Wizjany 104b7c2cf2 Fixed falling into void and wolves still taking damage. Requires Craftbukkit 638+ 2011-04-07 00:35:52 -04:00
Wizjany 355c89ecab Added missing default global config option to file. 2011-04-07 00:35:52 -04:00
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
Wizjany 3cb9b90ef0 Added config to disable damage from falling into the void. 2011-04-03 05:48:32 -04: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
sk89q 541b1dbc44 Updated for 3.2. 2011-01-30 01:38:39 -08:00
sk89q 005ac41820 Added PvP default flag. 2011-01-30 01:36:59 -08:00
sk89q dd93772233 Fixed creeper explosion block with WorldGuard. 2011-01-30 01:16:16 -08:00
sk89q 428fc7e5f6 Fixed commands for the Bukkit commands change. 2011-01-30 01:03:57 -08:00
sk89q 5cf38cc885 Added redstone support to sponges, removed classic water. 2011-01-28 10:23:43 -08:00
sk89q 2f6b51e811 Fixed item durability disable for hoes. 2011-01-28 00:59:19 -08:00
sk89q 2f12da6bc6 Fixed error in a test. 2011-01-28 00:06:58 -08:00
sk89q 3985e157d9 Increased the priority of WorldGuard's event handling. 2011-01-24 09:17:20 -08:00
sk89q 3034eb5c12 Updated CHANGELOG.txt. 2011-01-24 09:12:56 -08:00
sk89q f666f1baa9 Fixed creeper and chest flag conflicting. 2011-01-24 09:12:32 -08:00
sk89q 3bbffa7b55 Updated for 3.1. 2011-01-24 02:40:17 -08:00
sk89q bc774e2596 Added /regionmembership permission. 2011-01-24 02:38:18 -08:00
sk89q 65a0e5c188 Possibly fixed projectile blocking in no-PvP zones. 2011-01-24 02:37:11 -08:00
sk89q 772d2cb580 Added ability to disable chest protection. 2011-01-24 02:35:33 -08:00
sk89q edc6825f83 Added WorldGuardPlugin.getRegionLoader(). 2011-01-22 01:41:18 -08:00
sk89q 7b2f9e0c86 Added Javadoc compilation. 2011-01-22 01:31:57 -08:00
sk89q 0fa4fa1862 Added getRegionManager() to WorldGuardPlugin. 2011-01-22 01:31:48 -08:00
sk89q 5be31ebb5c Fixed /god not working for others. 2011-01-21 19:49:22 -08:00
sk89q 962394b2ba Updated for 3.0b2. 2011-01-21 19:45:41 -08:00
sk89q 7cf7c5f44c Fixed issue where permissions were not loaded. 2011-01-21 19:45:06 -08:00
sk89q 5b494a09ec Fixed permissions for /stack, /locate, and /reloadwg. 2011-01-21 17:53:06 -08:00
sk89q 5cfac5da4a Marked version as beta1. 2011-01-21 15:41:25 -08:00
sk89q 203004951b Updated CHANGELOG.txt. 2011-01-21 15:26:43 -08:00
sk89q 765d7402fa Added parent-child relationships to regions, overhauled region code, added global build flag, improved flag support. 2011-01-21 15:23:11 -08:00
sk89q 151b5fc561 Fixed no-PvP zone messages being sent to the wrong person. 2011-01-21 01:37:40 -08:00
sk89q b489da7fe4 Fixed commands so that they work in a recent version of Bukkit. 2011-01-21 01:32:23 -08:00
sk89q 786a0f6f2b Reduced the number of imports in WorldGuardPlugin. 2011-01-21 01:27:18 -08:00
sk89q e2a940e01b Cleaned up code. 2011-01-21 01:21:36 -08:00
sk89q 518c3be478 Fixed errors in TestPlayer.java. 2011-01-21 01:13:20 -08:00
sk89q 6f3eaac008 Fixed NullPointerException in explode hook. 2011-01-21 00:51:50 -08:00
sk89q 31633e9466 Updated for 2.3.1. 2011-01-20 11:23:56 -08:00
sk89q 02913780ec Fixed the item durability disable setting changing the damage value on an empty hand. 2011-01-20 11:23:13 -08:00
sk89q f03a2263d8 Added checks for unchecked exceptions when resolving permissions. 2011-01-20 11:19:59 -08:00
sk89q a8cd832c28 Fixed various cast exceptions with the blacklist loggers. 2011-01-20 11:16:59 -08:00
sk89q abbced0530 Updated changelog. 2011-01-20 02:09:04 -08:00
sk89q 200e07023f Fixed /locate printing the name of the wrong person. 2011-01-20 02:03:43 -08:00
sk89q 5fdd26b53f Fixed CSVDatabase spitting an error if the owners list was empty. 2011-01-20 02:01:50 -08:00
sk89q 61896ea760 Updated example config.yml. 2011-01-20 01:56:42 -08:00
sk89q b43881c299 Added /locate. 2011-01-20 01:54:47 -08:00
sk89q 6046f4defc Fixed teleport-on-suffocation setting. 2011-01-20 01:07:39 -08:00
sk89q 69ccb9f12b Implemented contact damage and fixed other damage protection. 2011-01-20 00:55:20 -08:00
sk89q 430f2f57e9 Made TNT blocking work. 2011-01-19 23:38:16 -08:00
sk89q c3f0bbb41c Added /heal and /slay. 2011-01-19 23:31:20 -08:00
sk89q 7e481e6a9a Moved commands handling to be Bukkit-compliant. 2011-01-19 23:27:35 -08:00
sk89q 627de1aebd Changed how the player item event was handled. 2011-01-19 22:09:15 -08:00
sk89q 194108336b Updated CHANGELOG.txt. 2011-01-17 19:47:24 -08:00
sk89q eade612981 Fixed WorldGuard not getting group lists for permissions correctly. 2011-01-17 19:45:53 -08:00
sk89q 733163cc4c Updated changelog, readme. 2011-01-17 19:22:04 -08:00
sk89q 86a917ddd1 Added creeper block support. 2011-01-17 18:38:12 -08:00
sk89q e8503aa0b9 Now supports GroupUsers (through WorldEdit). 2011-01-17 17:55:56 -08:00
sk89q 01bf9e8406 Fixed issue where the build process did not make sure that plugin.yml would be updated. 2011-01-17 17:47:07 -08:00
sk89q 0bdadf63b3 Fixed errors in tests. 2011-01-17 17:45:51 -08:00
sk89q 5b1c35bf06 Fixed build file not replacing version macro correctly. 2011-01-17 16:51:04 -08:00
sk89q c467acdfac Updated CHANGELOG.txt for 2.1.1. 2011-01-17 02:55:18 -08:00
sk89q 22167a0a07 Allowed placing WorldEdit.jar as a dependency in WorldGuard/. 2011-01-17 02:53:13 -08:00
sk89q 251647c7a2 Added some priority support. 2011-01-17 02:31:32 -08:00
sk89q 80e9799579 Fixed typo in README.txt. 2011-01-17 00:23:17 -08:00
sk89q 95f49f34d0 Cleaned up code. 2011-01-17 00:19:23 -08:00
sk89q b01b67f64c Cleaned up code. 2011-01-17 00:16:02 -08:00
sk89q 603fb5d2b8 Made /reload WorldGuard work for everyone by default. 2011-01-17 00:13:27 -08:00
sk89q 22f7c347ab Simplified release ZIP. 2011-01-17 00:10:32 -08:00
sk89q 08229ed4f9 Made WorldGuard write default configuration files, more friendly. Removed hMod configuration files. 2011-01-17 00:05:35 -08:00
sk89q a942fd08f5 Fixed NullPointerException related to the player item event. 2011-01-16 23:15:30 -08:00
sk89q c96d534c26 Fixed fire spread disable preventing flint and steel too. 2011-01-16 19:38:29 -08:00
sk89q 789a9a9bb4 Fixed configuration file not being reloaded. 2011-01-16 13:33:23 -08:00
sk89q d2435a8026 Updated supporting documentation. 2011-01-16 13:33:14 -08:00
sk89q 36db436fa3 Implemented temporary permissions. 2011-01-16 12:56:17 -08:00
sk89q 30d9978412 Fixed various issues with regions. 2011-01-16 11:54:03 -08:00
sk89q 5db7f124ac Added region claiming, some fixes. 2011-01-16 10:44:37 -08:00
sk89q c82ee055e7 Updated stack command to use ItemType.usesDamageValue(). 2011-01-16 09:15:16 -08:00
sk89q cb1c1efc35 Moved blacklist message flood logger to Blacklist. 2011-01-16 09:11:42 -08:00
sk89q 0037a4e83f Restored blacklist. 2011-01-16 02:50:41 -08:00
sk89q c369b3c62a Removed item drop blacklist. 2011-01-15 23:50:29 -08:00
sk89q 0934a12205 Updated region protection to support chests. 2011-01-15 23:47:15 -08:00
sk89q d19db5f86f Further progress on the port. 2011-01-15 23:21:27 -08:00
sk89q 5657ee6c90 Progress. 2011-01-15 16:33:21 -08:00
sk89q 41a71d6185 Added Updatr support. 2011-01-12 09:18:09 -08:00
sk89q 11592cd742 2.0beta3 2011-01-12 09:15:44 -08:00
sk89q 43d83d8855 Fixed NullPointerException inside the ignite hook. 2011-01-12 09:15:04 -08:00
sk89q d1cb628473 Updated WorldGuard to catch a missing WorldEdit. 2011-01-10 13:18:28 -08:00
sk89q 44fc802e8b Updated for 2.0beta2. 2011-01-10 13:00:38 -08:00
sk89q bfa1734d23 Fixed the NullPointerException in the damage hook caused by a null attacker. 2011-01-10 13:00:04 -08:00
sk89q 66139dacac Updated for 2.0beta1. 2011-01-08 18:43:19 -08:00
sk89q 714c24445d Updated for 2.0. 2011-01-08 18:41:26 -08:00
sk89q 79f55a02cb Fixed NullPointerExceptions in item use hook. 2011-01-08 18:38:18 -08:00
sk89q 484fe22e9e Finished up regions support. 2011-01-08 18:26:49 -08:00
sk89q 119d8b1a81 Fixed /delarea and allowed it to use its own /delarea permission instead. 2011-01-08 16:42:09 -08:00
sk89q 953d1f0aed Add denial messages to region protection. Changed use-protected-regions to use-regions and turned it on by default. 2011-01-08 16:36:25 -08:00
sk89q 2e225a9452 Removed INVENTORY_CHANGE hook. 2011-01-08 16:35:35 -08:00
sk89q 960dc2cd48 Changed ProtectedCuboidRegion to do its bounds check without Vector. 2011-01-08 16:35:15 -08:00
sk89q 345ac35649 Added area protection code borrowed from WorldEdit. While the framework is currently quite flexible, the implementation still needs work. 2011-01-08 02:04:21 -08:00
sk89q 802114c605 Commented out WorldGuardListener.onInventoryChange(). 2011-01-08 01:33:20 -08:00
sk89q 16bbd30209 Code cleanup. 2010-12-30 00:51:12 -08:00
sk89q 0021e789bc Removed com.sk89q.worldedit.blocks.BlockType. 2010-12-30 00:48:50 -08:00
sk89q 41daebb629 Updated changelog. 2010-12-26 10:32:31 -08:00
sk89q b496e88557 Fixed NullPointerException in WorldGuardListener.onSignChange(). 2010-12-26 10:31:54 -08:00
sk89q 7c0e10d058 Updated build file to copy sample worldguard.properties. 2010-12-25 22:30:27 -08:00
sk89q 1d72447096 Updated default worldguard.properties. 2010-12-25 22:26:58 -08:00
sk89q 01e93a642e Updated for 1.8. 2010-12-25 22:24:57 -08:00
sk89q 696ae7c967 Changed blacklist hooks. 2010-12-25 22:16:45 -08:00
sk89q b28202f1cb Added Ant build file. 2010-12-25 21:56:05 -08:00
sk89q 601e15db5a Updated for Minecraft beta. 2010-12-25 21:50:05 -08:00
sk89q f30b413b46 Added missing BlockType class. 2010-12-10 00:46:32 -08:00
sk89q a9c4a81abe Added suffocation damage prevention. 2010-12-10 00:46:06 -08:00
sk89q d619ed5798 Added coordinates to blacklist file logger. 2010-12-10 00:46:06 -08:00
sk89q e94a9bf68f Added exact respawning and teleporting to home on death. 2010-12-10 00:46:06 -08:00
sk89q 257c12e727 Updated for 0.2.8. 2010-12-04 00:15:50 -08:00
sk89q 8b3eaa70fb Updated for newer builds of hMod. 2010-12-02 22:56:47 -08:00
sk89q c96bb890b4 Caught NullPointerException caused by getting the players list too early. 2010-12-01 22:43:36 -08:00
sk89q 8192a1962a Updated for 1.7. 2010-11-30 21:59:39 -08:00
sk89q 80df9c6aa4 Improved blacklist support for the new hooks. 2010-11-30 21:54:36 -08:00
sk89q 8073089da4 Updated for Minecraft update. Untested. 2010-11-30 17:24:07 -08:00
sk89q 23e7d4a8bb Updated for 1.7. 2010-11-30 02:48:39 -08:00
sk89q 0e1e92df13 Added option to prevent block damage created by flowing water (Minecart tracks, Redstone wire, etc.) 2010-11-30 02:44:01 -08:00
sk89q d13f0b9191 Made /stack ignore buckets. 2010-11-30 02:33:51 -08:00
sk89q aa2bffbd00 Fixed /god for the new hMod versions. 2010-11-30 02:27:13 -08:00
sk89q a456d67528 Updated readmes. 2010-11-30 02:19:18 -08:00
sk89q 95f074342c Fixed damage type prevention. 2010-11-30 02:04:12 -08:00
sk89q 74016bf93e Made amphibious feature in WorldGuard more efficient and fixed missing group console spam. 2010-11-30 01:41:07 -08:00
sk89q 3f8bac582c Added /reload WorldGuard command; adjusted wg-invincible so that it won't console spam every time someone joins. 2010-11-29 12:59:44 -08:00
sk89q 6b57e58d63 Fixed damage type protection affecting all entities. Added wg-invincible and wg-amphibious groups that let you give certain players invincibility or underwater breathing. 2010-11-29 12:39:12 -08:00
sk89q 19aa20537d Added the ability to disable fall, water, lava, and fire damage individually. 2010-11-29 12:30:42 -08:00
sk89q cf31df35ec Switched water/lava bucket block to use new onItemUse hook. 2010-11-28 15:54:29 -08:00
sk89q 6d39ce7240 Added /stack command, alias /; to compact items into stacks (up to 64 items). Works for even non-stackable items like signs and it won't stack items with durability or infinite supply. 2010-11-26 01:06:32 -08:00
sk89q 0f3c1b94d7 Caught error message for when the configuration file does not exist. 2010-11-25 23:27:33 -08:00
sk89q 13cc6736e2 /god mode now at least lets you gain health while it is on. 2010-11-25 13:47:20 -08:00
sk89q 64629bd878 Updated README and CHANGELOG. 2010-11-25 02:40:46 -08:00
sk89q e42be555b1 Fixed spelling error in /god and allowed use of /god on others. 2010-11-25 02:37:50 -08:00
sk89q c62c5f5cae Updated for 1.6. 2010-11-25 00:02:59 -08:00
sk89q 313bdbd8bf Added spawn protection, updated login protection. 2010-11-24 23:55:27 -08:00
sk89q 765b606e18 Added login protection. 2010-11-24 23:13:42 -08:00
sk89q c0be685846 Added /god mode. 2010-11-24 22:44:09 -08:00
sk89q 133e4c2c78 Updated for 1.5.1. 2010-11-24 13:10:29 -08:00
sk89q b7e91ac6d0 'Fixed' java.lang.NoSuchMethodError: Item.setDamage(I)V. 2010-11-24 13:09:53 -08:00
sk89q 79518e6503 Updated CHANGELOG. 2010-11-24 12:44:37 -08:00
sk89q 2999f9d168 Removed warning emitted when a hook does not exist. 2010-11-24 12:43:18 -08:00
sk89q b4d8b2095d Changed some configuration defaults: summary-on-start=true, disable-lava-fire=true, simulate-sponge=true, item-durability=false. 2010-11-24 12:41:32 -08:00
sk89q f7099f2093 Improved README. 2010-11-24 12:31:56 -08:00
sk89q 8c51795b1a Removed mention of the block lag fix. 2010-11-24 12:26:58 -08:00
sk89q ba523ce3f3 Updated for 1.5. 2010-11-24 12:18:45 -08:00
sk89q e4af400acb Added a startup message indicating when all features all supported. 2010-11-24 12:17:26 -08:00
sk89q ffa38f9fd1 Removed the block lag fix and cleaned up code. 2010-11-24 12:02:04 -08:00
sk89q 84ccabdf34 Improved missing feature detection. 2010-11-24 11:58:54 -08:00
sk89q c0b4d95082 Added documentation for required hooks. Improved missing hook messages. 2010-11-23 22:42:30 -08:00
sk89q f305b3a119 Hooks are now conditionally loaded. summary-on-start is now disabled by default and mentioned in the README. 2010-11-23 22:31:28 -08:00
116 changed files with 16937 additions and 3093 deletions

No files matched your search

+177
View File
@@ -1,3 +1,180 @@
5.2.2:
- Changed configuration saving so empty lists will be added to
the configuration files.
5.2.1:
- Add region bounds to /region info
- Added the ability to add owners/members to the global region for
handling guest groups. Now if there's owners or members on the global
region, then those that are not on the list cannot build.
- Fixed some flag algorithm issues.
- API: Fixed DefaultDomain.size() not counting players.
- API: Undeprecated ApplicableRegionSet.allows(StateFlag).
5.2:
- Gave the ability to use color colors and macros in greeting
and farewell messages.
- Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread,
disable-snow-melting, disable-ice-formation.
- Added paintings to blacklist support.
- Added default.disable-health-regain.
- Added auto-invincible-permission setting, which lets you use the permission
'worldguard.auto-invincible' to become invincible on join automatically.
- Flames won't appear if you are /god'ed now.
- Added blocked-cmds region flag to block commands.
- Added allowed-cmds region flag to whitelist commands.
- Added entry region flag to block entry. Use entry-group to determine who
this affects.
- Added exit region flag to block exit. Use exit-group to determine who
this affects.
- Made negative healing possible via the healing flag.
- Changed the configuration header messages to be more helpful to new users.
- Added a warning about modifying region files by hand.
- Improved the API for plugin developers.
5.1:
- A lot of changes.
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.
- Fixed creeper explosion blocking.
- Added redstone support to sponges, removed classic water.
- Fixed item durability disable for hoes.
3.1.2:
- Increased the priority of WorldGuard's event handling.
3.1.1:
- Fixed creeper and chest flag conflicting.
3.1:
- Added ability to disable chest protection. New configuration setting
(regions.build.chest-access) and new chest flag.
- Possibly fixed projectile blocking in no-PvP zones.
- Added /regionmembership permission that lets people only change
the owners and members of regions they own.
3.0b2:
- Fixed issue where built-in permissions were not (re)loaded.
- Fixed /god not working for others.
3.0b1:
- Added parent-child relationships to regions.
- Added global build flag.
- Improved flag support.
- Fixed no-PvP zone messages being sent to the wrong person.
- Fixed commands so that they work in a recent version of Bukkit.
- Fixed NullPointerException in explode hook.
2.3.1:
- Fixed various cast exceptions with the blacklist loggers.
- Added checks for unchecked exceptions when resolving permissions.
- Fixed the item durability disable setting changing the damage value on
an empty hand.
2.3:
- /god now works very well.
- Item (TNT, flint and steel, etc.) blocking should now work.
- The TNT blocking configuration variable should now work.
- Re-added /heal (not sure where that went), added /slay.
- Implemented contact damage disable toggle.
- Made all player damage disabling configuration parameters work.
- Fixed teleport-on-suffocation setting.
- Added /locate <name>, /locate <x> <y> <z>, and /locate that lets you
program/change your compass bearing to point to a player's position
(not yet live), a position, or back to spawn.
- Fixed CSVDatabase spitting an error if the owners list was empty.
2.2:
- Now supports GroupUsers.
- Added support for blocking creeper explosions.
- Fixed a bug where a player's groups were not being loaded correctly,
causing the blacklist group ignore option to not work.
2.1.1:
- Fixed fire spread disable preventing flint and steel too.
- Fixed NullPointerException related to the player item event.
- Made setup simpler.
2.1:
- Improved Bukkit support.
2.0beta3:
- Fixed NullPointerException inside the ignite hook.
2.0beta2:
- Fixed a NullPointerException in the damage hook.
2.0beta1:
- Added area protection. Use /region or /rg to define regions.
1.8.1
- Fixed NullPointerException.
1.8
- Updated for Minecraft beta.
- Blacklist hooks have CHANGED. The new hooks are work better. on-create has
been replaced with on-place (for block placement) and on-use
(for item usage, light buckets and lighters). The old on-use is now
on-right-click although it currently does nothing.
- Added coordinates to blacklist file logger.
- Added suffocation damage prevention.
1.7.1
- Updated for v0.2.8.
1.7
- Updated for v0.2.6_02 and hMod b129.
- Added option to prevent water from damaging particular blocks
(Redstone wire, Minecart tracks, etc.). See disable-water-damage-blocks.
- /reload WorldGuard should now reload WorldGuard's configuration.
- Added wg-invincible and wg-amphibious groups that let you give certain
players invincibility or underwater breathing.
- Added the ability to disable fall, water, lava, and/or fire damage.
- Water/lava bucket blocking should now be more reliable.
- Added /stack (alias /;) commands to stack items in your inventory into
piles up to 64 items in size. Even unstackable items like signs can be
stacked.
- /god mode should now let you gain health.
- /god mode should now work more reliably.
- Caught an error message for when the configuration file does not exist.
1.6
- Added spawn protection that prevents damage when a player spawns.
- Added login protection that prevents damage when a player joins.
- Added /god. /god can be used on others, provided that the /godother
permission is set for the command's user.
1.5.1
- Removed the 'java.lang.NoSuchMethodError: Item.setDamage(I)V' error
generated.
1.5
- Removed the block lag fix.
- WorldGuard now conditionally loads features so you can use any up-to-date
build of hMod and the unsupported features won't break the entire
plugin. When WG loads, check the server console for a report of
features that are not supported by your version of hMod.
- Changed some configuration defaults:
disable-lava-fire=true
simulate-sponge=true
item-durability=false
1.4.1
- Fixed issue with the block lag fix dropping item stacks of 0 quantity.
-15
View File
@@ -1,15 +0,0 @@
Installation
------------
This plugin requires Hey0's server modification.
1. Create a "plugins" folder inside your "bin" folder.
2. Copy WorldGuard.jar into "plugins".
3. Add "WorldGuard" to the "plugins" line of your server.properties file.
If it's not already there, add the line. The line should look like this:
plugins=WorldGuard
If you have multiple plugins, separate plugin names with commas.
+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.
+116
View File
@@ -0,0 +1,116 @@
<!DOCTYPE html>
<html>
<head>
<title>WorldGuard ${version}</title>
<style>
body {
margin: 0;
padding: 20px;
background: #efefef;
color: #333;
}
#wrapper {
margin: 20px auto 20px auto;
width: 600px;
background: #fff;
padding: 40px;
border: 1px solid #fff;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
box-shadow: 0 0 2px #999;
-webkit-box-shadow: 0 0 3px #999;
}
a img {
border: 0;
}
body, th, td, input {
font: 13px/17px "Lucida Grande", "Lucida Sans Unicode", Arial, Verdana, sans-serif;
}
a:link, a:visited {
color: #00688f;
text-decoration: underline;
}
a:hover, a:active {
color: #000;
border: 0;
}
h1 {
font: 170% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #b90000;
margin: 15px 0 5px 0;
}
h2 {
font: 130% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #6a45ac;
margin: 50px 0 5px 0;
padding: 0 0 3px 0;
border-bottom: 1px solid #ccc;
}
.warning {
background: #fffedf;
padding: 8px;
border: 1px dashed #ccc;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 90%;
}
.subtle {
color: #999;
}
.optional {
background: none repeat scroll 0 0 #FFE081;
border-radius: 3px 3px 3px 3px;
font-size: 80%;
font-weight: normal;
padding: 1px 4px;
}
</style>
</head>
<body>
<div id="wrapper">
<h1>WorldGuard ${version}</h1>
<p>Thanks for choosing WorldGuard!</p>
<h2>Getting Started</h2>
<p>Now, to begin, you want to:</p>
<ol>
<li><strong>Install the plugin:</strong> Copy WorldGuard.jar into your Bukkit server's &quot;plugins&quot; directory.</li>
<li><strong>Change the configuration:</strong> Run your server once (with WorldGuard) to generate the default configuration files. There are <em>two</em> types of configuration files:
<ul>
<li>The main config.yml file inside &quot;plugins/WorldGuard&quot; is the main configuration. </li>
<li>Each world has a configuration file in &quot;plugins/WorldGuard/worlds&quot; that you can use to override any setting in the main configuration file for that specific world.</li>
</ul>
</li>
Use <em>/wg reload</em> in the console to reload the configuration.
<li><strong>Learn how to use WorldGuard:</strong> Check <a href="http://wiki.sk89q.com/wiki/WorldGuard">out the wiki</a> to learn how to disable things like fire and to protect regions.</li>
</ol>
<p class="warning"><strong>Note:</strong> <a href="http://www.sk89q.com/projects/worldedit/">WorldEdit</a> must be installed, but if you do not want it, put WorldEdit.jar into your Bukkit root folder (outside of plugins/). Note that region protection requires WorldEdit in plugins/.</p>
<p>Be sure to:</p>
<ul>
<li>Subscribe to <a href="http://minecraftnews.sk89q.com/">SK's Minecraft blog</a> for news about WorldGuard</li>
<li>Idle with us in IRC at <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a></li>
</ul>
<h2>Getting Help</h2>
<p>If you need help, the best two ways to ask are:</p>
<ul>
<li><a href="http://forum.sk89q.com/">Visit the WorldGuard forum</a></li>
<li>Ask in IRC chat on <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a> (idle with us!)</li>
<li>Submit bug reports and suggestions to the <a href="http://redmine.sk89q.com/projects/worldguard/issues">issue tracker</a></li>
</ul>
<h2>Contributing</h2>
<p>WorldGuard is entirely open source! You can download all of the plugin code to learn from it, modify it for your own self, or even contribute back!</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">Download WorldGuard code from GitHub</a></li>
<li>You can also <a href="http://www.sk89q.com/donate/">donate</a></li>
</ul>
<p>The code is covered under the GNU General Public License v3.</p>
<p class="subtle">Maven information: ${groupId}/${artifactId}/${version}</p>
</div>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
WorldGuard
==========
WorldGuard protects your Minecraft server. As Minecraft's oldest surviving world protection mod, you know you're in safe hands.
Compiling
---------
You need to have Maven installed (http://maven.apache.org). Once installed,
simply run:
mvn clean install
Maven will automatically download dependencies for you. Note: For that to work,
be sure to add Maven to your "PATH".
Contributing
------------
We happily accept contributions. The best way to do this is to fork WorldGuard
on GitHub, add your changes, and then submit a pull request. We'll look at it,
make comments, and merge it into WorldGuard if everything works out.
By submitting code, you agree to place to license your code under the
GNU General Public License v3.
-209
View File
@@ -1,209 +0,0 @@
WorldGuard
Copyright (c) 2010 sk89q <http://www.sk89q.com>
Licensed under the GNU Lesser General Public License v3
Introduction
------------
WorldGuard has a number of features, any of which you can choose to
use or not:
- Enforce only one session for a player on a server (can't login twice).
- Block creeper explosions.
- Block TNT explosions.
- Block lighters from setting fires.
- Block all fires.
- Allow fire but prevent it from burning certain blocks.
- Prevent lava from starting fires.
- Restrict lava spreading to only some block types.
- Simulate classic-esque water by letting water infinitely expand in
area (only if there is a block underneath).
- Simulate the function of the sponge from Minecraft Classic.
- Notify admins, block, log, kick or ban for the use of certain block types
or items.
- Temporarily stop fire globally with some commands.
- Fix the block lag.
- Destroy tools on drop to alleviate the durability cheat.
- OR just fix the durability bug.
- Prevent gravel and sand from falling.
- Allow portal blocks to be placed anywhere.
hMod is required as WorldGuard is a plugin for hMod.
Configuration
-------------
A "worldguard.properties" will be created the first the time that you load
WorldGuard on your server. You can either restart your server or use
/reloadplugin WorldGuard to reload the configuraton file after editing it.
- item-durability (def. true)
Enables item durability.
- classic-water (def. false)
Toggle use of classic water. Be foreward that your world may be
flooded if you are not careful. If you have WorldEdit, you can use
//drain in such an event, although that will drain the entire pool
as well. This classic-esque water will only spread infinitely over
ground, but if there are air blocks underneath, the water will not
spread (preventing waterfalls from becoming tsunamis).
- simulate-sponge (def. false)
Toggle simulation of the sponge from Classic. It blocks water from
flowing near the sponge.
- sponge-radius (def. 3)
The radius of the sponge's effect. The default is that of Classic,
creating a 5x5x5 cuboid free of water. Increasing the number will
increase server load exponentially, although 3-5 has fairly low impact.
- no-physics-gravel (def. false)
Prevents gravel from falling due to gravity.
- no-physics-sand (def. false)
Prevents sand from falling due to gravity.
- allow-portal-anywhere (def. false)
Allows you to place portal blocks anywhere.
- enforce-single-session (def. true)
Enforce single sessions. If the player is already found to be on
the server when s/he logs in, the other player will be kicked with
an informative message. The inventory will have been saved before
the new session starts.
- block-tnt (def. false)
Block TNT explosions. TNT will still explode client-side but the blocks
will be "restored" in a few seconds afterwards.
- block-lighter (def. false)
Block flint and steel fires. Those with access to the commands
/uselighter or /lighter can bypass this. /uselighter is not a real
command; it is only used for permissions.
- block-creepers (def. false)
Block creeper explosions from destroying terrain (and possibly from
causing damage).
- disable-lava-fire (def. false)
Prevent lava from starting fires.
- allowed-lava-spread-blocks (no default)
List of block names/IDs to allow lava to spread to. Leave blank
to disable this feature.
- disable-all-fire-spread (def. false)
Disable all fire from spreading.
- disallowed-fire-spread-blocks (no default)
List of block names/IDs to prevent fire from spreading to. Leave blank
to disable this feature. Enabling disable-all-fire-spread will
override this function.
- item-drop-blacklist (no default)
List of block names/IDs to destroy on drop. This can alleviate the
durability cheat that allows you to drop your tools to fix their
durability. You can also enforce this with the blacklist but
this is an easier way to do it (this way also prints a more
friendly message than if you used the 'tell' action of the blacklist).
- block-lag-fix (def. false)
Attempts to fix block lag. For maximum compatibility with other plugins,
you must list WorldGuard as the first plugin in server.properties and
you cannot reload or enable WorldGuard while the server is up.
This is for bad plugins that unnecessarily use the "critical" priority
for its hooks like the LWC. Most plugins, the popular protection ones
included, don't do that though so this won't apply for most people.
- log-console (def. true)
For blacklist log actions, print to console.
- log-file (def. false)
For blacklist log actions, log to file.
- log-file-path (def. "worldguard/logs/%Y-%m-%d.log")
Log blacklist events to file. You can use these patterns in the path:
%Y the year (YYYY)
%m the month (MM)
%d the day (DD)
%W the week of the year (00-52)
%H 24-hour time (HH)
%h 12-hour time (HH)
%i the minute (mm)
%s the second (ss)
%u the user's name
%% translates to a single percent sign "%"
The files are not automatically rotated if they get large so you should
perhaps put a week in the filename at least.
Escape backslashes with another backslash, like so:
C:\path\to\log.txt -> C:\\path\\to\\log.txt
- log-file-open-files (def. 10)
The number of log files to keep open at once. Unless you use dynamic
patterns in the path, the value of this variable won't matter. However,
if, for example, you use a player's username in the filename and you
have many users who cause logged events to occur, files would have
to be opened for each user and this parameter would matter.
- log-database (def. false)
Log blacklist events to database.
- log-database-dsn (def. "jdbc:mysql://localhost:3306/minecraft")
Connection string. A string to use for MySQL would be:
jdbc:mysql://localhost:3306/minecraft
The "minecraft" part at the end is the database name.
Escape colons with a backslash, like so:
jdbc:mysql://localhost:3306/minecraft
->
jdbc\:mysql\://localhost\:3306/minecraft
- log-database-user (def. "root")
Database username.
- log-database-pass (def. "")
Database password.
- log-database-table (def. "blacklist_events")
Database table to use.
Commands
--------
- /stopfire and /allowfire
Disables and enables fire spread globally. Both commands require the
permission to use only "/stopfire. Re-enabling fire spread with this
command will not override other fire spread control features of
WorldGuard. Note that disabling fire does not disable fire damage
but fire at least won't spread.
Server Commands
---------------
- fire-stop and fire-allow
Disables and enables fire spread globally. Re-enabling fire spread
with this command will not override other fire spread control features
of WorldGuard. Note that disabling fire does not disable fire damage
but fire at least won't spread.
Blacklists
----------
Blacklists let you control the use of blocks and items. You can have
certain rules apply to only some groups.
Edit the included worldguard-blacklist.txt file and follow the
instructions inside. The file comes with the download for WorldGuard.
Thanks
------
While I would like to thank everyone for their support, I would like to
say thanks to the following individuals for their direct
contributions to WorldGuard:
- Sturmeh, for contributing the original durability workaround
- Meaglin, for changing the on flow hook at my request
- Dinnerbone, for implementing the on item pick up hook at my request,
and also for figuring out the durability bug in the process
+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
-2
View File
@@ -1,2 +0,0 @@
Manifest-Version: 1.0
WorldGuard-Version: 1.4.1
+186
View File
@@ -0,0 +1,186 @@
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
CommandBook is available under the GNU General Public License v3
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.2.2</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<repositories>
<!-- Repository for other dependencies of SK's -->
<repository>
<id>sk89q-mvn2</id>
<url>http://mvn2.sk89q.com/repo</url>
</repository>
<!-- Repository for Bukkit -->
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/artifactory/repo</url>
</repository>
</repositories>
<dependencies>
<!-- Required component -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>4.4.2</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldEdit.jar WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.1</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
<!-- TODO: Get Doclava working -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
</configuration>
</plugin>
</plugins>
</reporting>
</project>
-694
View File
@@ -1,694 +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/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
/**
*
* @author sk89q
*/
public class BlacklistEntry {
/**
* Used to prevent spamming.
*/
private static Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
/**
* Parent blacklist entry.
*/
private Blacklist blacklist;
/**
* List of groups to not affect.
*/
private Set<String> ignoreGroups;
/**
* List of actions to perform on destruction.
*/
private String[] destroyActions;
/**
* List of actions to perform on break.
*/
private String[] breakActions;
/**
* List of actions to perform on left click.
*/
private String[] destroyWithActions;
/**
* List of actions to perform on right click.
*/
private String[] createActions;
/**
* List of actions to perform on right click upon.
*/
private String[] useActions;
/**
* List of actions to perform on drop.
*/
private String[] dropActions;
/**
* List of actions to perform on drop.
*/
private String[] acquireActions;
/**
* Message for users.
*/
private String message;
/**
* Comment for administrators.
*/
private String comment;
/**
* Used to ignore messages.
*/
private static ActionHandler silentHandler = new ActionHandler() {
public void log(String itemName) {}
public void kick(String itemName) {}
public void ban(String itemName) {}
public void notifyAdmins(String itemName) {}
public void tell(String itemName) {}
};
/**
* Construct the object.
*
* @param blacklist
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
}
/**
* @return the ignoreGroups
*/
public String[] getIgnoreGroups() {
return ignoreGroups.toArray(new String[ignoreGroups.size()]);
}
/**
* @param ignoreGroups the ignoreGroups to set
*/
public void setIgnoreGroups(String[] ignoreGroups) {
Set<String> ignoreGroupsSet = new HashSet<String>();
for (String group : ignoreGroups) {
ignoreGroupsSet.add(group.toLowerCase());
}
this.ignoreGroups = ignoreGroupsSet;
}
/**
* @return
*/
public String[] getDestroyActions() {
return destroyActions;
}
/**
* @param actions
*/
public void setDestroyActions(String[] actions) {
this.destroyActions = actions;
}
/**
* @return
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param action
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return the rightClickActions
*/
public String[] getCreateActions() {
return createActions;
}
/**
* @param actions
*/
public void setCreateActions(String[] actions) {
this.createActions = actions;
}
/**
* @return
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Returns true if this player should be ignored.
*
* @param player
* @return
*/
public boolean shouldIgnore(Player player) {
if (ignoreGroups == null) {
return false;
}
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
return true;
}
}
return false;
}
/**
* Announces a message to all administrators.
*
* @param str
*/
public void notifyAdmins(String str) {
for (Player player : etc.getServer().getPlayerList()) {
if (player.canUseCommand("/wprotectalerts")
|| player.canUseCommand("/worldguardnotify")) {
player.sendMessage(Colors.LightGray + "WG: " + str);
}
}
}
/**
* Ban a player.
*
* @param player
* @param msg
*/
public void banPlayer(Player player, String msg) {
etc.getServer().ban(player.getName());
etc.getLoader().callHook(PluginLoader.Hook.BAN, new Object[]{
player.getUser(), player.getUser(), msg
});
player.kick(msg);
}
/**
* Called on block destruction. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onDestroy(final Block block, final Player player) {
if (destroyActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDestroyAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You are not allowed to destroy " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You are not allowed to destroy " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (destroy) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You are not allowed to destroy " + itemName + ".");
}
};
return process(block.getType(), player, destroyActions, handler, false, false);
}
/**
* Called on block break. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onBreak(final Block block, final Player player) {
if (breakActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logBreakAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You are not allowed to break " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You are not allowed to break " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (break) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You are not allowed to break " + itemName + ".");
}
};
return process(block.getType(), player, breakActions, handler, true, false);
}
/**
* Called on left click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDestroyWith(final int item, final Player player) {
if (destroyWithActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDestroyWithAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't destroy with " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't destroy with " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (destroy w/) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You can't destroy with " + itemName + ".");
}
};
return process(item, player, destroyWithActions, handler, false, false);
}
/**
* Called on right click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onCreate(final int item, final Player player) {
if (createActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logCreateAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't place " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't place " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (place) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You can't place " + itemName + ".");
}
};
return process(item, player, createActions, handler, true, false);
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onUse(final Block block, final Player player) {
if (useActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logUseAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You can't use " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't use " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (use) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to use " + itemName + ".");
}
};
return process(block.getType(), player, useActions, handler, false, false);
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentUse(final Block block, final Player player) {
if (useActions == null) {
return true;
}
return process(block.getType(), player, useActions, silentHandler, false, true);
}
/**
* Called on item drop. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDrop(final int item, final Player player) {
if (dropActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDropAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't drop " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't drop " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (drop) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to drop " + itemName + ".");
}
};
return process(item, player, dropActions, handler, true, false);
}
/**
* Called on item acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onAcquire(final int item, final Player player) {
if (acquireActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logAcquireAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't acquire " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't acquire " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (acquire) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to acquire " + itemName + ".");
}
};
return process(item, player, acquireActions, handler, true, false);
}
/**
* Called on item acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentAcquire(final int item, final Player player) {
if (acquireActions == null) {
return true;
}
return process(item, player, acquireActions, silentHandler, false, true);
}
/**
* Internal method to handle the actions.
*
* @param id
* @param player
* @param actions
* @param handler
* @param allowRepeat
* @param silent
* @return
*/
private boolean process(int id, Player player, String[] actions,
ActionHandler handler, boolean allowRepeat, boolean silent) {
if (shouldIgnore(player)) {
return true;
}
String name = player.getName();
long now = System.currentTimeMillis();
boolean repeating = false;
// Check to see whether this event is being repeated
BlacklistTrackedEvent tracked = lastAffected.get(name);
if (tracked != null) {
if (tracked.getId() == id && tracked.getTime() > now - 3000) {
repeating = true;
} else {
tracked.setTime(now);
tracked.setId(id);
}
} else {
lastAffected.put(name, new BlacklistTrackedEvent(id, now));
}
boolean ret = true;
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (this.message != null) {
player.kick(String.format(this.message,
etc.getDataSource().getItem(id)));
} else {
handler.kick(etc.getDataSource().getItem(id));
}
// Ban
} else if (action.equalsIgnoreCase("ban")) {
handler.ban(etc.getDataSource().getItem(id));
if (this.message != null) {
banPlayer(player, "Banned: " + String.format(this.message,
etc.getDataSource().getItem(id)));
} else {
handler.ban(etc.getDataSource().getItem(id));
}
} else if (!repeating || allowRepeat) {
// Notify
if (action.equalsIgnoreCase("notify")) {
handler.notifyAdmins(etc.getDataSource().getItem(id));
// Log
} else if (action.equalsIgnoreCase("log")) {
handler.log(etc.getDataSource().getItem(id));
// Tell
} else if (action.equalsIgnoreCase("tell")) {
if (this.message != null) {
player.sendMessage(Colors.Yellow +
String.format(message, etc.getDataSource().getItem(id))
+ ".");
} else {
handler.tell(etc.getDataSource().getItem(id));
}
}
}
}
return ret;
}
/**
* Forget a player.
*
* @param player
*/
public static void forgetPlayer(Player player) {
lastAffected.remove(player.getName());
}
/**
* Forget all players.
*
* @param player
*/
public static void forgetAllPlayers() {
lastAffected.clear();
}
/**
* Gets called for actions.
*/
private static interface ActionHandler {
public void log(String itemName);
public void kick(String itemName);
public void ban(String itemName);
public void notifyAdmins(String itemName);
public void tell(String itemName);
}
}
-153
View File
@@ -1,153 +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/>.
*/
import java.util.Set;
import java.util.HashSet;
/**
*
* @author sk89q
*/
public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* List of logger handlers.
*/
private Set<BlacklistLoggerHandler> handlers
= new HashSet<BlacklistLoggerHandler>();
/**
* Add a handler.
*
* @param handler
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Add a handler.
*
* @param handler
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
}
/**
* Add a handler.
*
* @param handler
*/
public void clearHandlers() {
handlers.clear();
}
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDestroyAttempt(player, block, comment);
}
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logBreakAttempt(player, block, comment);
}
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logUseAttempt(player, block, comment);
}
}
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDestroyWithAttempt(player, item, comment);
}
}
/**
* Log a right click attempt.
*
* @param player
* @param item
*/
public void logCreateAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logCreateAttempt(player, item, comment);
}
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDropAttempt(player, item, comment);
}
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logAcquireAttempt(player, item, comment);
}
}
/**
* Close the connection.
*/
public void close() {
for (BlacklistLoggerHandler handler : handlers) {
handler.close();
}
}
}
-79
View File
@@ -1,79 +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/>.
*/
/**
* Interface for loggers for the blacklist.
*
* @author sk89q
*/
public interface BlacklistLoggerHandler {
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment);
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment);
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, Block block, String comment);
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment);
/**
* Log a right click attempt.
*
* @param player
* @param item
*/
public void logCreateAttempt(Player player, int item, String comment);
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment);
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment);
/**
* Close the logger.
*/
public void close();
}
-131
View File
@@ -1,131 +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/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to destroy " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to break " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to use " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log an attempt to destroy with an item.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to destroy with " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a block creation attempt.
*
* @param player
* @param item
*/
public void logCreateAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to create " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to drop " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to acquire " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*/
private static String getFriendlyItemName(int id) {
return etc.getDataSource().getItem(id) + " (#" + id + ")";
}
/**
* Close the connection.
*/
public void close() {
}
}
-215
View File
@@ -1,215 +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/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
/**
*
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* DSN.
*/
private String dsn;
/**
* Username.
*/
private String user;
/**
* Password.
*/
private String pass;
/**
* Table.
*/
private String table;
/**
* Database connection.
*/
private Connection conn;
/**
* Construct the object.
*
* @param dsn
* @param user
* @param pass
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
}
/**
* Gets the database connection.
*
* @return
* @throws SQLException
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(dsn, user, pass);
}
return conn;
}
/**
* Log an event to the database.
*
* @param event
* @param name
* @param x
* @param y
* @param z
* @param item
* @param comment
*/
private void logEvent(String event, String name, int x, int y, int z, int item,
String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
stmt.setString(2, name);
stmt.setInt(3, x);
stmt.setInt(4, y);
stmt.setInt(5, z);
stmt.setInt(6, item);
stmt.setInt(7, (int)(System.currentTimeMillis() / 1000));
stmt.setString(8, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
+ e.getMessage());
}
}
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
logEvent("DESTROY", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
logEvent("BREAK", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, Block block, String comment) {
logEvent("USE", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
logEvent("DESTROY_WITH", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log a right click attempt.
*
* @param player
* @param item
*/
public void logCreateAttempt(Player player, int item, String comment) {
logEvent("CREATE", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
logEvent("DROP", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log an aquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
logEvent("AQUIRE", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Close the connection.
*/
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
}
}
}
-137
View File
@@ -1,137 +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/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.jar.Manifest;
import java.util.jar.Attributes;
import java.net.URL;
import java.io.*;
/**
* Entry point for the plugin for hey0's mod.
*
* @author sk89q
*/
public class WorldGuard extends Plugin {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Listener for the plugin system.
*/
private WorldGuardListener listener;
/**
* Initialize the plugin.
*/
public WorldGuard() {
listener = new WorldGuardListener(this);
}
/**
* Initializes the plugin.
*/
@Override
public void initialize() {
PluginLoader loader = etc.getLoader();
loader.addListener(PluginLoader.Hook.COMMAND, listener, this,
PluginListener.Priority.MEDIUM);
loader.addListener(PluginLoader.Hook.SERVERCOMMAND, listener, this,
PluginListener.Priority.MEDIUM);
loader.addListener(PluginLoader.Hook.EXPLODE, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.IGNITE, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.FLOW, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.LOGINCHECK, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.LOGIN, listener, this,
PluginListener.Priority.MEDIUM);
loader.addListener(PluginLoader.Hook.BLOCK_CREATED, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.BLOCK_DESTROYED, listener, this,
PluginListener.Priority.CRITICAL);
loader.addListener(PluginLoader.Hook.BLOCK_BROKEN, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.DISCONNECT, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.ITEM_DROP, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.ITEM_PICK_UP, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.COMPLEX_BLOCK_CHANGE, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.COMPLEX_BLOCK_SEND, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.INVENTORY_CHANGE, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.BLOCK_PHYSICS, listener, this,
PluginListener.Priority.MEDIUM);
}
/**
* Enables the plugin.
*/
@Override
public void enable() {
logger.log(Level.INFO, "WorldGuard version " + getVersion() + " loaded");
listener.loadConfiguration();
etc.getInstance().addCommand("/stopfire", "Globally stop fire spread");
etc.getInstance().addCommand("/allowfire", "Globally re-enable fire spread");
}
/**
* Disables the plugin.
*/
@Override
public void disable() {
try {
listener.disable();
BlacklistEntry.forgetAllPlayers();
} catch (Throwable t) {
}
etc.getInstance().removeCommand("/stopfire");
etc.getInstance().removeCommand("/allowfire");
}
/**
* Get the WorldGuard version.
*
* @return
*/
private String getVersion() {
try {
String classContainer = WorldGuard.class.getProtectionDomain()
.getCodeSource().getLocation().toString();
URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(manifestUrl.openStream());
Attributes attrib = manifest.getMainAttributes();
String ver = (String)attrib.getValue("WorldGuard-Version");
return ver != null ? ver : "(unavailable)";
} catch (IOException e) {
return "(unknown)";
}
}
}
-894
View File
@@ -1,894 +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/>.
*/
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.Handler;
import java.util.logging.ConsoleHandler;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import java.io.*;
import java.util.logging.FileHandler;
import com.sk89q.worldguard.*;
/**
* Event listener for Hey0's server mod.
*
* @author sk89q
*/
public class WorldGuardListener extends PluginListener {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Timer for threading.
*/
private static final Timer timer = new Timer();
/**
* Random number generator.
*/
private static Random rand = new Random();
/**
* Plugin host.
*/
private WorldGuard plugin;
/**
* Properties file for WorldGuard.
*/
private PropertiesFile properties = new PropertiesFile("worldguard.properties");
/**
* Stop fire spread mode.
*/
private boolean stopFireSpread = false;
private boolean enforceOneSession;
private boolean blockCreepers;
private boolean blockTNT;
private boolean blockLighter;
private boolean preventLavaFire;
private boolean disableAllFire;
private boolean simulateSponge;
private int spongeRadius;
private boolean blockLagFix;
private boolean itemDurability;
private Set<Integer> fireNoSpreadBlocks;
private Set<Integer> allowedLavaSpreadOver;
private Set<Integer> itemDropBlacklist;
private boolean classicWater;
private boolean noPhysicsGravel;
private boolean noPhysicsSand;
private boolean allowPortalAnywhere;
private Blacklist blacklist;
/**
* Construct the listener.
*
* @param plugin
*/
public WorldGuardListener(WorldGuard plugin) {
this.plugin = plugin;
}
/**
* Convert a comma-delimited list to a set of integers.
*
* @param str
* @return
*/
private static Set<Integer> toBlockIDSet(String str) {
if (str.trim().length() == 0) {
return null;
}
String[] items = str.split(",");
Set<Integer> result = new HashSet<Integer>();
for (String item : items) {
try {
result.add(Integer.parseInt(item.trim()));
} catch (NumberFormatException e) {
int id = etc.getDataSource().getItem(item.trim());
if (id != 0) {
result.add(id);
} else {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
+ item);
}
}
}
return result;
}
/**
* Load the configuration
*/
public void loadConfiguration() {
properties.load();
// Load basic options
enforceOneSession = properties.getBoolean("enforce-single-session", true);
blockCreepers = properties.getBoolean("block-creepers", false);
blockTNT = properties.getBoolean("block-tnt", false);
blockLighter = properties.getBoolean("block-lighter", false);
preventLavaFire = properties.getBoolean("disable-lava-fire", false);
disableAllFire = properties.getBoolean("disable-all-fire-spread", false);
itemDropBlacklist = toBlockIDSet(properties.getString("item-drop-blacklist", ""));
fireNoSpreadBlocks = toBlockIDSet(properties.getString("disallowed-fire-spread-blocks", ""));
allowedLavaSpreadOver = toBlockIDSet(properties.getString("allowed-lava-spread-blocks", ""));
classicWater = properties.getBoolean("classic-water", false);
simulateSponge = properties.getBoolean("simulate-sponge", false);
spongeRadius = Math.max(1, properties.getInt("sponge-radius", 3)) - 1;
blockLagFix = properties.getBoolean("block-lag-fix", false);
itemDurability = properties.getBoolean("item-durability", true);
noPhysicsGravel = properties.getBoolean("no-physics-gravel", false);
noPhysicsSand = properties.getBoolean("no-physics-sand", false);
allowPortalAnywhere = properties.getBoolean("allow-portal-anywhere", false);
// Console log configuration
boolean logConsole = properties.getBoolean("log-console", true);
// Database log configuration
boolean logDatabase = properties.getBoolean("log-database", false);
String dsn = properties.getString("log-database-dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = properties.getString("log-database-user", "root");
String pass = properties.getString("log-database-pass", "");
String table = properties.getString("log-database-table", "blacklist_events");
// File log configuration
boolean logFile = properties.getBoolean("log-file", false);
String logFilePattern = properties.getString("log-file-path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, properties.getInt("log-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 blacklist = new Blacklist();
blacklist.load(new File("worldguard-blacklist.txt"));
// If the blacklist is empty, then set the field to null
// and save some resources
if (blacklist.isEmpty()) {
this.blacklist = null;
} else {
this.blacklist = blacklist;
logger.log(Level.INFO, "WorldGuard: Blacklist loaded.");
BlacklistLogger blacklistLogger = blacklist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler());
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize);
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 (properties.getBoolean("summary-on-start", true)) {
logger.log(Level.INFO, enforceOneSession ? "WorldGuard: Single session is enforced."
: "WorldGuard: Single session is NOT ENFORCED.");
logger.log(Level.INFO, blockTNT ? "WorldGuard: TNT ignition is blocked."
: "WorldGuard: TNT ignition is PERMITTED.");
logger.log(Level.INFO, blockLighter ? "WorldGuard: Lighters are blocked."
: "WorldGuard: Lighters are PERMITTED.");
logger.log(Level.INFO, preventLavaFire ? "WorldGuard: Lava fire is blocked."
: "WorldGuard: Lava fire is PERMITTED.");
if (disableAllFire) {
logger.log(Level.INFO, "WorldGuard: All fire spread is disabled.");
} else {
if (fireNoSpreadBlocks != null) {
logger.log(Level.INFO, "WorldGuard: Fire spread is limited to "
+ fireNoSpreadBlocks.size() + " block types.");
} else {
logger.log(Level.INFO, "WorldGuard: Fire spread is UNRESTRICTED.");
}
}
}
}
/**
* Called during the early login process to check whether or not to kick the
* player
*
* @param user
* @return kick reason. null if you don't want to kick the player.
*/
public String onLoginChecks(String user) {
if (enforceOneSession) {
for (Player player : etc.getServer().getPlayerList()) {
if (player.getName().equalsIgnoreCase(user)) {
player.kick("Logged in from another location.");
}
}
}
return null;
}
/**
* Called during the later login process
*
* @param player
*/
public void onLogin(Player player) {
if (stopFireSpread) {
player.sendMessage(Colors.Yellow + "Fire spread is currently globally disabled.");
}
}
/**
* Called before the command is parsed. Return true if you don't want the
* command to be parsed.
*
* @param player
* @param split
* @return false if you want the command to be parsed.
*/
public boolean onCommand(Player player, String[] split) {
if (split[0].equalsIgnoreCase("/stopfire") &&
player.canUseCommand("/stopfire")) {
if (!stopFireSpread) {
etc.getServer().messageAll(Colors.Yellow
+ "Fire spread has been globally disabled by " + player.getName() + ".");
} else {
player.sendMessage(Colors.Yellow + "Fire spread was already globally disabled.");
}
stopFireSpread = true;
return true;
} else if (split[0].equalsIgnoreCase("/allowfire")
&& player.canUseCommand("/stopfire")) {
if (stopFireSpread) {
etc.getServer().messageAll(Colors.Yellow
+ "Fire spread has been globally re-enabled by " + player.getName() + ".");
} else {
player.sendMessage(Colors.Yellow + "Fire spread was already globally enabled.");
}
stopFireSpread = false;
return true;
}
return false;
}
/**
* Called before the console command is parsed. Return true if you don't
* want the server command to be parsed by the server.
*
* @param split
* @return false if you want the command to be parsed.
*/
public boolean onConsoleCommand(String[] split) {
if (split[0].equalsIgnoreCase("fire-stop")) {
if (!stopFireSpread) {
etc.getServer().messageAll(Colors.Yellow
+ "Fire spread has been globally disabled by server console.");
logger.log(Level.INFO, "Fire spread is now globally disabled.");
} else {
logger.log(Level.INFO, "Fire spread was already globally disabled.");
}
stopFireSpread = true;
return true;
} else if (split[0].equalsIgnoreCase("fire-allow")) {
if (stopFireSpread) {
etc.getServer().messageAll(Colors.Yellow
+ "Fire spread has been globally re-enabled by server console.");
logger.log(Level.INFO, "Fire spread is now globally enabled.");
} else {
logger.log(Level.INFO, "Fire spread was already globally enabled.");
}
stopFireSpread = false;
return true;
}
return false;
}
/**
* Called when a player drops an item.
*
* @param player
* player who dropped the item
* @param item
* item that was dropped
* @return true if you don't want the dropped item to be spawned in the
* world
*/
public boolean onItemDrop(Player player, Item item) {
if (itemDropBlacklist != null) {
int n = item.getItemId();
if (itemDropBlacklist.contains(n)) {
player.sendMessage(Colors.Rose + "Item was destroyed!");
return true;
}
}
if (blacklist != null) {
if (!blacklist.onDrop(item.getItemId(), player)) {
return true;
}
}
if (!itemDurability) {
item.setDamage(0);
}
return false;
}
/**
* Called when a player picks up an item.
*
* @param player
* player who picked up the item
* @param item
* item that was picked up
* @return true if you want to leave the item where it was
*/
public boolean onItemPickUp(Player player, Item item) {
if (blacklist != null && blacklist.hasOnAcquire()) {
if (!blacklist.onSilentAcquire(item.getItemId(), player)) {
return true;
}
}
return false;
}
/**
* Called when a player's inventory is modified.
*
* @param player
* player who's inventory was modified
* @return true if you want any changes to be reverted
*/
public boolean onInventoryChange(Player player) {
if (blacklist != null && blacklist.hasOnAcquire()) {
hj[] items = player.getInventory().getArray();
boolean needUpdate = false;
for (int i = 0; i < items.length; i++) {
if (items[i] != null) {
if (!blacklist.onAcquire(items[i].c, player)) {
items[i] = null;
needUpdate = true;
}
}
}
if (needUpdate) {
player.getInventory().updateInventory();
}
}
return false;
}
/**
* Called when someone presses right click. If they right clicked with a
* block you can return true to cancel that. You can intercept this to add
* your own right click actions to different item types (see itemInHand)
*
* @param player
* @param blockPlaced
* @param blockClicked
* @param itemInHand
* @return false if you want the action to go through
*/
public boolean onBlockCreate(Player player, Block blockPlaced, Block blockClicked,
int itemInHand) {
if (blacklist != null) {
if (!blacklist.onCreate(itemInHand, player)) {
// Water/lava bucket fix
if (itemInHand == 326 || itemInHand == 327) {
final int x = blockPlaced.getX();
final int y = blockPlaced.getY();
final int z = blockPlaced.getZ();
final int existingID = etc.getServer().getBlockIdAt(x, y, z);
// This is REALLY BAD, but there's no other choice
// at the moment that is as reliable
timer.schedule(new TimerTask() {
public void run() {
try {
etc.getServer().setBlockAt(existingID, x, y, z);
} catch (Throwable t) {}
}
}, 200); // Just in case
}
return true;
}
if (!blacklist.onUse(blockClicked, player)) {
return true;
}
}
if (simulateSponge && blockPlaced.getType() == 19) {
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
Server server = etc.getServer();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
int id = server.getBlockIdAt(ox + cx, oy + cy, oz + cz);
if (id == 8 || id == 9) {
server.setBlockAt(0, ox + cx, oy + cy, oz + cz);
}
}
}
}
}
return false;
}
/**
* Called when a person left clicks a block.
*
* @param player
* @param block
* @return
*/
public boolean onBlockDestroy(Player player, Block block) {
int type = block.getType();
if (blacklist != null) {
if (!blacklist.onDestroyWith(player.getItemInHand(), player)) {
return true;
}
if (!blacklist.onDestroy(block, player)) {
return true;
}
}
if (blockLagFix
&& type != 7 // Bedrock
&& type != 46 // TNT
&& type != 50 // Torch
&& type != 51 // Fire
&& type != 59 // Crops
&& type != 62 // Burning furnace
&& type != 64 // Wooden door
&& type != 69 // Lever
&& type != 71 // Iron door
&& type != 75 // Redstone torch
&& type != 76 // Redstone torch
&& type != 77 // Stone button
) {
// Check other plugins first to see if this block can be
// destroyed. Since this causes the hook to eventually call
// twice, we try to nullify it below
if (canDestroyBlock(player, block)) {
if (block.getStatus() == 3 && canBreakBlock(player, block)) {
int dropItem = type;
int count = 1;
if (type == 1) { dropItem = 4; } // Stone
else if (type == 2) { dropItem = 3; } // Grass
else if (type == 16) { dropItem = 263; } // Coal ore
else if (type == 18) { // Leaves
if (rand.nextDouble() > 0.95) {
dropItem = 6;
} else {
dropItem = 0;
}
}
else if (type == 20) { dropItem = 0; } // Glass
else if (type == 43) { dropItem = 44; } // Double step
else if (type == 47) { dropItem = 0; } // Bookshelves
else if (type == 52) { dropItem = 0; } // Mob spawner
else if (type == 53) { dropItem = 5; } // Wooden stairs
else if (type == 55) { dropItem = 331; } // Redstone wire
else if (type == 56) { dropItem = 264; } // Diamond ore
else if (type == 60) { dropItem = 3; } // Soil
else if (type == 63) { dropItem = 323; } // Sign post
else if (type == 67) { dropItem = 4; } // Cobblestone stairs
else if (type == 68) { dropItem = 323; } // Wall sign
else if (type == 73) { dropItem = 331; count = 4; } // Redstone ore
else if (type == 74) { dropItem = 331; count = 4; } // Glowing redstone ore
else if (type == 78) { dropItem = 0; } // Snow
else if (type == 79) { dropItem = 0; } // Ice
else if (type == 82) { dropItem = 337; count = 4; } // Clay
else if (type == 83) { dropItem = 338; } // Reed
else if (type == 89) { dropItem = 348; } // Lightstone
etc.getServer().setBlockAt(0, block.getX(), block.getY(), block.getZ());
if (dropItem > 0) {
for (int i = 0; i < count; i++) {
etc.getServer().dropItem(block.getX(), block.getY(), block.getZ(),
dropItem, 1);
}
// Drop flint with gravel
if (type == 13) {
if (rand.nextDouble() >= 0.9) {
etc.getServer().dropItem(block.getX(), block.getY(), block.getZ(),
318, 1);
}
}
}
// Now loop this hook back through!
simulateBlockDestroy(player, block);
}
return true;
}
// So we don't have double hook calls caused by the
// plugin/protection check
block.setType(0);
block.setStatus(2);
}
return false;
}
/**
* Called when a person actually breaks the block.
*
* @param player
* @param block
* @return
*/
public boolean onBlockBreak(Player player, Block block) {
if (blacklist != null) {
if (!blacklist.onBreak(block, player)) {
return true;
}
}
return false;
}
/**
* Called when either a sign, chest or furnace is changed.
*
* @param player
* player who changed it
* @param complexBlock
* complex block that changed
* @return true if you want any changes to be reverted
*/
public boolean onComplexBlockChange(Player player, ComplexBlock complexBlock) {
if (blacklist != null) {
if (complexBlock instanceof Chest) {
Block block = new Block(54, complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
if (!blacklist.onSilentUse(block, player)) {
return true;
}
} else if (complexBlock instanceof Furnace) {
int id = etc.getServer().getBlockIdAt(complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
Block block = new Block(id, complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
if (!blacklist.onSilentUse(block, player)) {
return true;
}
} else if (complexBlock instanceof Sign) {
int id = etc.getServer().getBlockIdAt(complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
Block block = new Block(id, complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
if (!blacklist.onSilentUse(block, player)) {
return true;
}
}
}
return false;
}
/**
* Called when either a sign, chest or furnace is sent to a player
*
* @param player
* player who the block is being sent to
* @param complexBlock
* complex block that's being sent
* @return true if you want the chest, furnace or sign to be empty
*/
public boolean onSendComplexBlock(Player player, ComplexBlock complexBlock) {
if (blacklist != null) {
if (complexBlock instanceof Chest) {
Block block = new Block(54, complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
if (!blacklist.onSilentUse(block, player)) {
return true;
}
} else if (complexBlock instanceof Furnace) {
int id = etc.getServer().getBlockIdAt(complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
Block block = new Block(id, complexBlock.getX(),
complexBlock.getY(), complexBlock.getZ());
if (!blacklist.onSilentUse(block, player)) {
return true;
}
}
}
return false;
}
/*
* Called when either a lava block or a lighter tryes to light something on fire.
* block status depends on the light source:
* 1 = lava.
* 2 = lighter (flint + steel).
* 3 = spread (dynamic spreading of fire).
* @param block
* block that the fire wants to spawn in.
*
* @return true if you dont want the fire to ignite.
*/
public boolean onIgnite(Block block, Player player) {
if (preventLavaFire && block.getStatus() == 1) {
return true;
}
if (blockLighter && block.getStatus() == 2) {
return !player.canUseCommand("/uselighter")
&& !player.canUseCommand("/lighter");
}
if (stopFireSpread && block.getStatus() == 3) {
return true;
}
if (disableAllFire && block.getStatus() == 3) {
return true;
}
if (fireNoSpreadBlocks != null && block.getStatus() == 3) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (fireNoSpreadBlocks.contains(etc.getServer().getBlockIdAt(x, y - 1, z))
|| fireNoSpreadBlocks.contains(etc.getServer().getBlockIdAt(x + 1, y, z))
|| fireNoSpreadBlocks.contains(etc.getServer().getBlockIdAt(x - 1, y, z))
|| fireNoSpreadBlocks.contains(etc.getServer().getBlockIdAt(x, y, z - 1))
|| fireNoSpreadBlocks.contains(etc.getServer().getBlockIdAt(x, y, z + 1))) {
return true;
}
}
return false;
}
/*
* Called when a dynamite block or a creeper is triggerd.
* block status depends on explosive compound:
* 1 = dynamite.
* 2 = creeper.
* @param block
* dynamite block/creeper location block.
*
* @return true if you dont the block to explode.
*/
public boolean onExplode(Block block) {
if (blockCreepers && block.getStatus() == 2) {
return true;
}
if (blockTNT && block.getStatus() == 1) {
return true;
}
return false;
}
/*
* Called when fluid wants to flow to a certain block.
* (10 & 11 for lava and 8 & 9 for water)
*
* @param blockFrom
* the block where the fluid came from.
* (blocktype = fluid type)
* @param blockTo
* the block where fluid wants to flow to.
*
*
* @return true if you dont want the substance to flow.
*/
public boolean onFlow(Block blockFrom, Block blockTo) {
int x = blockFrom.getX();
int y = blockFrom.getY();
int z = blockFrom.getZ();
boolean isWater = blockFrom.getType() == 8 || blockFrom.getType() == 9;
boolean isLava = blockFrom.getType() == 10 || blockFrom.getType() == 11;
if (simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
Server server = etc.getServer();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
if (server.getBlockIdAt(ox + cx, oy + cy, oz + cz) == 19) {
return true;
}
}
}
}
}
if (classicWater && isWater) {
int blockBelow = etc.getServer().getBlockIdAt(blockFrom.getX(), blockFrom.getY() - 1, blockFrom.getZ());
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
etc.getServer().setBlockAt(9, blockFrom.getX(), blockFrom.getY(), blockFrom.getZ());
return false;
}
}
if (allowedLavaSpreadOver != null && isLava) {
int targetId = etc.getServer().getBlockIdAt(
blockTo.getX(), blockTo.getY() - 1, blockTo.getZ());
if (!allowedLavaSpreadOver.contains(targetId)) {
return true;
}
}
return false;
}
/**
* Called when the game is checking the physics for a certain block.
* This method is called frequently whenever a nearby block is changed,
* or if the block has just been placed.
* Currently the only supported blocks are sand, gravel and portals.
*
* @param block Block which requires special physics
* @param boolean true if this block has just been placed
* @return true if you do want to stop the default physics for this block
*/
public boolean onBlockPhysics(Block block, boolean placed) {
int id = block.getType();
if (id == 13 && noPhysicsGravel) {
return true;
}
if (id == 12 && noPhysicsSand) {
return true;
}
if (id == 90 && allowPortalAnywhere) {
return true;
}
return false;
}
/**
* Called on player disconnect
*
* @param player
*/
public void onDisconnect(Player player) {
BlacklistEntry.forgetPlayer(player);
}
/**
* Simulate the block destroy hook.
*
* @param player
* @param block
* @return
*/
private boolean simulateBlockDestroy(Player player, Block block) {
plugin.toggleEnabled(); // Prevent infinite loop
try {
block.setStatus(3);;
return !(Boolean)etc.getLoader().callHook(PluginLoader.Hook.BLOCK_DESTROYED,
new Object[]{ player.getUser(), block });
} catch (Throwable t) {
return true;
} finally {
plugin.toggleEnabled();
}
}
/**
* Checks if a block can be broken.
*
* @param player
* @param block
* @return
*/
private boolean canBreakBlock(Player player, Block orig) {
try {
Block block = etc.getServer().getBlockAt(
orig.getX(), orig.getY(), orig.getZ());
return !(Boolean)etc.getLoader().callHook(PluginLoader.Hook.BLOCK_BROKEN,
new Object[]{ player.getUser(), block });
} catch (Throwable t) {
return true;
}
}
/**
* Checks if a block can be destroyed.
*
* @param player
* @param block
* @return
*/
private boolean canDestroyBlock(Player player, Block block) {
plugin.toggleEnabled(); // Prevent infinite loop
try {
return !(Boolean)etc.getLoader().callHook(PluginLoader.Hook.BLOCK_DESTROYED,
new Object[]{ player.getUser(), block });
} catch (Throwable t) {
return true;
} finally {
plugin.toggleEnabled();
}
}
/**
* Call to disable the plugin.
*/
public void disable() {
if (blacklist != null) {
blacklist.getLogger().close();
}
}
}
@@ -1,64 +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;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Used for formatting.
*
* @author sk89q
*/
public class ConsoleLogFormat extends Formatter {
public String format(LogRecord record) {
StringBuilder text = new StringBuilder();
Level level = record.getLevel();
if (level == Level.FINEST) {
text.append("[FINEST] ");
} else if (level == Level.FINER) {
text.append("[FINER] ");
} else if (level == Level.FINE) {
text.append("[FINE] ");
} else if (level == Level.INFO) {
text.append("[INFO] ");
} else if (level == Level.WARNING) {
text.append("[WARNING] ");
} else if (level == Level.SEVERE) {
text.append("[SEVERE] ");
}
text.append(record.getMessage());
text.append("\r\n");
Throwable t = record.getThrown();
if (t != null) {
StringWriter writer = new StringWriter();
t.printStackTrace(new PrintWriter(writer));
text.append(writer.toString());
}
return text.toString();
}
}
+35
View File
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>default</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}-${project.version}.jar</source>
<destName>WorldGuard.jar</destName>
<outputDirectory>/</outputDirectory>
<filtered>false</filtered>
</file>
<file>
<source>README.html</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
</files>
<fileSets>
<fileSet>
<includes>
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>blacklist_table.sql</include>
</includes>
</fileSet>
</fileSets>
</assembly>
@@ -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;
import com.sk89q.worldedit.Vector;
public abstract class LocalPlayer {
/**
* Get a player's name.
*
* @return
*/
public abstract String getName();
/**
* Returns true if the player is inside a group.
*
* @param group
* @return
*/
public abstract boolean hasGroup(String group);
/**
* Get the player's position.
*
* @return
*/
public abstract Vector getPosition();
/**
* Kick the player.
*
* @param msg
*/
public abstract void kick(String msg);
/**
* Ban the player.
*
* @param msg
*/
public abstract void ban(String msg);
/**
* Send the player a message;
*
* @param msg
*/
public abstract void printRaw(String msg);
/**
* Get the player's list of groups.
*
* @return
*/
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)) {
return false;
}
return ((LocalPlayer)obj).getName().equals(getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
}
@@ -1,47 +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.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Level;
/**
* Used for formatting.
*
* @author sk89q
*/
public class SimpleLogFormat extends Formatter {
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public String format(LogRecord record) {
StringBuilder text = new StringBuilder();
Level level = record.getLevel();
text.append("[");
text.append(dateFormat.format(new Date(record.getMillis())));
text.append("] ");
text.append(record.getMessage());
text.append("\r\n");
return text.toString();
}
}
// $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;
}
}
@@ -17,6 +17,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
@@ -24,12 +26,16 @@ import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.*;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class Blacklist {
public abstract class Blacklist {
/**
* Logger.
*/
@@ -44,11 +50,23 @@ public class Blacklist {
* Logger.
*/
private BlacklistLogger blacklistLogger = new BlacklistLogger();
/**
* Blacklist contains on-acquire events.
* Last event.
*/
private boolean hasOnAcquire;
private BlacklistEvent lastEvent;
/**
* Used to prevent flooding.
*/
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
private boolean useAsWhitelist;
public Blacklist(Boolean useAsWhitelist)
{
this.useAsWhitelist = useAsWhitelist;
}
/**
* Returns whether the list is empty.
@@ -61,11 +79,32 @@ public 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.
*
@@ -76,190 +115,21 @@ public class Blacklist {
}
/**
* Called on block destruction. Returns true to let the action pass
* through.
*
* @param block
* @param player
* Method to handle the event.
*
* @param event
* @param forceRepeat
* @param silent
* @return
*/
public boolean onDestroy(final Block block, final Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
List<BlacklistEntry> entries = getEntries(event.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDestroy(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on block break. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onBreak(final Block block, final Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onBreak(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on left click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDestroyWith(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDestroyWith(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on right click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onCreate(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onCreate(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onUse(Block block, Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onUse(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentUse(Block block, Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onSilentUse(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on drop. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDrop(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDrop(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onAcquire(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onAcquire(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentAcquire(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onSilentAcquire(item, player)) {
if (!entry.check(useAsWhitelist, event, forceRepeat, silent)) {
ret = false;
}
}
@@ -270,7 +140,6 @@ public class Blacklist {
* Load the blacklist.
*
* @param file
* @return
* @throws IOException
*/
public void load(File file) throws IOException {
@@ -282,8 +151,6 @@ public class Blacklist {
input = new FileReader(file);
BufferedReader buff = new BufferedReader(input);
hasOnAcquire = false;
String line;
List<BlacklistEntry> currentEntries = null;
while ((line = buff.readLine()) != null) {
@@ -306,7 +173,7 @@ public class Blacklist {
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = etc.getDataSource().getItem(item.trim());
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
+ item);
@@ -338,23 +205,21 @@ public class Blacklist {
for (BlacklistEntry entry : currentEntries) {
if (parts[0].equalsIgnoreCase("ignore-groups")) {
entry.setIgnoreGroups(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-destroy")) {
entry.setDestroyActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("ignore-perms")) {
entry.setIgnorePermissions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-break")) {
entry.setBreakActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-left")
|| parts[0].equalsIgnoreCase("on-destroy-with")) {
} else if (parts[0].equalsIgnoreCase("on-destroy-with")) {
entry.setDestroyWithActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-right")
|| parts[0].equalsIgnoreCase("on-create")) {
entry.setCreateActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-right-on")
|| parts[0].equalsIgnoreCase("on-use")) {
} else if (parts[0].equalsIgnoreCase("on-place")) {
entry.setPlaceActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-interact")) {
entry.setInteractActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-use")) {
entry.setUseActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-drop")) {
entry.setDropActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-acquire")) {
hasOnAcquire = true;
entry.setAcquireActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("message")) {
entry.setMessage(parts[1].trim());
@@ -385,13 +250,81 @@ public class Blacklist {
}
}
}
/**
* Blacklist contains on-acquire events.
* Get the last event.
*
* @return
*/
public boolean hasOnAcquire() {
return hasOnAcquire;
public BlacklistEvent getLastEvent() {
return lastEvent;
}
/**
* Notify administrators.
*
* @param event
* @param comment
*/
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + event.getPlayer().getName()
+ ChatColor.GOLD + " (" + event.getDescription() + ") "
+ ChatColor.WHITE
+ getFriendlyItemName(event.getType())
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
/**
* Sends a notification to all subscribing users.
*
* @param msg
*/
public abstract void broadcastNotification(String msg);
/**
* Forget a player.
*
* @param player
*/
public void forgetPlayer(LocalPlayer player) {
lastAffected.remove(player.getName());
}
/**
* Forget all players.
*/
public void forgetAllPlayers() {
lastAffected.clear();
}
/**
* Get an item's ID from its name.
*
* @param name
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
if (type != null) {
return type.getID();
} else {
return -1;
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -0,0 +1,423 @@
// $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.blacklist;
import java.util.Set;
import java.util.HashSet;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class BlacklistEntry {
/**
* Parent blacklist entry.
*/
private Blacklist blacklist;
/**
* List of groups to not affect.
*/
private Set<String> ignoreGroups;
/**
* List of permissions to not affect.
*/
private Set<String> ignorePermissions;
private String[] breakActions;
private String[] destroyWithActions;
private String[] placeActions;
private String[] interactActions;
private String[] useActions;
private String[] dropActions;
private String[] acquireActions;
private String message;
private String comment;
/**
* Construct the object.
*
* @param blacklist
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
}
/**
* @return the ignoreGroups
*/
public String[] getIgnoreGroups() {
return ignoreGroups.toArray(new String[ignoreGroups.size()]);
}
/**
* @return the ignoreGroups
*/
public String[] getIgnorePermissions() {
return ignorePermissions.toArray(new String[ignorePermissions.size()]);
}
/**
* @param ignoreGroups the ignoreGroups to set
*/
public void setIgnoreGroups(String[] ignoreGroups) {
Set<String> ignoreGroupsSet = new HashSet<String>();
for (String group : ignoreGroups) {
ignoreGroupsSet.add(group.toLowerCase());
}
this.ignoreGroups = ignoreGroupsSet;
}
/**
* @param ignorePermissions the ignorePermissions to set
*/
public void setIgnorePermissions(String[] ignorePermissions) {
Set<String> ignorePermissionsSet = new HashSet<String>();
for (String perm : ignorePermissions) {
ignorePermissionsSet.add(perm);
}
this.ignorePermissions = ignorePermissionsSet;
}
/**
* @return
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param actions
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return
*/
public String[] getInteractActions() {
return interactActions;
}
/**
* @param actions
*/
public void setInteractActions(String[] actions) {
this.interactActions = actions;
}
/**
* @return
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Returns true if this player should be ignored.
*
* @param player
* @return
*/
public boolean shouldIgnore(LocalPlayer player) {
if (ignoreGroups != null) {
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
return true;
}
}
}
if (ignorePermissions != null) {
for (String perm : ignorePermissions) {
if (player.hasPermission(perm)) {
return true;
}
}
}
return false;
}
/**
* Get the associated actions with an event.
*
* @param event
* @return
*/
private String[] getActions(BlacklistEvent event) {
if (event instanceof BlockBreakBlacklistEvent) {
return breakActions;
} else if (event instanceof BlockPlaceBlacklistEvent) {
return placeActions;
} else if (event instanceof BlockInteractBlacklistEvent) {
return interactActions;
} else if (event instanceof DestroyWithBlacklistEvent) {
return destroyWithActions;
} else if (event instanceof ItemAcquireBlacklistEvent) {
return acquireActions;
} else if (event instanceof ItemDropBlacklistEvent) {
return dropActions;
} else if (event instanceof ItemUseBlacklistEvent) {
return useActions;
} else {
return null;
}
}
/**
* Method to handle the event.
*
* @param useAsWhitelist
* @param event
* @param forceRepeat
* @param silent
* @return
*/
public boolean check(boolean useAsWhitelist, BlacklistEvent event, boolean forceRepeat, boolean silent) {
LocalPlayer player = event.getPlayer();
if (shouldIgnore(player)) {
return true;
}
String name = player.getName();
long now = System.currentTimeMillis();
boolean repeating = false;
// Check to see whether this event is being repeated
BlacklistTrackedEvent tracked = blacklist.lastAffected.get(name);
if (tracked != null) {
if (tracked.matches(event, now)) {
repeating = true;
}
} else {
blacklist.lastAffected.put(name, new BlacklistTrackedEvent(event, now));
}
String actions[] = getActions(event);
boolean ret = useAsWhitelist ? false : true;
// Nothing to do
if (actions == null) {
return useAsWhitelist ? false : true;
}
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Allow
} else if (action.equalsIgnoreCase("allow")) {
if (silent) {
return true;
}
ret = true;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (silent) {
continue;
}
if (this.message != null) {
player.kick(String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.kick("You can't " + event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
// Ban
} else if (action.equalsIgnoreCase("ban")) {
if (silent) {
continue;
}
if (this.message != null) {
player.ban("Banned: " + String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.ban("Banned: You can't "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
} else if (!silent && (!repeating || forceRepeat)) {
// Notify
if (action.equalsIgnoreCase("notify")) {
blacklist.notify(event, comment);
// Log
} else if (action.equalsIgnoreCase("log")) {
blacklist.getLogger().logEvent(event, comment);
// Tell
} else if (action.equalsIgnoreCase("tell")) {
if (this.message != null) {
player.printRaw(ChatColor.YELLOW +
String.format(message, getFriendlyItemName(event.getType()))
+ ".");
} else {
player.printRaw(ChatColor.YELLOW + "You're not allowed to "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()) + ".");
}
}
}
}
return ret;
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -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.blacklist;
import java.util.Set;
import java.util.HashSet;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.loggers.BlacklistLoggerHandler;
/**
*
* @author sk89q
*/
public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* List of logger handlers.
*/
private Set<BlacklistLoggerHandler> handlers
= new HashSet<BlacklistLoggerHandler>();
/**
* Add a handler.
*
* @param handler
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Add a handler.
*
* @param handler
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
}
/**
* Add a handler.
*/
public void clearHandlers() {
handlers.clear();
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logEvent(event, comment);
}
}
/**
* Close the connection.
*/
public void close() {
for (BlacklistLoggerHandler handler : handlers) {
handler.close();
}
}
}
@@ -17,50 +17,32 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class BlacklistTrackedEvent {
private int id;
private BlacklistEvent event;
private long time;
/**
* Construct the object.
*
* @param id
* @param event
* @param time
*/
public BlacklistTrackedEvent(int id, long time) {
this.id = id;
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
this.time = time;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the time
*/
public long getTime() {
return time;
}
/**
* @param time the time to set
*/
public void setTime(long time) {
this.time = time;
public boolean matches(BlacklistEvent other, long now) {
return other.getType() == event.getType()
&& time > now - 3000
&& other.getClass() == event.getClass();
}
}
@@ -0,0 +1,85 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* Represents a blacklist event.
*
* @author sk89q
*/
public abstract class BlacklistEvent {
private Vector pos;
private int type;
/**
* Holds the player that triggered the event.
*/
private LocalPlayer player;
/**
* Construct the object.
*
* @param player
* @param pos
* @param type
*/
public BlacklistEvent(LocalPlayer player, Vector pos, int type) {
this.player = player;
this.pos = pos;
this.type = type;
}
/**
* Get the player.
*
* @return
*/
public LocalPlayer getPlayer() {
return player;
}
/**
* Get the position.
*
* @return
*/
public Vector getPosition() {
return pos;
}
/**
* Get the type.
*
* @return
*/
public int getType() {
return type;
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
public abstract String getDescription();
}
@@ -0,0 +1,29 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public abstract class BlockBlacklistEvent extends BlacklistEvent {
public BlockBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
public BlockBreakBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "break";
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
public BlockInteractBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "interact with";
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
public BlockPlaceBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "place";
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class DestroyWithBlacklistEvent extends BlacklistEvent {
public DestroyWithBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "destroy with";
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
public ItemAcquireBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "acquire";
}
}
@@ -0,0 +1,29 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public abstract class ItemBlacklistEvent extends BlacklistEvent {
public ItemBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemDropBlacklistEvent extends ItemBlacklistEvent {
public ItemDropBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "drop";
}
}
@@ -0,0 +1,39 @@
// $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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemUseBlacklistEvent extends ItemBlacklistEvent {
public ItemUseBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "use";
}
}
@@ -0,0 +1,42 @@
// $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.blacklist.loggers;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
* Interface for loggers for the blacklist.
*
* @author sk89q
*/
public interface BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param comment
*/
public void logEvent(BlacklistEvent event, String comment);
/**
* Close the logger.
*/
public void close();
}
@@ -0,0 +1,126 @@
// $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.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.events.*;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private String worldName;
public ConsoleLoggerHandler(String worldName)
{
this.worldName = worldName;
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "WorldGuard: [" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
/**
* Close the connection.
*/
public void close() {
}
}
@@ -0,0 +1,205 @@
// $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.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* DSN.
*/
private String dsn;
/**
* Username.
*/
private String user;
/**
* Password.
*/
private String pass;
/**
* Table.
*/
private String table;
/**
* World name.
*/
private String worldName;
/**
* Database connection.
*/
private Connection conn;
/**
* Construct the object.
*
* @param dsn
* @param user
* @param pass
* @param table
* @param worldName
*/
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;
}
/**
* Gets the database connection.
*
* @return
* @throws SQLException
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(dsn, user, pass);
}
return conn;
}
/**
* Log an event to the database.
*
* @param event
* @param name
* @param x
* @param y
* @param z
* @param item
* @param comment
*/
private void logEvent(String event, LocalPlayer player, Vector pos, int item,
String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, world, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
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: "
+ e.getMessage());
}
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent("BREAK", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent("PLACE", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block interact
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent("INTERACT", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent("DESTROY_WITH", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent("ACQUIRE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent("DROP", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent("USE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Unknown
} else {
logEvent("UNKNOWN", event.getPlayer(), event.getPlayer().getPosition(),
-1, comment);
}
}
/**
* Close the connection.
*/
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
}
}
}
@@ -17,17 +17,18 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.loggers;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.*;
import java.util.regex.*;
import java.util.Map;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.*;
import java.text.SimpleDateFormat;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
/**
*
@@ -56,6 +57,10 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* Path pattern.
*/
private String pathPattern;
/**
* World name.
*/
private String worldName;
/**
* Cache of writers.
*/
@@ -66,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;
}
/**
@@ -76,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;
}
/**
@@ -93,8 +102,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
Pattern p = Pattern.compile("%.");
Matcher m = p.matcher(pathPattern);
Matcher m = pattern.matcher(pathPattern);
StringBuffer buffer = new StringBuffer();
// Pattern replacements
@@ -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));
@@ -143,7 +157,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* @param player
* @param message
*/
private void log(Player player, String message, String comment) {
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
try {
String date = dateFormat.format(new Date());
@@ -207,76 +221,66 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
}
/**
* Log a block destroy attempt.
*
* @param player
* @param block
* Gets the coordinates in text form for the log.
*
* @param pos
* @return
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
log(player, "Tried to destroy " + getFriendlyItemName(block.getType()),
comment);
private String getCoordinates(Vector pos) {
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
log(player, "Tried to break " + getFriendlyItemName(block.getType()),
comment);
private void logEvent(BlacklistEvent event, String text, int id, Vector pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + getFriendlyItemName(id)
+ " " + getCoordinates(pos), comment);
}
/**
* Log a right click on attempt.
* Log an event.
*
* @param player
* @param block
* @param event
*/
public void logUseAttempt(Player player, Block block, String comment) {
log(player, "Tried to use " + getFriendlyItemName(block.getType()),
comment);
}
/**
* Log an attempt to destroy with an item.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
log(player, "Tried to destroy with " + getFriendlyItemName(item), comment);
}
/**
* Log a block creation attempt.
*
* @param player
* @param item
*/
public void logCreateAttempt(Player player, int item, String comment) {
log(player, "Tried to create " + getFriendlyItemName(item), comment);
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
log(player, "Tried to drop " + getFriendlyItemName(item), comment);
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
log(player, "Tried to acquire " + getFriendlyItemName(item), comment);
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent(event, "break", evt.getType(), evt.getPosition(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent(event, "place", evt.getType(), evt.getPosition(), comment);
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent(event, "interact with", evt.getType(), evt.getPosition(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent(event, "destroy with", evt.getType(), evt.getPosition(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent(event, "acquire", evt.getType(), evt.getPosition(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent(event, "drop", evt.getType(), evt.getPosition(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent(event, "use", evt.getType(), evt.getPosition(), comment);
// Unknown
} else {
log(event.getPlayer(), "Unknown event: "
+ event.getClass().getCanonicalName(), comment);
}
}
/**
@@ -285,7 +289,12 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* @param id
*/
private static String getFriendlyItemName(int id) {
return etc.getDataSource().getItem(id) + " (#" + id + ")";
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
/**
@@ -17,6 +17,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.loggers;
import java.io.*;
/**
@@ -40,6 +42,7 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Construct the object.
*
* @param path
* @param writer
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
@@ -73,8 +76,6 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Update last use time.
*
* @return
*/
public void updateLastUse() {
lastUse = System.currentTimeMillis();
@@ -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.bukkit;
import com.sk89q.worldguard.blacklist.Blacklist;
public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist);
this.plugin = plugin;
}
@Override
public void broadcastNotification(String msg) {
plugin.broadcastNotification(msg);
}
}
@@ -0,0 +1,77 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BukkitPlayer extends LocalPlayer {
private Player player;
private WorldGuardPlugin plugin;
public BukkitPlayer(WorldGuardPlugin plugin, Player player) {
this.plugin = plugin;
this.player = player;
}
@Override
public String getName() {
return player.getName();
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(player, group);
}
@Override
public Vector getPosition() {
Location loc = player.getLocation();
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
@Override
public void kick(String msg) {
player.kickPlayer(msg);
}
@Override
public void ban(String msg) {
player.kickPlayer(msg);
}
@Override
public String[] getGroups() {
return plugin.getGroups(player);
}
@Override
public void printRaw(String msg) {
player.sendMessage(msg);
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
}
@@ -0,0 +1,222 @@
// $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.util.List;
import com.sk89q.worldedit.blocks.BlockType;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
public class BukkitUtil {
private BukkitUtil() {
}
/**
* Converts the location of a Bukkit block to a WorldEdit vector.
*
* @param block
* @return
*/
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
/**
* Converts a Bukkit location to a WorldEdit vector.
*
* @param loc
* @return
*/
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
/**
* Converts a Bukkit vector to a WorldEdit vector.
*
* @param vector
* @return
*/
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
}
/**
* Converts a WorldEdit vector to a Bukkit location.
*
* @param world
* @param vec
* @return
*/
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Matches one player based on name.
*
* @param server
* @param name
* @return
*/
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
return null;
}
return players.get(0);
}
/**
* Drops a sign item and removes a sign.
*
* @param block
*/
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(Material.SIGN));
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
* @param world
* @param ox
* @param oy
* @param oz
*/
public static 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
* @return
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
return true;
} else {
return false;
}
}
/**
* 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
* a series of two free blocks. The player will be teleported to
* that free position.
*
* @param player
*/
public static void findFreePosition(Player player) {
Location loc = player.getLocation();
int x = loc.getBlockX();
int y = Math.max(0, loc.getBlockY());
int origY = y;
int z = loc.getBlockZ();
World world = player.getWorld();
byte free = 0;
while (y <= 129) {
if (BlockType.canPassThrough(world.getBlockTypeIdAt(x, y, z))) {
free++;
} else {
free = 0;
}
if (free == 2) {
if (y - 1 != origY || y == 1) {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
if (y <= 2 && world.getBlockAt(x,0,z).getType() == Material.AIR) {
world.getBlockAt(x,0,z).setTypeId(20);
loc.setY(2);
}
player.setFallDistance(0F);
player.teleport(loc);
}
return;
}
y++;
}
}
/**
* Replace color macros in a string. The macros are in the form of `[char]
* where char represents the color. R is for red, Y is for yellow,
* G is for green, C is for cyan, B is for blue, and P is for purple.
* The uppercase versions of those are the darker shades, while the
* lowercase versions are the lighter shades. For white, it's 'w', and
* 0-2 are black, dark grey, and grey, respectively.
*
* @param str
* @return color-coded string
*/
public static String replaceColorMacros(String str) {
str = str.replace("&r", ChatColor.RED.toString());
str = str.replace("&R", ChatColor.DARK_RED.toString());
str = str.replace("&y", ChatColor.YELLOW.toString());
str = str.replace("&Y", ChatColor.GOLD.toString());
str = str.replace("&g", ChatColor.GREEN.toString());
str = str.replace("&G", ChatColor.DARK_GREEN.toString());
str = str.replace("&c", ChatColor.AQUA.toString());
str = str.replace("&C", ChatColor.DARK_AQUA.toString());
str = str.replace("&b", ChatColor.BLUE.toString());
str = str.replace("&B", ChatColor.DARK_BLUE.toString());
str = str.replace("&p", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("&P", ChatColor.DARK_PURPLE.toString());
str = str.replace("&0", ChatColor.BLACK.toString());
str = str.replace("&1", ChatColor.DARK_GRAY.toString());
str = str.replace("&2", ChatColor.GRAY.toString());
str = str.replace("&w", ChatColor.WHITE.toString());
return str;
}
}
@@ -0,0 +1,228 @@
// $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 {
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace any setting in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" +
"# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
/**
* 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;
public boolean useRegionsScheduler;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
/**
* 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);
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
autoGodMode = config.getBoolean(
"auto-invincible-permission", false);
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.save();
}
/**
* 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,169 @@
// $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.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import org.bukkit.World;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
/**
* This processes per-player state information and is also meant to be used
* as a scheduled task.
*
* @author sk89q
*/
public class FlagStateManager implements Runnable {
public static final int RUN_DELAY = 20;
private WorldGuardPlugin plugin;
private Map<String, PlayerFlagState> states;
/**
* Construct the object.
*
* @param plugin
*/
public FlagStateManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
states = new HashMap<String, PlayerFlagState>();
}
/**
* Run the task.
*/
public void run() {
Player[] players = plugin.getServer().getOnlinePlayers();
ConfigurationManager config = plugin.getGlobalStateManager();
for (Player player : players) {
WorldConfiguration worldConfig = config.get(player.getWorld());
if (!worldConfig.useRegions) {
continue;
}
PlayerFlagState state;
synchronized (this) {
state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
}
Vector playerLocation = toVector(player.getLocation());
RegionManager regionManager = plugin.getGlobalRegionManager()
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
processHeal(applicable, player, state);
}
}
/**
* Process healing for a player.
*
* @param applicable
* @param player
* @param state
*/
private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (player.getHealth() >= 20 && healAmount > 0) {
return;
}
if (healDelay <= 0 && healAmount > 0) {
player.setHealth(20);
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
player.setHealth(Math.min(20, Math.max(0, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
/**
* Forget a player.
*
* @param player
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
}
/**
* Get a player's flag state.
*
* @param player
* @return
*/
public synchronized PlayerFlagState getState(Player player) {
PlayerFlagState state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
return state;
}
/**
* Keeps state per player.
*/
public static class PlayerFlagState {
public long lastHeal;
public String lastGreeting;
public String lastFarewell;
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
public int lastBlockZ;
}
}
@@ -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;
}
}
@@ -0,0 +1,69 @@
// $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.util.logging.Handler;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
/**
* Sends all logger messages to a player.
*
* @author sk89q
*/
public class LoggerToChatHandler extends Handler {
/**
* Player.
*/
private CommandSender player;
/**
* Construct the object.
*
* @param 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,335 @@
// $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.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;
import com.sk89q.worldguard.util.LogListBlock;
public class ReportWriter {
private static final SimpleDateFormat dateFmt =
new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
private Date date = new Date();
private StringBuilder output = new StringBuilder();
public ReportWriter(WorldGuardPlugin plugin) {
appendReportHeader(plugin);
appendServerInformation(plugin.getServer());
appendPluginInformation(plugin.getServer().getPluginManager().getPlugins());
appendWorldInformation(plugin.getServer().getWorlds());
appendGlobalConfiguration(plugin.getGlobalStateManager());
appendWorldConfigurations(plugin, plugin.getServer().getWorlds(),
plugin.getGlobalRegionManager(), plugin.getGlobalStateManager());
appendln("-------------");
appendln("END OF REPORT");
appendln();
}
protected static String repeat(String str, int n) {
if(str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
protected void appendln(String text) {
output.append(text);
output.append("\r\n");
}
protected void appendln(String text, Object ... args) {
output.append(String.format(text, args));
output.append("\r\n");
}
protected void append(LogListBlock log) {
output.append(log.toString());
}
protected void appendln() {
output.append("\r\n");
}
protected void appendHeader(String text) {
String rule = repeat("-", text.length());
output.append(rule);
output.append("\r\n");
appendln(text);
output.append(rule);
output.append("\r\n");
appendln();
}
private void appendReportHeader(WorldGuardPlugin plugin) {
appendln("WorldGuard Configuration Report");
appendln("Generated " + dateFmt.format(date));
appendln();
appendln("Version: " + plugin.getDescription().getVersion());
appendln();
}
private void appendGlobalConfiguration(ConfigurationManager config) {
appendHeader("Global Configuration");
LogListBlock log = new LogListBlock();
LogListBlock configLog = log.putChild("Configuration");
Class<? extends ConfigurationManager> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
}
}
append(log);
appendln();
}
private void appendServerInformation(Server server) {
appendHeader("Server Information");
LogListBlock log = new LogListBlock();
Runtime runtime = Runtime.getRuntime();
log.put("Java", "%s %s (%s)",
System.getProperty("java.vendor"),
System.getProperty("java.version"),
System.getProperty("java.vendor.url"));
log.put("Operating system", "%s %s (%s)",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
log.put("Available processors", runtime.availableProcessors());
log.put("Free memory", runtime.freeMemory() / 1024 / 1024 + " MB");
log.put("Max memory", runtime.maxMemory() / 1024 / 1024 + " MB");
log.put("Total memory", runtime.totalMemory() / 1024 / 1024 + " MB");
log.put("Server ID", server.getServerId());
log.put("Server name", server.getServerName());
log.put("Implementation", server.getVersion());
//log.put("Address", server.getIp(), server.getPort());
log.put("Player count", "%d/%d",
server.getOnlinePlayers().length, server.getMaxPlayers());
append(log);
appendln();
}
private void appendPluginInformation(Plugin[] plugins) {
appendHeader("Plugins");
LogListBlock log = new LogListBlock();
for (Plugin plugin : plugins) {
log.put(plugin.getDescription().getName(), plugin.getDescription().getVersion());
}
append(log);
appendln();
/*appendHeader("Plugin Information");
log = new LogListBlock();
for (Plugin plugin : plugins) {
log.putChild(plugin.getDescription().getName())
.put("Data folder", plugin.getDataFolder())
.put("Website", plugin.getDescription().getWebsite())
.put("Entry point", plugin.getDescription().getMain());
}
append(log);
appendln();*/
}
private void appendWorldInformation(List<World> worlds) {
appendHeader("Worlds");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
int loadedChunkCount = world.getLoadedChunks().length;
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock entitiesLog = worldLog.putChild("Entities");
infoLog.put("ID", world.getId());
infoLog.put("Environment", world.getEnvironment().toString());
infoLog.put("Player count", world.getPlayers().size());
infoLog.put("Entity count", world.getEntities().size());
infoLog.put("Loaded chunk count", loadedChunkCount);
infoLog.put("Spawn location", world.getSpawnLocation());
infoLog.put("Raw time", world.getFullTime());
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()) {
entitiesLog.put(entry.getKey().getSimpleName(),
"%d [%f]",
entry.getValue(),
(float) (entry.getValue() / (double) loadedChunkCount));
}
i++;
}
append(log);
appendln();
}
private void appendWorldConfigurations(WorldGuardPlugin plugin, List<World> worlds,
GlobalRegionManager regionMgr, ConfigurationManager mgr) {
appendHeader("World Configurations");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock configLog = worldLog.putChild("Configuration");
LogListBlock blacklistLog = worldLog.putChild("Blacklist");
LogListBlock regionsLog = worldLog.putChild("Region manager");
infoLog.put("Configuration file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/config.yml")).getAbsoluteFile());
infoLog.put("Blacklist file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/blacklist.txt")).getAbsoluteFile());
infoLog.put("Regions file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/regions.yml")).getAbsoluteFile());
WorldConfiguration config = mgr.get(world);
Class<? extends WorldConfiguration> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
}
}
if (config.getBlacklist() == null) {
blacklistLog.put("State", "DISABLED");
} else {
blacklistLog.put("State", "Enabled");
blacklistLog.put("Number of items",
config.getBlacklist().getItemCount());
blacklistLog.put("Is whitelist",
config.getBlacklist().isWhitelist());
}
RegionManager worldRegions = regionMgr.get(world);
regionsLog.put("Type", worldRegions.getClass().getCanonicalName());
regionsLog.put("Number of regions", worldRegions.getRegions().size());
LogListBlock globalRegionLog = regionsLog.putChild("Global region");
ProtectedRegion globalRegion = worldRegions.getRegion("__global__");
if (globalRegion == null) {
globalRegionLog.put("Status", "UNDEFINED");
} else {
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (flag instanceof StateFlag) {
globalRegionLog.put(flag.getName(),
globalRegion.getFlag(flag));
}
}
}
}
append(log);
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,124 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
import org.bukkit.World;
public class SpongeUtil {
/**
* Remove water around a sponge.
*
* @param plugin
* @param world
* @param ox
* @param oy
* @param oz
*/
public static void clearSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
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 plugin
* @param world
* @param ox
* @param oy
* @param oz
*/
public static void addSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
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);
}
}
}
}
}
@@ -0,0 +1,484 @@
// $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 com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.chest.SignChestProtection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
/**
* Holds the configuration for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class WorldConfiguration {
public static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's world configuration file\r\n" +
"#\r\n" +
"# This is a world configuration file. Anything placed into here will only\r\n" +
"# affect this world. If you don't put anything in this file, then the\r\n" +
"# settings will be inherited from the main configuration file.\r\n" +
"#\r\n" +
"# If you see {} below, that means that there are NO entries in this file.\r\n" +
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private static final Logger logger = Logger
.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
private String worldName;
private Configuration parentConfig;
private Configuration config;
private File configFile;
private File blacklistFile;
private Blacklist blacklist;
private ChestProtection chestProtection = new SignChestProtection();
/* Configuration data start */
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean enforceOneSession;
public boolean itemDurability;
public boolean classicWater;
public boolean simulateSponge;
public int spongeRadius;
public boolean 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 disableLightningDamage;
public boolean disableDrowningDamage;
public boolean disableSuffocationDamage;
public boolean teleportOnSuffocation;
public boolean disableVoidDamage;
public boolean teleportOnVoid;
public boolean disableExplosionDamage;
public boolean disableMobDamage;
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;
public boolean signChestProtection;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
public boolean preventLightningFire;
public Set<Integer> disallowedLightningBlocks;
public boolean disableThunder;
public boolean disableWeather;
public boolean alwaysRaining;
public boolean alwaysThundering;
public boolean disablePigZap;
public boolean disableCreeperPower;
public boolean disableHealthRegain;
public boolean disableMushroomSpread;
public boolean disableIceMelting;
public boolean disableSnowMelting;
public boolean disableSnowFormation;
public boolean disableIceFormation;
public boolean disableLeafDecay;
/* 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;
this.parentConfig = plugin.getConfiguration();
WorldGuardPlugin.createDefaultConfiguration(configFile, "config_world.yml");
WorldGuardPlugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
config = new Configuration(this.configFile);
loadConfiguration();
logger.info("WorldGuard: Loaded configuration for world '" + worldName + '"');
}
private boolean getBoolean(String node, boolean def) {
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return parentConfig.getBoolean(node, def);
}
}
private String getString(String node, String def) {
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return parentConfig.getString(node, def);
}
}
private int getInt(String node, int def) {
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return parentConfig.getInt(node, def);
}
}
private double getDouble(String node, double def) {
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return parentConfig.getDouble(node, def);
}
}
private List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res;
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
} else {
res = parentConfig.getIntList(node, def);
}
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
return res;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res;
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
} else {
res = parentConfig.getStringList(node, def);
}
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
return res;
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
config.load();
opPermissions = getBoolean("op-permissions", true);
enforceOneSession = getBoolean("protection.enforce-single-session", true);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
classicWater = getBoolean("simulation.classic-water", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
pumpkinScuba = getBoolean("pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
noPhysicsGravel = getBoolean("physics.no-physics-gravel", false);
noPhysicsSand = getBoolean("physics.no-physics-sand", false);
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
blockTNT = getBoolean("ignition.block-tnt", false);
blockLighter = getBoolean("ignition.block-lighter", false);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", true);
disableFireSpread = getBoolean("fire.disable-all-fire-spread", false);
disableFireSpreadBlocks = new HashSet<Integer>(getIntList("fire.disable-fire-spread-blocks", null));
allowedLavaSpreadOver = new HashSet<Integer>(getIntList("fire.lava-spread-blocks", null));
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
loginProtection = getInt("spawn.login-protection", 3);
spawnProtection = getInt("spawn.spawn-protection", 0);
kickOnDeath = getBoolean("spawn.kick-on-death", false);
exactRespawn = getBoolean("spawn.exact-respawn", false);
teleportToHome = getBoolean("spawn.teleport-to-home-on-death", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
disableFireDamage = getBoolean("player-damage.disable-fire-damage", false);
disableLightningDamage = getBoolean("player-damage.disable-lightning-damage", false);
disableDrowningDamage = getBoolean("player-damage.disable-drowning-damage", false);
disableSuffocationDamage = getBoolean("player-damage.disable-suffocation-damage", false);
disableContactDamage = getBoolean("player-damage.disable-contact-damage", false);
teleportOnSuffocation = getBoolean("player-damage.teleport-on-suffocation", false);
disableVoidDamage = getBoolean("player-damage.disable-void-damage", false);
teleportOnVoid = getBoolean("player-damage.teleport-on-void-falling", false);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
signChestProtection = getBoolean("chest-protection.enable", false);
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<Integer>(getIntList("weather.prevent-lightning-strike-blocks", null));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
disableWeather = getBoolean("weather.disable-weather", false);
disablePigZap = getBoolean("weather.disable-pig-zombification", false);
disableCreeperPower = getBoolean("weather.disable-powered-creepers", false);
alwaysRaining = getBoolean("weather.always-raining", false);
alwaysThundering = getBoolean("weather.always-thundering", false);
disableMushroomSpread = getBoolean("dynamics.disable-mushroom-spread", false);
disableIceMelting = getBoolean("dynamics.disable-ice-melting", false);
disableSnowMelting = getBoolean("dynamics.disable-snow-melting", false);
disableSnowFormation = getBoolean("dynamics.disable-snow-formation", false);
disableIceFormation = getBoolean("dynamics.disable-ice-formation", false);
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
useRegions = getBoolean("regions.enable", true);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
regionWand = getInt("regions.wand", 287);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player", 7);
useiConomy = getBoolean("iconomy.enable", false);
buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<CreatureType>();
for (String creatureName : 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 = getBoolean("blacklist.use-as-whitelist", false);
// Console log configuration
boolean logConsole = getBoolean("blacklist.logging.console.enable", true);
// Database log configuration
boolean logDatabase = getBoolean("blacklist.logging.database.enable", false);
String dsn = getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = getString("blacklist.logging.database.user", "root");
String pass = getString("blacklist.logging.database.pass", "");
String table = getString("blacklist.logging.database.table", "blacklist_events");
// File log configuration
boolean logFile = getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, 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 (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.");
}
}
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.save();
}
public Blacklist getBlacklist() {
return this.blacklist;
}
public String getWorldName() {
return this.worldName;
}
public boolean isChestProtected(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtected(block, player);
}
public boolean isChestProtected(Block block) {
if (!signChestProtection) {
return false;
}
return chestProtection.isProtected(block, null);
}
public boolean isChestProtectedPlacement(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtectedPlacement(block, player);
}
public boolean isAdjacentChestProtected(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isAdjacentChestProtected(block, player);
}
public ChestProtection getChestProtection() {
return chestProtection;
}
}
@@ -0,0 +1,780 @@
// $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.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.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.World;
import org.bukkit.event.block.*;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import java.util.logging.Logger;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener extends BlockListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
/**
* Construct the object.
*
* @param plugin
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("BLOCK_DAMAGE", Priority.High);
registerEvent("BLOCK_BREAK", Priority.High);
registerEvent("BLOCK_FROMTO", Priority.Normal);
registerEvent("BLOCK_IGNITE", Priority.High);
registerEvent("BLOCK_PHYSICS", Priority.Normal);
registerEvent("BLOCK_PLACE", Priority.High);
registerEvent("BLOCK_BURN", Priority.High);
registerEvent("SIGN_CHANGE", Priority.High);
registerEvent("REDSTONE_CHANGE", Priority.High);
registerEvent("SNOW_FORM", Priority.High);
registerEvent("LEAVES_DECAY", Priority.High);
registerEvent("BLOCK_FORM", Priority.High);
registerEvent("BLOCK_SPREAD", Priority.High);
registerEvent("BLOCK_FADE", Priority.High);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Get the world configuration given a world.
*
* @param world
* @return
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player
* @return
*/
protected WorldConfiguration getWorldConfig(Player player) {
return plugin.getGlobalStateManager().get(player.getWorld());
}
/**
* Called when a block is damaged.
*/
@Override
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
// Cake are damaged and not broken when they are eaten, so we must
// handle them a bit separately
if (blockDamaged.getType() == Material.CAKE_BLOCK) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockDamaged)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
event.setCancelled(true);
return;
}
}
}
/**
* Called when a block is broken.
*/
@Override
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getTypeId() > 0
&& !(ItemType.usesDamageValue(held.getTypeId())
|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) -1);
player.setItemInHand(held);
}
}
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 (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
event.getBlock().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
if (!wcfg.getBlacklist().check(
new DestroyWithBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
player.getItemInHand().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
return;
}
}
/**
* Called when fluids flow.
*/
@Override
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;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
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
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
}
}
}
}
}
/*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;
}
}*/
// 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 (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.
*/
@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.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
event.setCancelled(true);
return;
}
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.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
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) {
if (!set.canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (!set.allows(DefaultFlag.LIGHTER)
&& !plugin.hasPermission(player, "worldguard.override.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.
*/
@Override
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
return;
}
}
if (wcfg.isChestProtected(event.getBlock())) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Block block = event.getBlock();
Vector pt = toVector(block);
RegionManager mgr = plugin.getGlobalRegionManager().get(block.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when block physics occurs.
*/
@Override
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int id = event.getChangedTypeId();
if (id == 13 && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
}
/**
* Called when a player places a block.
*/
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
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 (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(blockPlaced),
blockPlaced.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getType())) {
if (wcfg.isAdjacentChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
event.setCancelled(true);
return;
}
}
if (wcfg.simulateSponge && blockPlaced.getTypeId() == 19) {
if (wcfg.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
return;
}
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
SpongeUtil.clearSpongeWater(plugin, world, ox, oy, oz);
}
}
/**
* Called when redstone changes.
*/
@Override
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
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++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
}
}
}
}
return;
}
}
/**
* Called when a sign is changed.
*/
@Override
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
dropSign(event.getBlock());
event.setCancelled(true);
return;
}
if (event.getBlock().getType() != Material.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
dropSign(event.getBlock());
event.setCancelled(true);
return;
}
if (!event.getLine(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
dropSign(event.getBlock());
event.setCancelled(true);
return;
}
Material below = event.getBlock().getRelative(0, -1, 0).getType();
if (below == Material.TNT || below == Material.SAND
|| below == Material.GRAVEL || below == Material.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
dropSign(event.getBlock());
event.setCancelled(true);
return;
}
event.setLine(0, "[Lock]");
player.sendMessage(ChatColor.YELLOW
+ "A chest or double chest above is now protected.");
}
} else {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
dropSign(event.getBlock());
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;
}
}
/**
* Called when snow is formed.
*/
@Override
public void onSnowForm(SnowFormEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.SNOW_FALL,
event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY,
event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
}
/**
* Called when a block is formed based on world conditions.
*/
public void onBlockForm(BlockFormEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material type = event.getNewState().getType();
if (wcfg.disableIceFormation && type == Material.ICE) {
event.setCancelled(true);
return;
}
if (wcfg.disableSnowFormation && type == Material.SNOW) {
event.setCancelled(true);
return;
}
}
/**
* Called when a block spreads based on world conditions.
*/
public void onBlockSpread(BlockSpreadEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material fromType = event.getSource().getType();
if (wcfg.disableMushroomSpread && (fromType == Material.RED_MUSHROOM
|| fromType == Material.BROWN_MUSHROOM)) {
event.setCancelled(true);
return;
}
}
/**
* Called when a block fades.
*/
public void onBlockFade(BlockFadeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
Material type = event.getBlock().getType();
if (wcfg.disableIceMelting && type == Material.ICE) {
event.setCancelled(true);
return;
}
if (wcfg.disableSnowMelting && type == Material.SNOW) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,690 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.Set;
import java.util.logging.Logger;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener extends EntityListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("ENTITY_DAMAGE", Priority.High);
registerEvent("ENTITY_COMBUST", Priority.High);
registerEvent("ENTITY_EXPLODE", Priority.High);
registerEvent("CREATURE_SPAWN", Priority.High);
registerEvent("ENTITY_INTERACT", Priority.High);
registerEvent("CREEPER_POWER", Priority.High);
registerEvent("PIG_ZAP", Priority.High);
registerEvent("PAINTING_BREAK", Priority.High);
registerEvent("PAINTING_PLACE", Priority.High);
registerEvent("ENTITY_REGAIN_HEALTH", Priority.High);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Called when an entity interacts with another object.
*/
@Override
public void onEntityInteract(EntityInteractEvent event) {
//bukkit doesn't actually throw this event yet, someone add a ticket to leaky
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (block.getType() == Material.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
}
}
/**
* Called on entity damage by a block.
*
* @param event
*/
private void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
if (cfg.hasGodMode(player)) player.setFireTicks(0);
return;
}
if (wcfg.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
if (wcfg.teleportOnVoid && type == DamageCause.VOID) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableVoidDamage && type == DamageCause.VOID) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.BLOCK_EXPLOSION) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on entity damage by an entity.
*
* @param event
*/
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.ENTITY_EXPLOSION) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
/**
* Called on entity damage by a projectile.
*
* @param event
*/
private void onEntityDamageByProjectile(EntityDamageByProjectileEvent event) {
Entity defender = event.getEntity();
Entity attacker = event.getDamager();
if (defender instanceof Player) {
Player player = (Player) defender;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Skeleton) {
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
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;
}
}
}
}
}
/**
* Called on entity damage.
*/
@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();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
player.setFireTicks(0);
return;
}
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 (wcfg.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (wcfg.disableDrowningDamage && type == DamageCause.DROWNING) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on entity combust.
*/
@Override
public void onEntityCombust(EntityCombustEvent event) {
if (event.isCancelled()) {
return;
}
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (entity instanceof Player) {
Player player = (Player) entity;
if (cfg.hasGodMode(player)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on entity explode.
*/
@Override
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
Entity ent = event.getEntity();
if (ent instanceof LivingEntity) {
if (wcfg.blockCreeperBlockDamage) {
event.setCancelled(true);
return;
}
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
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 if (ent instanceof Fireball) {
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
} else if (ent instanceof TNTPrimed) {
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.blockTNT) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(l);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
return;
}
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
event.setCancelled(true);
return;
}
}
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
// Whoo, for each block
for (Block block : event.blockList()) {
Vector pt = toVector(block);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.TNT)) {
event.setCancelled(true);
return;
}
}
}
}
/**
* Called on creature spawn.
*/
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
CreatureType creaType = event.getCreatureType();
if (wcfg.blockCreatureSpawn.contains(creaType)) {
event.setCancelled(true);
return;
}
Location eventLoc = event.getLocation();
if (wcfg.useRegions) {
Vector pt = toVector(eventLoc);
RegionManager mgr = plugin.getGlobalRegionManager().get(eventLoc.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_SPAWNING)) {
event.setCancelled(true);
return;
}
Set<CreatureType> blockTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (blockTypes != null && blockTypes.contains(creaType)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on pig zap.
*/
@Override
public void onPigZap(PigZapEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disablePigZap) {
event.setCancelled(true);
}
}
/**
* Called on creeper power.
*/
@Override
public void onCreeperPower(CreeperPowerEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
}
}
/**
* Called when a painting is removed.
*/
@Override
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (breakEvent.isCancelled()) {
return;
}
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
if (!(event.getRemover() instanceof Player)) {
return;
}
Painting painting= event.getPainting();
Player player = (Player) event.getRemover();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
/**
* Called on painting place.
*/
@Override
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
/**
* Called on entity health regain.
*/
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,778 @@
// $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.protection.managers.RegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.bukkit.migration.*;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.TickSyncDelayLoggerFilter;
import com.sk89q.worldguard.bukkit.commands.GeneralCommands;
import com.sk89q.worldguard.bukkit.commands.ProtectionCommands;
import com.sk89q.worldguard.bukkit.commands.ToggleCommands;
import com.sk89q.worldguard.protection.*;
import java.io.*;
import java.util.*;
import java.util.logging.Filter;
import java.util.logging.Logger;
/**
* The main class for WorldGuard as a Bukkit plugin.
*
* @author sk89q
*/
public class WorldGuardPlugin extends JavaPlugin {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Manager for commands. This automatically handles nested commands,
* permissions checking, and a number of other fancy command things.
* We just set it up and register commands against it.
*/
private final CommandsManager<CommandSender> commands;
/**
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Processes queries for permissions information. The permissions manager
* is from WorldEdit and it automatically handles looking up permissions
* systems and picking the right one. WorldGuard just needs to call
* the permission methods.
*/
private PermissionsResolverManager perms;
/**
* Used for scheduling flags.
*/
private FlagStateManager flagStateManager;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
*/
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new GlobalRegionManager(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@Override
public boolean hasPermission(CommandSender player, String perm) {
return plugin.hasPermission(player, perm);
}
};
// Register command classes
commands.register(ToggleCommands.class);
commands.register(ProtectionCommands.class);
commands.register(GeneralCommands.class);
}
/**
* Called on plugin enable.
*/
public void onEnable() {
// Need to create the plugins/WorldGuard folder
getDataFolder().mkdirs();
// Set up permissions
perms = new PermissionsResolverManager(
getConfiguration(), getServer(), "WorldGuard", logger);
perms.load();
// This must be done before configuration is laoded
LegacyWorldGuardMigration.migrateBlacklist(this);
// Load the configuration
configuration.load();
globalRegionManager.preload();
// Migrate regions after the regions were loaded because
// the migration code reuses the loaded region managers
LegacyWorldGuardMigration.migrateRegions(this);
// Load permissions
(new PermissionsResolverServerListener(perms)).register(this);
flagStateManager = new FlagStateManager(this);
if (configuration.useRegionsScheduler) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this,
flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
if (configuration.suppressTickSyncWarnings) {
Logger.getLogger("Minecraft").setFilter(
new TickSyncDelayLoggerFilter());
} else {
Filter filter = Logger.getLogger("Minecraft").getFilter();
if (filter != null && filter instanceof TickSyncDelayLoggerFilter) {
Logger.getLogger("Minecraft").setFilter(null);
}
}
// Register events
(new WorldGuardPlayerListener(this)).registerEvents();
(new WorldGuardBlockListener(this)).registerEvents();
(new WorldGuardEntityListener(this)).registerEvents();
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardWorldListener(this)).registerEvents();
logger.info("WorldGuard " + this.getDescription().getVersion() + " enabled.");
}
/**
* Called on plugin disable.
*/
public void onDisable() {
globalRegionManager.unload();
configuration.unload();
logger.info("WorldGuard " + getDescription().getVersion() + " disabled.");
}
/**
* Handle a command.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
try {
commands.execute(cmd.getName(), args, sender, this, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
if (e.getCause() instanceof NumberFormatException) {
sender.sendMessage(ChatColor.RED + "Number expected, string received instead.");
} else {
sender.sendMessage(ChatColor.RED + "An error has occurred. See console.");
e.printStackTrace();
}
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
/**
* Get the GlobalRegionManager.
*
* @return
*/
public GlobalRegionManager getGlobalRegionManager() {
return globalRegionManager;
}
/**
* Get the WorldGuardConfiguraton.
*
* @return
* @deprecated Use {@link #getGlobalStateManager()} instead
*/
@Deprecated
public ConfigurationManager getGlobalConfiguration() {
return getGlobalStateManager();
}
/**
* Gets the flag state manager.
*
* @return
*/
public FlagStateManager getFlagStateManager() {
return flagStateManager;
}
/**
* Get the WorldGuardConfiguraton.
*
* @return
*/
public ConfigurationManager getGlobalStateManager() {
return configuration;
}
/**
* Check whether a player is in a group.
*
* @param player
* @param group
* @return
*/
public boolean inGroup(Player player, String group) {
try {
return perms.inGroup(player.getName(), group);
} catch (Throwable t) {
t.printStackTrace();
return false;
}
}
/**
* Get the groups of a player.
*
* @param player
* @return
*/
public String[] getGroups(Player player) {
try {
return perms.getGroups(player.getName());
} catch (Throwable t) {
t.printStackTrace();
return new String[0];
}
}
/**
* Gets the name of a command sender. This is a unique name and this
* method should never return a "display name".
*
* @param sender
* @return
*/
public String toUniqueName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
return "*Console*";
}
}
/**
* Gets the name of a command sender. This play be a display name.
*
* @param sender
* @return
*/
public String toName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
return "*Console*";
}
}
/**
* Checks permissions.
*
* @param sender
* @param perm
* @return
*/
public boolean hasPermission(CommandSender sender, String perm) {
if (sender.isOp()) {
if (sender instanceof Player) {
if (this.getGlobalStateManager().get(((Player) sender).
getWorld()).opPermissions) {
return true;
}
} else {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
return perms.hasPermission(((Player) sender).getName(), perm);
}
return false;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param sender
* @param perm
* @throws CommandPermissionsException
*/
public void checkPermission(CommandSender sender, String perm)
throws CommandPermissionsException {
if (!hasPermission(sender, perm)) {
throw new CommandPermissionsException();
}
}
/**
* Checks to see if the sender is a player, otherwise throw an exception.
*
* @param sender
* @return
* @throws CommandException
*/
public Player checkPlayer(CommandSender sender)
throws CommandException {
if (sender instanceof Player) {
return (Player) sender;
} else {
throw new CommandException("A player is expected.");
}
}
/**
* Match player names.
*
* @param filter
* @return
*/
public List<Player> matchPlayerNames(String filter) {
Player[] players = getServer().getOnlinePlayers();
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (Player player : players) {
if (player.getName().equalsIgnoreCase(filter)) {
List<Player> list = new ArrayList<Player>();
list.add(player);
return list;
}
}
return new ArrayList<Player>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
/**
* Checks if the given list of players is greater than size 0, otherwise
* throw an exception.
*
* @param players
* @return
* @throws CommandException
*/
protected Iterable<Player> checkPlayerMatch(List<Player> players)
throws CommandException {
// Check to see if there were any matches
if (players.size() == 0) {
throw new CommandException("No players matched query.");
}
return players;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param source
* @param filter
* @return iterator for players
* @throws CommandException no matches found
*/
public Iterable<Player> matchPlayers(CommandSender source, String filter)
throws CommandException {
if (getServer().getOnlinePlayers().length == 0) {
throw new CommandException("No players matched query.");
}
if (filter.equals("*")) {
return checkPlayerMatch(Arrays.asList(getServer().getOnlinePlayers()));
}
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// Handle #world, which matches player of the same world as the
// calling source
if (filter.equalsIgnoreCase("#world")) {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
}
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
org.bukkit.util.Vector sourceVector
= sourcePlayer.getLocation().toVector();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)
&& player.getLocation().toVector().distanceSquared(
sourceVector) < 900) {
players.add(player);
}
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<Player> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
/**
* Match only a single player.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*/
public Player matchSinglePlayer(CommandSender sender, String filter)
throws CommandException {
// This will throw an exception if there are no matches
Iterator<Player> players = matchPlayers(sender, filter).iterator();
Player match = players.next();
// We don't want to match the wrong person, so fail if if multiple
// players were found (we don't want to just pick off the first one,
// as that may be the wrong player)
if (players.hasNext()) {
throw new CommandException("More than one player found! " +
"Use @<name> for exact matching.");
}
return match;
}
/**
* Match only a single player or console.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*/
public CommandSender matchPlayerOrConsole(CommandSender sender, String filter)
throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return new ConsoleCommandSender(getServer());
}
return matchSinglePlayer(sender, filter);
}
/**
* Get a single player as an iterator for players.
*
* @param player
* @return iterator for players
*/
public Iterable<Player> matchPlayers(Player player) {
return Arrays.asList(new Player[] {player});
}
/**
* Match a world.
* @param sender
*
* @param filter
* @return
* @throws CommandException
*/
public World matchWorld(CommandSender sender, String filter) throws CommandException {
List<World> worlds = getServer().getWorlds();
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
if (world.getEnvironment() == Environment.NORMAL) {
return world;
}
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
if (world.getEnvironment() == Environment.NETHER) {
return world;
}
}
throw new CommandException("No nether world found.");
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String parts[] = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
/**
* Gets a copy of the WorldEdit plugin.
*
* @return
* @throws CommandException
*/
public WorldEditPlugin getWorldEdit() throws CommandException {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
}
if (worldEdit instanceof WorldEditPlugin) {
return (WorldEditPlugin) worldEdit;
} else {
throw new CommandException("WorldEdit detection failed (report error).");
}
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player
* @return
*/
public LocalPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, player);
}
/**
* Create a default configuration file from the .jar.
*
* @param actual
* @param defaultName
*/
public static void createDefaultConfiguration(File actual,
String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (actual.exists()) {
return;
}
InputStream input = WorldGuardPlugin.class
.getResourceAsStream("/defaults/" + defaultName);
if (input != null) {
FileOutputStream output = null;
try {
output = new FileOutputStream(actual);
byte[] buf = new byte[8192];
int length = 0;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
logger.info("WorldGuard: Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
}
}
}
}
/**
* Notifies all with the notify permission.
*
* @param msg
*/
public void broadcastNotification(String msg) {
for (Player player : getServer().getOnlinePlayers()) {
if (hasPermission(player, "worldguard.notify")) {
player.sendMessage(msg);
}
}
}
/**
* Forgets a player.
*
* @param player
*/
public void forgetPlayer(Player player) {
flagStateManager.forget(player);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param loc
* @return
*/
public boolean canBuild(Player player, Location loc) {
return getGlobalRegionManager().canBuild(player, loc);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param block
* @return
*/
public boolean canBuild(Player player, Block block) {
return getGlobalRegionManager().canBuild(player, block);
}
/**
* Gets the region manager for a world.
*
* @param world world to get the region manager for
* @return the region manager or null if regions are not enabled
*/
public RegionManager getRegionManager(World world) {
if (!getGlobalStateManager().get(world).useRegions) {
return null;
}
return getGlobalRegionManager().get(world);
}
/**
* Replace macros in the text.
*
* @param sender
* @param message
* @return
*/
public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
message = message.replace("%name%", toName(sender));
message = message.replace("%id%", toUniqueName(sender));
message = message.replace("%online%", String.valueOf(online.length));
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
message = message.replace("%world%", world.getName());
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}
}
@@ -0,0 +1,149 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.Location;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.weather.WeatherListener;
import org.bukkit.plugin.PluginManager;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.logging.Logger;
public class WorldGuardWeatherListener extends WeatherListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("LIGHTNING_STRIKE", Priority.High);
registerEvent("THUNDER_CHANGE", Priority.High);
registerEvent("WEATHER_CHANGE", Priority.High);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
@Override
public void onWeatherChange(WeatherChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysRaining) {
event.setCancelled(true);
}
}
}
@Override
public void onThunderChange(ThunderChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toThunderState()) {
if (wcfg.disableThunder) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysThundering) {
event.setCancelled(true);
}
}
}
@Override
public void onLightningStrike(LightningStrikeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (wcfg.disallowedLightningBlocks.size() > 0) {
int targetId = event.getLightning().getLocation().getBlock().getTypeId();
if (wcfg.disallowedLightningBlocks.contains(targetId)) {
event.setCancelled(true);
}
}
Location loc = event.getLightning().getLocation();
if (wcfg.useRegions) {
Vector pt = toVector(loc);
RegionManager mgr = plugin.getGlobalRegionManager().get(loc.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
}
}
}
}
@@ -0,0 +1,84 @@
// $Id$
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* All rights reserved.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.plugin.PluginManager;
import java.util.logging.Logger;
public class WorldGuardWorldListener extends WorldListener {
/**
* Logger for messages.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
registerEvent("CHUNK_LOAD", Event.Priority.Normal);
}
/**
* Register an event, but not failing if the event is not implemented.
*
* @param typeName
* @param priority
*/
private void registerEvent(String typeName, Event.Priority priority) {
try {
Event.Type type = Event.Type.valueOf(typeName);
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvent(type, this, priority, plugin);
} catch (IllegalArgumentException e) {
logger.info("WorldGuard: Unable to register missing event type " + typeName);
}
}
/**
* Called when a chunk is loaded.
*/
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (cfg.activityHaltToggle) {
int removed = 0;
for (Entity entity : event.getChunk().getEntities()) {
if (entity instanceof Item
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player))) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info("WG Halt-Act: " + removed + " entities (>50) auto-removed from "
+ event.getChunk().toString());
}
}
}
}
@@ -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 = "s", min = 0, max = 1)
public static void god(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
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 = "s", min = 0, max = 1)
public static void ungod(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
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 no longer have god mode.");
}
}
@Command(aliases = {"heal"},
usage = "[player]",
desc = "Heal a player",
flags = "s", min = 0, max = 1)
public static void heal(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
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 = "s", 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 + "Slain!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Slain 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 slain.");
}
}
@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,921 @@
// $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.getGlobalStateManager().get(player.getWorld());
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
// 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 (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
if (region.volume() > wcfg.maxClaimVolume) {
player.sendMessage(ChatColor.RED + "This region is too 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());
BlockVector min = region.getMinimumPoint();
BlockVector max = region.getMaximumPoint();
String c = "(" + min.getBlockX() + "," + min.getBlockY() + "," + min.getBlockZ() + ")";
c += " (" +max.getBlockX() + "," + max.getBlockY() + "," + max.getBlockZ() + ")";
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds: " + c);
}
@Command(aliases = {"list"},
usage = "[.player] [page] [world]",
desc = "Get a list of regions",
flags = "", min = 0, max = 3)
// @CommandPermissions({"worldguard.region.list"})
public static void list(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
World world;
int page = 0;
int argl = 0;
String name = "";
boolean own = false;
LocalPlayer localPlayer = null;
if (args.argsLength() > 0 && args.getString(0).startsWith(".")) {
name = args.getString(0).substring(1).toLowerCase();
argl = 1;
if (name.equals("me") || name.isEmpty() ||
name.equals(plugin.checkPlayer(sender).getDisplayName().toLowerCase())) {
plugin.checkPermission(sender, "worldguard.region.list.own");
name = plugin.checkPlayer(sender).getDisplayName().toLowerCase();
localPlayer = plugin.wrapPlayer(plugin.checkPlayer(sender));
own = true;
}
}
if (!own)
plugin.checkPermission(sender, "worldguard.region.list");
if (args.argsLength() > 0 + argl) {
page = Math.max(0, args.getInteger(0 + argl) - 1);
}
if (args.argsLength() > 1 + argl) {
world = plugin.matchWorld(sender, args.getString(1 + argl));
} 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();
String[] regionIDList = new String[size];
int index = 0;
boolean show = false;
String prefix = "";
for (String id : regions.keySet()) {
show = false;
prefix = "";
if (name.isEmpty()) {
show = true;
}
else {
if (own) {
if (regions.get(id).isOwner(localPlayer)) {
show = true;
prefix += "+";
}
else if (regions.get(id).isMember(localPlayer)) {
show = true;
prefix += "-";
}
}
else {
if (regions.get(id).getOwners().getPlayers().contains(name)) {
show = true;
prefix += "+";
}
if (regions.get(id).getMembers().getPlayers().contains(name)) {
show = true;
prefix += "-";
}
}
}
if (show) {
regionIDList[index] = prefix + " " + id;
index++;
}
}
if (!name.isEmpty())
regionIDList = Arrays.copyOf(regionIDList, index);
Arrays.sort(regionIDList);
size = index;
int pages = (int) Math.ceil(size / (float) listSize);
sender.sendMessage(ChatColor.RED
+ (name == "" ? "Regions (page " : "Regions for " + name + " (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,203 @@
// $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);
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);
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);
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);
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,143 @@
// $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 com.sk89q.worldguard.bukkit.ConfigurationManager;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.entity.*;
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.getGlobalStateManager().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.getGlobalStateManager().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;
}
@Command(aliases = {"halt-activity"},
usage = "", desc = "Attempts to cease as much activity in order to stop lag",
flags = "c", min = 0, max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public static void stopLag(CommandContext args, WorldGuardPlugin plugin,
CommandSender sender) throws CommandException {
ConfigurationManager configManager = plugin.getGlobalStateManager();
configManager.activityHaltToggle = !args.hasFlag('c');
if (configManager.activityHaltToggle) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted by "
+ plugin.toName(sender) + ".");
for (World world : plugin.getServer().getWorlds()) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (entity instanceof Item
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player))) {
entity.remove();
removed++;
}
}
if (removed > 10) {
sender.sendMessage("" + removed + " entities (>10) auto-removed from "
+ world.toString());
}
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity no longer halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity is now allowed.");
}
}
}
@@ -0,0 +1,125 @@
// $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.getGlobalStateManager().unload();
plugin.getGlobalRegionManager().unload();
plugin.getGlobalStateManager().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() {
public void handleSuccess(String url) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report (1 hour): " + url);
}
public void handleError(String err) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report pastebin error: " + err);
}
});
}
}
}
@@ -0,0 +1,67 @@
// $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.chest;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
/**
* Interface for chest protection.
*/
public interface ChestProtection {
/**
* Returns whether a block is protected.
*
* @param block
* @param player
* @return
*/
public boolean isProtected(Block block, Player player);
/**
* Returns whether a location where a chest block is trying to be created
* is protected.
*
* @param block
* @param player
* @return
*/
public boolean isProtectedPlacement(Block block, Player player);
/**
* Returns whether an adjacent chest is protected.
*
* @param searchBlock
* @param player
* @return
*/
public boolean isAdjacentChestProtected(Block searchBlock, Player player);
/**
* Returns whether a material is a chest.
*
* @param material
* @return
*/
public boolean isChest(Material material);
}
@@ -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.chest;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
/**
* Sign-based chest protection.
*
* @author sk89q
*/
public class SignChestProtection implements ChestProtection {
public boolean isProtected(Block block, Player player) {
if (isChest(block.getType())) {
Block below = block.getRelative(0, -1, 0);
return isProtectedSignAround(below, player);
} else if (block.getType() == Material.SIGN_POST) {
return isProtectedSignAndChestBinary(block, player);
} else {
Block above = block.getRelative(0, 1, 0);
Boolean res = isProtectedSign(above, player);
if (res != null) return res;
return false;
}
}
public boolean isProtectedPlacement(Block block, Player player) {
return isProtectedSignAround(block, player);
}
private boolean isProtectedSignAround(Block searchBlock, Player player) {
Block side;
Boolean res;
side = searchBlock;
res = isProtectedSign(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtectedSignAndChest(side, player);
if (res != null && res == true) return res;
return false;
}
private Boolean isProtectedSign(Sign sign, Player player) {
if (sign.getLine(0).equalsIgnoreCase("[Lock]")) {
if (player == null) { // No player, no access
return true;
}
String name = player.getName();
if (name.equalsIgnoreCase(sign.getLine(1).trim())
|| name.equalsIgnoreCase(sign.getLine(2).trim())
|| name.equalsIgnoreCase(sign.getLine(3).trim())) {
return false;
}
// No access!
return true;
}
return null;
}
private Boolean isProtectedSign(Block block, Player player) {
BlockState state = block.getState();
if (state == null || !(state instanceof Sign)) {
return null;
}
return isProtectedSign((Sign) state, player);
}
private Boolean isProtectedSignAndChest(Block block, Player player) {
if (!isChest(block.getRelative(0, 1, 0).getType())) {
return null;
}
return isProtectedSign(block, player);
}
private boolean isProtectedSignAndChestBinary(Block block, Player player) {
Boolean res = isProtectedSignAndChest(block, player);
if (res == null || res == false) {
return false;
}
return true;
}
public boolean isAdjacentChestProtected(Block searchBlock, Player player) {
Block side;
Boolean res;
side = searchBlock;
res = isProtected(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtected(side, player);
if (res != null && res == true) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtected(side, player);
if (res != null && res == true) return res;
return false;
}
public boolean isChest(Material material) {
return material == Material.CHEST
|| material == Material.DISPENSER
|| material == Material.FURNACE
|| material == Material.BURNING_FURNACE;
}
}
@@ -0,0 +1,126 @@
// $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.domains;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
public class DefaultDomain implements Domain {
private Set<String> groups;
private Set<String> players;
public DefaultDomain() {
this.groups = new LinkedHashSet<String>();
this.players = new HashSet<String>();
}
public void addPlayer(String name) {
players.add(name.toLowerCase());
}
public void addPlayer(LocalPlayer player) {
players.add(player.getName().toLowerCase());
}
public void removePlayer(String name) {
players.remove(name.toLowerCase());
}
public void removePlayer(LocalPlayer player) {
players.remove(player.getName().toLowerCase());
}
public void addGroup(String name) {
groups.add(name.toLowerCase());
}
public void removeGroup(String name) {
groups.remove(name.toLowerCase());
}
public Set<String> getGroups() {
return groups;
}
public Set<String> getPlayers() {
return players;
}
public boolean contains(LocalPlayer player) {
if (players.contains(player.getName().toLowerCase())) {
return true;
}
for (String group : groups) {
if (player.hasGroup(group)) {
return true;
}
}
return false;
}
public int size() {
return groups.size() + players.size();
}
public String toPlayersString() {
StringBuilder str = new StringBuilder();
for (Iterator<String> it = players.iterator(); it.hasNext(); ) {
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
return str.toString();
}
public String toGroupsString() {
StringBuilder str = new StringBuilder();
for (Iterator<String> it = groups.iterator(); it.hasNext(); ) {
str.append("*");
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
return str.toString();
}
public String toUserFriendlyString() {
StringBuilder str = new StringBuilder();
if (players.size() > 0) {
str.append(toPlayersString());
}
if (groups.size() > 0) {
if (str.length() > 0) {
str.append("; ");
}
str.append(toGroupsString());
}
return str.toString();
}
}
@@ -0,0 +1,13 @@
package com.sk89q.worldguard.domains;
import com.sk89q.worldguard.LocalPlayer;
public interface Domain {
/**
* Returns true if a domain contains a player.
*
* @param player
* @return
*/
public boolean contains(LocalPlayer player);
}
@@ -0,0 +1,55 @@
// $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.domains;
import java.util.Set;
import java.util.LinkedHashSet;
import com.sk89q.worldguard.LocalPlayer;
public class DomainCollection implements Domain {
private Set<Domain> domains;
public DomainCollection() {
domains = new LinkedHashSet<Domain>();
}
public void add(Domain domain) {
domains.add(domain);
}
public void remove(Domain domain) {
domains.remove(domain);
}
public int size() {
return domains.size();
}
public boolean contains(LocalPlayer player) {
for (Domain domain : domains) {
if (domain.contains(player)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,56 @@
// $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.domains;
import java.util.Arrays;
import java.util.Set;
import java.util.LinkedHashSet;
import com.sk89q.worldguard.LocalPlayer;
public class GroupDomain implements Domain {
private Set<String> groups;
public GroupDomain() {
this.groups = new LinkedHashSet<String>();
}
public GroupDomain(String[] groups) {
this.groups = new LinkedHashSet<String>(Arrays.asList(groups));
}
public void addGroup(String name) {
groups.add(name);
}
public boolean contains(LocalPlayer player) {
for (String group : groups) {
if (player.hasGroup(group)) {
return true;
}
}
return false;
}
public int size() {
return groups.size();
}
}
@@ -0,0 +1,53 @@
// $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.domains;
import java.util.Set;
import java.util.HashSet;
import com.sk89q.worldguard.LocalPlayer;
public class PlayerDomain implements Domain {
private Set<String> players;
public PlayerDomain() {
this.players = new HashSet<String>();
}
public PlayerDomain(String[] players) {
this.players = new HashSet<String>();
for (String name : players) {
this.players.add(name.toLowerCase());
}
}
public void addPlayer(String name) {
players.add(name.toLowerCase());
}
public boolean contains(LocalPlayer player) {
return players.contains(player.getName().toLowerCase());
}
public int size() {
return players.size();
}
}
@@ -0,0 +1,385 @@
// $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.*;
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 com.sk89q.worldguard.LocalPlayer;
/**
* Represents a set of regions for a particular point or area and the rules
* that are represented by that set. An instance of this can be used to
* query the value of a flag or check if a player can build in the respective
* region or point. This object contains the list of applicable regions and so
* the expensive search of regions that are in the desired area has already
* been completed.
*
* @author sk89q
*/
public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
private Collection<ProtectedRegion> applicable;
private ProtectedRegion globalRegion;
/**
* Construct the object.
*
* @param applicable
* @param globalRegion
*/
public ApplicableRegionSet(Collection<ProtectedRegion> applicable,
ProtectedRegion globalRegion) {
this.applicable = applicable;
this.globalRegion = globalRegion;
}
/**
* Checks if a player can build in an area.
*
* @param player
* @return build ability
*/
public boolean canBuild(LocalPlayer player) {
return internalGetState(DefaultFlag.BUILD, player, null, null);
}
/**
* Checks if a player can use buttons and such in an area.
*
* @param player
* @return able to use items
*/
public boolean canUse(LocalPlayer player) {
return !allows(DefaultFlag.USE, player)
&& !canBuild(player);
}
/**
* Gets the state of a state flag. This cannot be used for the build flag.
*
* @param flag flag to check
* @return whether it is allowed
* @throws IllegalArgumentException if the build flag is given
*/
public boolean allows(StateFlag flag) {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, null, null);
}
/**
* Gets the state of a state flag. This cannot be used for the build flag.
*
* @param flag flag to check
* @param player player (used by some flags)
* @return whether the state is allows for it
* @throws IllegalArgumentException if the build flag is given
*/
public boolean allows(StateFlag flag, LocalPlayer player) {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, flag.getGroupFlag(), player);
}
/**
* Indicates whether a player is an owner of all regions in this set.
*
* @param player player
* @return whether the player is an owner of all regions
*/
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 player
* @return whether the player is a member of all regions
*/
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 flag flag to check
* @param player null to not check owners and members
* @param groupFlag group flag to check
* @param groupPlayer player to use for the group flag check
* @return
*/
private boolean internalGetState(StateFlag flag, LocalPlayer player,
RegionGroupFlag groupFlag,
LocalPlayer groupPlayer) {
boolean found = false;
boolean hasFlagDefined = false;
boolean allowed = false; // Used for ALLOW override
boolean def = flag.getDefault();
// Handle defaults
if (globalRegion != null) {
State globalState = globalRegion.getFlag(flag);
// The global region has this flag set
if (globalState != null) {
// Build flag is very special
if (player != null && globalRegion.hasMembersOrOwners()) {
def = globalRegion.isMember(player) && (globalState == State.ALLOW);
} else {
def = (globalState == State.ALLOW);
}
} else {
// Build flag is very special
if (player != null && globalRegion.hasMembersOrOwners()) {
def = globalRegion.isMember(player);
}
}
}
// 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 = Integer.MIN_VALUE;
// The algorithm is as follows:
// While iterating through the list of regions, if an entry disallows
// the flag, then put it into the needsClear set. If an entry allows
// the flag and it has a parent, then its parent is put into hasCleared.
// In the situation that the child is reached before the parent, upon
// the parent being reached, even if the parent disallows, because the
// parent will be in hasCleared, permission will be allowed. In the
// other case, where the parent is reached first, if it does not allow
// permissions, it will be placed into needsClear. If a child of
// the parent is reached later, the parent will be removed from
// needsClear. At the end, if needsClear is not empty, that means that
// 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();
while (it.hasNext()) {
ProtectedRegion region = it.next();
// Ignore lower priority regions
if (hasFlagDefined && region.getPriority() < lastPriority) {
break;
}
lastPriority = region.getPriority();
// Ignore non-build regions
if (player != null
&& region.getFlag(DefaultFlag.PASSTHROUGH) == State.ALLOW) {
continue;
}
// Check group permissions
if (groupPlayer != null && groupFlag != null) {
RegionGroupFlag.RegionGroup group = region.getFlag(groupFlag);
if (group == null) {
group = groupFlag.getDefault();
}
if (!RegionGroupFlag.isMember(region, group, groupPlayer)) {
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;
hasFlagDefined = 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) {
hasFlagDefined = true;
if (hasCleared.contains(region)) {
// Already cleared, so do nothing
} else {
if (!region.isMember(player)) {
needsClear.add(region);
} else {
// Need to clear all parents
clearParents(needsClear, hasCleared, region);
}
}
}
found = true;
}
return found == false ? def :
(allowed || (player != null && needsClear.size() == 0));
}
/**
* Clear a region's parents for isFlagAllowed().
*
* @param needsClear
* @param hasCleared
* @param region
*/
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
* (use {@link #allows(StateFlag, LocalPlayer)} for that).
*
* @param flag flag to check
* @return value of the flag
* @throws IllegalArgumentException if a StateFlag is given
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
if (flag instanceof StateFlag) {
throw new IllegalArgumentException("Cannot use StateFlag with getFlag()");
}
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();
}
}
@@ -0,0 +1,294 @@
// $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.getGlobalStateManager();
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
* @return
*/
public RegionManager 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());
return manager;
} catch (FileNotFoundException e) {
} catch (IOException e) {
logger.warning("WorldGuard: Failed to load regions from file "
+ file.getAbsolutePath() + " : " + e.getMessage());
}
// @TODO: THIS CREATES PROBLEMS!!
return null;
}
/**
* 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) {
manager = load(world);
}
return manager;
}
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
*/
public boolean hasBypass(LocalPlayer player, World world) {
return player.hasPermission("worldguard.region.bypass."
+ world.getName());
}
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
*/
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);
}
}
@@ -0,0 +1,24 @@
// $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;
public class UnsupportedIntersectionException extends Exception {
private static final long serialVersionUID = 6423189392345575148L;
}
@@ -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();
}
}
@@ -0,0 +1,344 @@
// $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.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;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import au.com.bytecode.opencsv.CSVReader;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.ArrayReader;
/**
* Represents a protected area database that uses CSV files.
*
* @author sk89q
*/
public class CSVDatabase extends AbstractProtectionDatabase {
private static Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* References the CSV file.
*/
private File file;
/**
* Holds the list of regions.
*/
private Map<String,ProtectedRegion> regions;
/**
* Construct the database with a path to a file. No file is read or
* written at this time.
*
* @param file
*/
public CSVDatabase(File file) {
this.file = file;
}
/**
* Saves the database.
*/
public void save() throws IOException {
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
* Load the database from file.
*/
public void load() throws IOException {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
Map<ProtectedRegion,String> parentSets =
new LinkedHashMap<ProtectedRegion, String>();
CSVReader reader = new CSVReader(new FileReader(file));
try {
String[] line;
while ((line = reader.readNext()) != null) {
if (line.length < 2) {
logger.warning("Invalid region definition: " + line);
continue;
}
String id = line[0].toLowerCase().replace(".", "");
String type = line[1];
ArrayReader<String> entries = new ArrayReader<String>(line);
if (type.equalsIgnoreCase("cuboid")) {
if (line.length < 8) {
logger.warning("Invalid region definition: " + line);
continue;
}
Vector pt1 = new Vector(
Integer.parseInt(line[2]),
Integer.parseInt(line[3]),
Integer.parseInt(line[4]));
Vector pt2 = new Vector(
Integer.parseInt(line[5]),
Integer.parseInt(line[6]),
Integer.parseInt(line[7]));
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
int priority = entries.get(8) == null ? 0 : Integer.parseInt(entries.get(8));
String ownersData = entries.get(9);
String flagsData = entries.get(10);
//String enterMessage = nullEmptyString(entries.get(11));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
parseFlags(region, flagsData);
region.setOwners(this.parseDomains(ownersData));
regions.put(id, region);
} else if (type.equalsIgnoreCase("cuboid.2")) {
Vector pt1 = new Vector(
Integer.parseInt(line[2]),
Integer.parseInt(line[3]),
Integer.parseInt(line[4]));
Vector pt2 = new Vector(
Integer.parseInt(line[5]),
Integer.parseInt(line[6]),
Integer.parseInt(line[7]));
BlockVector min = Vector.getMinimum(pt1, pt2).toBlockVector();
BlockVector max = Vector.getMaximum(pt1, pt2).toBlockVector();
int priority = entries.get(8) == null ? 0 : Integer.parseInt(entries.get(8));
String parentId = entries.get(9);
String ownersData = entries.get(10);
String membersData = entries.get(11);
String flagsData = entries.get(12);
//String enterMessage = nullEmptyString(entries.get(13));
//String leaveMessage = nullEmptyString(entries.get(14));
ProtectedRegion region = new ProtectedCuboidRegion(id, min, max);
region.setPriority(priority);
parseFlags(region, flagsData);
region.setOwners(this.parseDomains(ownersData));
region.setMembers(this.parseDomains(membersData));
regions.put(id, region);
// Link children to parents later
if (parentId.length() > 0) {
parentSets.put(region, parentId);
}
}
}
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
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;
}
/**
* Used to parse the specified domain in the CSV file.
*
* @param data
* @return
*/
private DefaultDomain parseDomains(String data) {
if (data == null) {
return new DefaultDomain();
}
DefaultDomain domain = new DefaultDomain();
Pattern pattern = Pattern.compile("^([A-Za-z]):(.*)$");
String[] parts = data.split(",");
for (String part : parts) {
if (part.trim().length() == 0) {
continue;
}
Matcher matcher = pattern.matcher(part);
if (!matcher.matches()) {
logger.warning("Invalid owner specification: " + part);
continue;
}
String type = matcher.group(1);
String id = matcher.group(2);
if (type.equals("u")) {
domain.addPlayer(id);
} else if (type.equals("g")) {
domain.addGroup(id);
} else {
logger.warning("Unknown owner specification: " + type);
}
}
return domain;
}
/**
* Used to parse the list of flags.
*
* @param data
*/
private void parseFlags(ProtectedRegion region, String data) {
if (data == null) {
return;
}
State curState = State.ALLOW;
for (int i = 0; i < data.length(); i++) {
char k = data.charAt(i);
if (k == '+') {
curState = State.ALLOW;
} else if (k == '-') {
curState = State.DENY;
} else {
String flagStr;
if (k == '_') {
if (i == data.length() - 1) {
logger.warning("_ read ahead fail");
break;
}
flagStr = "_" + data.charAt(i + 1);
i++;
logger.warning("_? custom flags are no longer supported");
continue;
} else {
flagStr = String.valueOf(k);
}
StateFlag flag = DefaultFlag.getLegacyFlag(flagStr);
if (flag != null) {
region.setFlag(flag, curState);
} else {
logger.warning("Legacy flag '" + flagStr + "' is unsupported");
}
}
}
}
/**
* Used to write the list of domains.
*
* @param domain
* @return
*/
/* private String writeDomains(DefaultDomain domain) {
StringBuilder str = new StringBuilder();
for (String player : domain.getPlayers()) {
str.append("u:" + player + ",");
}
for (String group : domain.getGroups()) {
str.append("g:" + group + ",");
}
return str.length() > 0 ?
str.toString().substring(0, str.length() - 1) : "";
}*/
/**
* Helper method to prepend '+' or '-' in front of a flag according
* to the flag's state.
*
* @param state
* @param flag
* @return
*/
/*
private String writeFlag(State state, String flag) {
if (state == State.ALLOW) {
return "+" + flag;
} else if (state == State.DENY) {
return "-" + flag;
}
return "";
}
*/
/**
* Returns a null if a string is null or empty.
*
* @param str
* @return
*/
protected String nullEmptyString(String str) {
if (str == null) {
return null;
} else if (str.length() == 0) {
return null;
} else {
return str;
}
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Get a list of protected regions.
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = regions;
}
}
@@ -0,0 +1,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.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,294 @@
// $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);
}
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;
}
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.setHeader("#\r\n" +
"# WorldGuard regions file\r\n" +
"#\r\n" +
"# WARNING: THIS FILE IS AUTOMATICALLY GENERATED. If you modify this file by\r\n" +
"# hand, be aware that A SINGLE MISTYPED CHARACTER CAN CORRUPT THE FILE. If\r\n" +
"# WorldGuard is unable to parse the file, your regions will FAIL TO LOAD and\r\n" +
"# the contents of this file will reset. Please use a YAML validator such as\r\n" +
"# http://yaml-online-parser.appspot.com (for smaller files).\r\n" +
"#\r\n" +
"# REMEMBER TO KEEP PERIODICAL BACKUPS.\r\n" +
"#");
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);
}
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
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,62 @@
// $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 CommandStringFlag extends Flag<String> {
public CommandStringFlag(String name, char legacyCode) {
super(name, legacyCode);
}
public CommandStringFlag(String name) {
super(name);
}
@Override
public String parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (!input.startsWith("/")) {
input = "/" + input;
}
return input.toLowerCase();
}
@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,56 @@
// $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;
import org.bukkit.entity.CreatureType;
/**
* Represents a creature type.
*
* @author sk89q
*/
public class CreatureTypeFlag extends EnumFlag<CreatureType> {
public CreatureTypeFlag(String name, char legacyCode) {
super(name, legacyCode, CreatureType.class);
}
public CreatureTypeFlag(String name) {
super(name, CreatureType.class);
}
@Override
public CreatureType detectValue(String input) {
CreatureType lowMatch = null;
for (CreatureType type : CreatureType.values()) {
if (type.name().equalsIgnoreCase(input.trim())) {
return type;
}
if (type.name().toLowerCase().startsWith(input.toLowerCase().trim())) {
lowMatch = type;
}
}
return lowMatch;
}
}
@@ -0,0 +1,106 @@
// $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.entity.CreatureType;
/**
*
* @author sk89q
*/
public final class DefaultFlag {
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", 'z', false);
public static final StateFlag BUILD = new StateFlag("build", 'b', true);
public static final StateFlag PVP = new StateFlag("pvp", 'p', true);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", 'm', true);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", 'c', true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true);
public static final StateFlag SLEEP = new StateFlag("sleep", true);
public static final StateFlag TNT = new StateFlag("tnt", 't', true);
public static final StateFlag LIGHTER = new StateFlag("lighter", 'l', true);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", 'f', true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", 'F', true);
public static final StateFlag LIGHTNING = new StateFlag("lightning", 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", true);
public static final StateFlag PLACE_VEHICLE = new StateFlag("vehicle-place", false);
public static final StateFlag SNOW_FALL = new StateFlag("snow-fall", true);
public static final StateFlag LEAF_DECAY = new StateFlag("leaf-decay", true);
public static final StateFlag ENTRY = new StateFlag("entry", true);
public static final RegionGroupFlag ENTRY_PERM = new RegionGroupFlag("entry-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StateFlag EXIT = new StateFlag("exit", true);
public static final RegionGroupFlag EXIT_PERM = new RegionGroupFlag("exit-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter");
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave");
public static final SetFlag<CreatureType> DENY_SPAWN = new SetFlag<CreatureType>("deny-spawn", new CreatureTypeFlag(null));
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final VectorFlag TELE_LOC = new VectorFlag("teleport");
public static final RegionGroupFlag TELE_PERM = new RegionGroupFlag("teleport-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final VectorFlag SPAWN_LOC = new VectorFlag("spawn");
public static final RegionGroupFlag SPAWN_PERM = new RegionGroupFlag("spawn-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", new CommandStringFlag(null));
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, PVP, MOB_DAMAGE, MOB_SPAWNING, CREEPER_EXPLOSION, SLEEP,
TNT, LIGHTER, FIRE_SPREAD, LAVA_FIRE, CHEST_ACCESS, WATER_FLOW, LAVA_FLOW,
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER,
NOTIFY_LEAVE, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE, SNOW_FALL, LEAF_DECAY,
GHAST_FIREBALL, BLOCKED_CMDS, ALLOWED_CMDS, ENTRY, ENTRY_PERM, EXIT, EXIT_PERM
};
static {
ENTRY.setGroupFlag(ENTRY_PERM);
EXIT.setGroupFlag(EXIT_PERM);
}
private DefaultFlag() {
}
public static Flag<?>[] getFlags() {
return flagsList;
}
/**
* Get the legacy flag.
*
* @param flagString
* @return null if not found
*/
public static StateFlag getLegacyFlag(String flagString) {
for (Flag<?> flag : flagsList) {
if (flag instanceof StateFlag && flagString.equals(String.valueOf(flag.getLegacyCode()))) {
return (StateFlag) flag;
}
}
return null;
}
}
@@ -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,91 @@
// $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 EnumFlag<T extends Enum<T>> extends Flag<T> {
private Class<T> enumClass;
public EnumFlag(String name, char legacyCode, Class<T> enumClass) {
super(name, legacyCode);
this.enumClass = enumClass;
}
public EnumFlag(String name, Class<T> enumClass) {
super(name);
this.enumClass = enumClass;
}
private T findValue(String input) throws IllegalArgumentException {
try {
return Enum.valueOf(enumClass, input);
} catch (IllegalArgumentException e) {
T val = detectValue(input);
if (val != null) {
return val;
}
throw e;
}
}
/**
* Fuzzy detect the value if the value is not found.
*
* @param input string input
* @return value or null
*/
public T detectValue(String input) {
return null;
}
@Override
public T parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
try {
return findValue(input);
} catch (IllegalArgumentException e) {
throw new InvalidFlagFormat("Unknown value '" + input + "' in "
+ enumClass.getName());
}
}
@Override
public T unmarshal(Object o) {
try {
return Enum.valueOf(enumClass, String.valueOf(o));
} catch (IllegalArgumentException e) {
return null;
}
}
@Override
public Object marshal(T o) {
return o.name();
}
}
@@ -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;
}
}
@@ -0,0 +1,29 @@
// $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;
public class InvalidFlagFormat extends Exception {
private static final long serialVersionUID = 8101615074524004172L;
public InvalidFlagFormat(String msg) {
super(msg);
}
}
@@ -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.protection.flags;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static enum RegionGroup {
MEMBERS,
OWNERS,
NON_MEMBERS,
NON_OWNERS
}
private RegionGroup def;
public RegionGroupFlag(String name, char legacyCode, RegionGroup def) {
super(name, legacyCode);
this.def = def;
}
public RegionGroupFlag(String name, RegionGroup def) {
super(name);
this.def = def;
}
public RegionGroup getDefault() {
return def;
}
@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("nonowners") || input.equalsIgnoreCase("nonowner")) {
return RegionGroup.NON_OWNERS;
} else if (input.equalsIgnoreCase("nonmembers") || input.equalsIgnoreCase("nonmember")) {
return RegionGroup.NON_MEMBERS;
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone")) {
return null;
} else {
throw new InvalidFlagFormat("Not none/allow/deny: " + input);
}
}
@Override
public RegionGroup unmarshal(Object o) {
String str = o.toString();
if (str.equalsIgnoreCase("members")) {
return RegionGroup.MEMBERS;
} else if (str.equalsIgnoreCase("owners")) {
return RegionGroup.OWNERS;
} else if (str.equalsIgnoreCase("nonmembers")) {
return RegionGroup.NON_MEMBERS;
} else if (str.equalsIgnoreCase("nonowners")) {
return RegionGroup.NON_OWNERS;
} else {
return null;
}
}
@Override
public Object marshal(RegionGroup o) {
if (o == RegionGroup.MEMBERS) {
return "members";
} else if (o == RegionGroup.OWNERS) {
return "owners";
} else if (o == RegionGroup.NON_MEMBERS) {
return "nonmembers";
} else if (o == RegionGroup.NON_OWNERS) {
return "nonowners";
} else {
return null;
}
}
public static boolean isMember(ProtectedRegion region, RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
if (region.isMember(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
if (!region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
if (!region.isMember(player)) {
return true;
}
}
return false;
}
public static boolean isMember(ApplicableRegionSet set,
RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
if (set.isMemberOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
if (!set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
if (!set.isMemberOfAll(player)) {
return true;
}
}
return false;
}
}
@@ -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;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.util.*;
/**
* Represents a flag that consists of a set.
*
* @author sk89q
*/
public class SetFlag<T> extends Flag<Set<T>> {
private Flag<T> subFlag;
public SetFlag(String name, char legacyCode, Flag<T> subFlag) {
super(name, legacyCode);
this.subFlag = subFlag;
}
public SetFlag(String name, Flag<T> subFlag) {
super(name);
this.subFlag = subFlag;
}
@Override
public Set<T> parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
Set<T> items = new HashSet<T>();
for (String str : input.split(",")) {
items.add(subFlag.parseInput(plugin, sender, str.trim()));
}
return new HashSet<T>(items);
}
@Override
public Set<T> unmarshal(Object o) {
if (o instanceof Collection) {
Collection collection = (Collection) o;
Set<T> items = new HashSet<T>();
for (Object sub : collection) {
T item = subFlag.unmarshal(sub);
if (item != null) {
items.add(item);
}
}
return items;
} else {
return null;
}
}
@Override
public Object marshal(Set<T> o) {
List<Object> list = new ArrayList<Object>();
for (T item : o) {
list.add(subFlag.marshal(item));
}
return list;
}
}
@@ -0,0 +1,99 @@
// $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;
private RegionGroupFlag groupFlag;
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;
}
public RegionGroupFlag getGroupFlag() {
return groupFlag;
}
public void setGroupFlag(RegionGroupFlag groupFlag) {
this.groupFlag = groupFlag;
}
@Override
public State parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
input = input.trim();
if (input.equalsIgnoreCase("allow")) {
return State.ALLOW;
} else if (input.equalsIgnoreCase("deny")) {
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,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.managers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.UnsupportedIntersectionException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import java.util.Iterator;
/**
* 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) {
TreeSet<ProtectedRegion> appRegions =
new TreeSet<ProtectedRegion>();
for (ProtectedRegion region : regions.values()) {
if (region.contains(pt)) {
appRegions.add(region);
ProtectedRegion parent = region.getParent();
while (parent != null) {
if (!appRegions.contains(parent)) {
appRegions.add(region);
}
parent = parent.getParent();
}
}
}
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,262 @@
// $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.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.khelekore.prtree.MBRConverter;
import org.khelekore.prtree.PRTree;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.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) {
List<ProtectedRegion> appRegions =
new ArrayList<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);
}
}
Collections.sort(appRegions);
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,173 @@
// $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. If the regions do not load properly, then
* the existing list should be used (as stored previously).
*
* @throws IOException thrown on load error
*/
public void load() throws IOException {
loader.load(this);
}
/**
* Save the list of regions.
*
* @throws IOException thrown on save eIf checking multiple flags for a single locationror
*/
public void save() throws IOException {
loader.save(this);
}
/**
* Get a map of protected regions. Use one of the region manager methods
* if possible if working with regions.
*
* @return map of regions, with keys being region IDs (lowercase)
*/
public abstract Map<String, ProtectedRegion> getRegions();
/**
* Set a list of protected regions. Keys should be lowercase in the given
* map fo regions.
*
* @param regions map of regions
*/
public abstract void setRegions(Map<String, ProtectedRegion> regions);
/**
* Adds a region. If a region by the given name already exists, then
* the existing region will be replaced.
*
* @param region region to add
*/
public abstract void addRegion(ProtectedRegion region);
/**
* Return whether a region exists by an ID.
*
* @param id id of the region, can be mixed-case
* @return whether the region exists
*/
public abstract boolean hasRegion(String id);
/**
* Get a region by its ID.
*
* @param id id of the region, can be mixed-case
* @return region or null if it doesn't exist
*/
public abstract ProtectedRegion getRegion(String id);
/**
* Removes a region, including inheriting children.
*
* @param id id of the region, can be mixed-case
*/
public abstract void removeRegion(String id);
/**
* Get an object for a point for rules to be applied with. Use this
* in order to query for flag data or membership data for a given
* point.
*
* @param pt point
* @return applicable region set
*/
public abstract ApplicableRegionSet getApplicableRegions(Vector pt);
/**
* Get an object for a point for rules to be applied with. This gets
* a set for the given reason.
*
* @deprecated not yet fully supported
* @param region region
* @return regino set
*/
@Deprecated
public abstract ApplicableRegionSet getApplicableRegions(
ProtectedRegion region);
/**
* Get a list of region IDs that contain a point.
*
* @param pt point
* @return list of region Ids
*/
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 region to check
* @param player player to check against
* @return whether there is an overlap
*/
public abstract boolean overlapsUnownedRegion(ProtectedRegion region,
LocalPlayer player);
/**
* Get the number of regions.
*
* @return number of regions
*/
public abstract int size();
/**
* Get the number of regions for a player.
*
* @param player player
* @return name number of regions that a player owns
*/
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,282 @@
// $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; i2 < ((ProtectedPolygonalRegion)region).getPoints().size(); i2++) {
BlockVector2D pt2Dr = ((ProtectedPolygonalRegion)region).getPoints().get(i2);
int minYr = ((ProtectedPolygonalRegion)region).minY;
int maxYr = ((ProtectedPolygonalRegion)region).maxY;
Vector ptr = new Vector(pt2Dr.getBlockX(), minYr, pt2Dr.getBlockZ());
Vector ptr2 = new Vector(pt2Dr.getBlockX(), maxYr, pt2Dr.getBlockZ());
if (this.contains(ptr) || this.contains(ptr2)) {
intersectingRegions.add(regions.get(i));
continue;
}
}
} else if (region instanceof ProtectedCuboidRegion) {
BlockVector ptcMin = region.getMinimumPoint();
BlockVector ptcMax = region.getMaximumPoint();
if (this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMin.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMax.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMax.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMin.getBlockZ()))
|| this.contains(new Vector(ptcMax.getBlockX(), ptcMin.getBlockY(), ptcMax.getBlockZ())) ) {
intersectingRegions.add(regions.get(i));
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, 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;
}
}
@@ -0,0 +1,406 @@
// $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 region has members or owners.
*
* @return whether there are members or owners
*/
public boolean hasMembersOrOwners() {
return owners.size() > 0 || members.size() > 0;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param player player to check
* @return whether an owner
*/
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 OR OWNER of the region
* or any of its parents.
*
* @param player player to check
* @return whether an owner or member
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)
|| curParent.getMembers().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 player to check
* @return whether an member
*/
public boolean isMemberOnly(LocalPlayer player) {
if (members.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (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 (id.equals(other.id)) {
return 0;
} else if (priority == other.priority) {
return 1;
} 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();
/**
* Get a list of intersecting regions.
*
* @param regions
* @return
* @throws UnsupportedIntersectionException
*/
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();
}
/**
* Returns the hash code.
*/
@Override
public int hashCode(){
return id.hashCode();
}
/**
* Returns whether this region has the same ID as another region.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ProtectedRegion)) {
return false;
}
ProtectedRegion other = (ProtectedRegion) obj;
return other.getId().equals(getId());
}
/**
* Thrown when setting a curParent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
}
}
@@ -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,44 @@
// $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;
public class ArrayReader<T> {
private T[] arr;
public ArrayReader(T[] arr) {
this.arr = arr;
}
public T get(int index) {
if (arr.length > index) {
return arr[index];
} else {
return null;
}
}
public T get(int index, T def) {
if (arr.length > index) {
return arr[index];
} else {
return def;
}
}
}
@@ -0,0 +1,128 @@
// $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.Map;
import java.util.LinkedHashMap;
public class LogListBlock {
private LinkedHashMap <String, Object> items
= new LinkedHashMap<String, Object>();
private int maxKeyLength = 0;
private void updateKey(String key) {
if (key.length() > maxKeyLength) {
maxKeyLength = key.length();
}
}
public LogListBlock put(String key, String value) {
updateKey(key);
items.put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, LogListBlock value) {
updateKey(key);
items.put(key, value);
return this;
}
public LogListBlock put(String key, Object value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, String value, Object ... args) {
put(key, String.format(value, args));
return this;
}
public LogListBlock put(String key, int value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, byte value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, double value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, float value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, short value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, long value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock put(String key, boolean value) {
put(key, String.valueOf(value));
return this;
}
public LogListBlock putChild(String key) {
updateKey(key);
LogListBlock block = new LogListBlock();
items.put(key, block);
return block;
}
private String padKey(String key, int len) {
return String.format("%-" + len + "s", key);
}
protected String getOutput(String prefix) {
StringBuilder out = new StringBuilder();
for (Map.Entry<String, Object> entry : items.entrySet()) {
Object val = entry.getValue();
if (val instanceof LogListBlock) {
out.append(prefix);
out.append(padKey(entry.getKey(), maxKeyLength));
out.append(":\r\n");
out.append(((LogListBlock) val).getOutput(prefix + " "));
} else {
out.append(prefix);
out.append(padKey(entry.getKey(), maxKeyLength));
out.append(": ");
out.append(val.toString());
out.append("\r\n");
}
}
return out.toString();
}
@Override
public String toString() {
return getOutput("");
}
}
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more