Compare commits

...
192 Commits
Author SHA1 Message Date
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
sk89q 48ace4947b Updated for 1.4.1. 2010-11-21 11:40:26 -08:00
sk89q 57acbebaf1 Fixed issue with the block lag fix dropping item stacks of 0 quantity. 2010-11-21 11:34:46 -08:00
sk89q e15311178b Updated the README.txt. 2010-11-21 01:36:13 -08:00
sk89q 7385be7eff Fixed typo in worldguard.properties. 2010-11-21 01:30:50 -08:00
sk89q 9a29474132 Updated for 1.4. 2010-11-21 01:29:52 -08:00
sk89q 881f050f0d Inventory checks now won't be used if there are no on-acquire events. 2010-11-21 01:25:59 -08:00
sk89q 339bf1a06d Improved documentation. 2010-11-21 01:21:20 -08:00
sk89q bc70678387 Updated for new version of durability fix. 2010-11-21 01:13:33 -08:00
sk89q c3eef60672 Added no-physics-gravel, no-physics-sand, and allow-portal-anywhere. 2010-11-21 01:12:00 -08:00
sk89q eb78b390ca Added item-durability and blacklist on-acquire event. Thanks to Dinnerbone for heading my requests :) 2010-11-21 00:45:16 -08:00
sk89q a0fc3472e4 Updated blacklist and added Sturmeh's item durability 'fix' as sample rules. 2010-11-20 20:10:29 -08:00
sk89q 915946317d Updated the changelog to note the table schema change. 2010-11-20 12:01:38 -08:00
sk89q d4c4a497c4 Updated for 1.3. 2010-11-20 11:59:35 -08:00
sk89q 0286900829 The notify, log, and tell actions will now trigger every time for the on-break, on-create, on-drop events. 2010-11-20 11:53:57 -08:00
sk89q cf7874f776 Added comments and messages. Made the blacklist notification messages more compact and a different color. 2010-11-20 11:47:32 -08:00
sk89q 93c0295744 Added on-break event to the blacklist. 2010-11-20 11:13:18 -08:00
sk89q 9bc3a25191 Fixed signs being blank if they were denied via the blacklist. 2010-11-20 10:59:34 -08:00
sk89q e95d7a8b6e Improved plugin compatibility with the block lag fix. 2010-11-20 10:56:47 -08:00
sk89q 1edc48b16f Added SQL for the blacklist database table. 2010-11-19 22:06:49 -08:00
sk89q 07c8abff54 Improved blacklist documentation. 2010-11-19 22:02:46 -08:00
sk89q afff62120e Updated documentation and version for 1.2. 2010-11-19 21:59:56 -08:00
sk89q ff8c48e69e Added fire spread spreading enabling and disabling commands. 2010-11-19 21:49:31 -08:00
sk89q b9e84f7b4a Improved item drop list for the block lag fix. 2010-11-19 21:34:14 -08:00
sk89q 924e6f3777 Fixed typo in source. 2010-11-19 21:17:30 -08:00
sk89q 6d0d2ee538 Sponge now removes water and obeys new 'sponge-radius' configuration variable. 2010-11-19 21:14:01 -08:00
sk89q 8983d7bc84 Fixed classic water for the onFlow update. 2010-11-19 21:02:54 -08:00
sk89q fc81a7034e Block lag fix now fakes block status 3 for other plugins. 2010-11-19 20:58:34 -08:00
sk89q b7e5828c3f WorldGuard should now close loggers on disable and reload. 2010-11-19 20:34:38 -08:00
sk89q e543ac733f Fixed errors caused by reloading the plugin. 2010-11-19 20:32:41 -08:00
sk89q d09fcab7b3 Updated onFlow hook for the new changes. 2010-11-19 20:31:12 -08:00
sk89q 70c6b26db5 Added summary-on-start configuration setting to control whether the summary should be printed. 2010-11-19 20:09:26 -08:00
sk89q 1859fc5db2 Overhauled the blacklist system.
- The blacklist's method of preventing notification repeats is now better, instead waiting 3 seconds before notifying again (before it didn't notify again at all unless the user started using another blocked action).
- To give users the ability to receive notifications, the command to give permission to has been changed to /worldguardnotify, although the old one (that was never mentioned anywhere) still works.
- Water and lava buckets are now psuedo-blocked using an unreliable method that risks the stability of your server (no other plugin does it better though). Use it as your own risk.
- Added on item drop and on item use (i.e. chest) events.
- Chests, signs, and furnaces can now be blocked better with the blacklist system.
- The event names in the blacklist configuration have changed but the old event names should still work. The new names should make "more sense."
- A new "ban" action has been added to the blacklist.
- Action messages have been improved, now longer saying "destroyed" for everything.
- Logging to file has been completely changed, allowing you to use the date and time and the player's username in the log filename. It no longer rotates log files based on size, however.
- Logging to database is now supported.
2010-11-19 20:03:19 -08:00
sk89q 47a4046d47 Merge branch 'master' of https://github.com/Sturmeh/worldguard into Worldguard. 2010-11-19 02:12:11 -08:00
sk89q 7b3a8402a1 Added 'right click on' events to the blacklist. 2010-11-19 02:01:10 -08:00
sk89q 84eb9343ce Improved water/bucket fix by having it set back the original block. Unfortunately this doesn't do anything about setting water buckets into lava (creating obsidian). 2010-11-19 00:14:08 -08:00
sk89q 0a8dd85224 Added a bucket block fix, but not a great one. 2010-11-18 23:58:22 -08:00
Sturmeh d4a3e04622 Merge branch 'master' of http://github.com/sk89q/worldguard 2010-11-18 16:40:49 +11:00
Sturmeh 2562502d26 Added itemDropBlacklist 2010-11-18 16:40:43 +11:00
sk89q e12fcdb1b8 Moved the block lag fix to a low priority listener. 2010-11-17 20:33:29 -08:00
68 changed files with 8622 additions and 1190 deletions

No files matched your search

+211
View File
@@ -1,3 +1,214 @@
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.
1.4
- New on-acquire hook. This does both a total inventory check on inventory
change and item pick up denial. The item pick up denial is largely
thanks to Dinnerbone for fulfilling my request to add a particular hook.
- Item durability can now be toggled with item-durability. Thanks to
Dinnerbone for figuring this out while filfilling my request. The
default setting is to fix item durability.
- New no-physics-gravel and no-physics-sand options allow you to
prevent gravel and sand from falling.
- New allow-portal-anywhere option allows you to create portal blocks
anywhere.
1.3
- UPGRADE WARNING: If you are using database logging, you must add a
NULL 'comment' VARCHAR field to the table. The line of SQL that you
can run for MySQL can be found in blacklist_table.sql.
- Improved plugin compatibility with the block lag fix. For maximum
compatibility, you must now list WorldGuard as the first plugin in
server.properties and you cannot reload or enable the plugin
while the server is up. This is for bad plugins that unnecessarily
use the "critical" priority for its hooks like the LWC. Most plugins
don't do that though, so this won't apply for most people.
- Fixed signs being blank if they were denied via the blacklist.
- Added on-break event to the blacklist.
- Added comments and messages. Comments are only for your own use and they
are printed with the log and notify actions of the blacklist. The
message replaces the message that is shown the user and it is optional.
- The blacklist notification messages are now more compact and are
light grey instead of light purple.
- The notify, log, and tell actions will now trigger every time for the
on-break, on-create, on-drop events rather than wait 3 seconds between
events for the same item or block for a player.
1.2
- /stopfire and /allowfire disable and enable fire spreading globally.
- Block lag fix slightly improved in accuracy for item drops.
- Sponge updated to remove water when the sponge block is set. Sponge radius
can now be controlled using the 'sponge-radius' parameter and the
default is now set to simulate Classic.
- Updated for a newer build of "b126," meaning that lava spread control
now works well!
- A new summary of the status of some core protections is now printed
on start. Disable this with 'summary-on-start'.
- Blacklist system has been overhauled. Check README.txt for changed
configuration settings!
- The blacklist's method of preventing notification repeats is now better,
instead waiting 3 seconds before notifying again (before it didn't
notify again at all unless the user started using another blocked
action).
- To give users the ability to receive notifications, the command to give
permission to has been changed to /worldguardnotify, although the
old one (that was never mentioned anywhere) still works.
- Water and lava buckets are now psuedo-blocked using an unreliable
method that risks the stability of your server (no other plugin
does it better though). Use it as your own risk.
- Added on item drop and on item use (i.e. chest) events.
- Chests, signs, and furnaces can now be blocked better with the
blacklist system.
- The event names in the blacklist configuration have changed but the old
event names should still work. The new names should make "more sense."
- A new "ban" action has been added to the blacklist.
- Action messages have been improved, now longer saying "destroyed"
for everything.
- Logging to file has been completely changed, allowing you to use
the date and time and the player's username in the log filename. It
no longer rotates log files based on size, however.
- Logging to database is now supported.
- Tools can now be destroyed on drop to alleviate the durability cheat.
You can do this with either with the blacklist or with the
'item-drop-blacklist' configuration option. The configuration option
prints more friendly messages than the 'tell' action of blacklists.
1.1.2
- Block lag fix: Snow and glass should no longer drop items.
- Block lag fix: Block object now reset after hook call.
-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.
+13 -100
View File
@@ -1,110 +1,23 @@
WorldGuard
Copyright (c) 2010 sk89q <http://www.sk89q.com>
Copyright (c) 2010, 2011 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:
WorldGuard protects your server!
- 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 sponge.
- Block the use, destruction and/or placement of some items or block types.
- Notify admins when a certain block type or item is used, destroyed,
or place.
- Log the use, destruction, and/or placement of some blocks/items.
- Kick for the use, destruction, and/or placement of some blocks.
Documentation can be found at:
http://wiki.sk89q.com/wiki/WorldGuard
hMod is required as WorldGuard is a plugin for hMod.
Thanks
------
Configuration
-------------
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:
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.
- 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. The sponge only prevents water
from spreading. It will not take away existing water. Simulation of
the sponge requires iterating over a 9x9x9 cuboid around the water
block and the resource impact of this has not been quantified.
- 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.
- blacklist-log-console (def. true)
For log actions, print to console as well.
- blacklist-log-file (no default)
File to log to. Log files are automatically rotated based on size, and
you can use these patterns in the path:
%t the system temporary directory
%h the value of the "user.home" system property
%g the generation number to distinguish rotated logs
%u a unique number to resolve conflicts
%% translates to a single percent sign "%"
There is no way to put the date in the filename or rotate by date.
- blacklist-log-file-limit (def. 5242880)
Size in bytes before the log file is rotated.
- blacklist-log-file-count (def. 10)
Number of log files to keep in rotation at maximum.
- 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. They will not explode client-side.
- 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.
- block-lag-fix (def. false)
Attempts to fix block lag.
Blacklists
----------
Edit the included worldguard-blacklist.txt file and follow the
instructions inside.
- 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
+84
View File
@@ -0,0 +1,84 @@
#
# This is the blacklist for WorldGuard. The blacklist allows you to perform
# actions depending on an item or block ID. Comments start with # and they
# are ignored so you can put your own notes.
#
# --------------------------------------------------------------------------
#
# WARNING:
# Remember to check the compatibility spreadsheet for WorldGuard to see
# if any events or actions are currently broken in your version of Bukkit.
#
# --------------------------------------------------------------------------
#
# Format:
# [item1,item2]
# option1=options
# event1=whatToDo1,whatToDo2,whatToDo3
# event2=whatToDo1,whatToDo2
#
# Example to block some ore mining and placement:
# [coalore,goldore,ironore]
# on-break=deny,log,kick
# on-place=deny,tell
#
# Options:
# - ignore-groups (comma-separated list of groups to not affect)
# - comment (message for yourself that is printed with 'log' and 'notify')
# - message (optional message to show the user instead; %s is the item name)
#
# Events:
# - on-break (when a block of this type is about to be broken)
# - on-destroy-with (the item/block held by the user while destroying)
# - on-place (a block is being placed)
# - on-use (an item like flint and steel or a bucket is being used)
# - on-interact (when a block in used (doors, chests, etc.))
# - on-drop (an item is being dropped from the player's inventory)
# - on-acquire (an item enters a player's inventory via some method)
#
# Actions (for events):
# - deny (deny completely)
# - notify (notify admins)
# - log (log to console/file/database)
# - tell (tell a player that that's not allowed)
# - kick (kick player)
# - ban (ban player)
#
# Users with the /worldguardnotify permission will receive notifications.
#
# -------------
#
# You can have the same block or item used in two different sections and
# they will both apply:
#
# [goldblock]
# ignore-groups=vip
# on-break=deny
# [goldblock]
# ignore-groups=admins
# on-break=tell
#
# However, some events override others. For example, if you disable both
# usage of the diamond pickaxe (with the on-destroy-with event) and
# destruction of gold blocks (with the on-break event) and a player tries
# to destroy a gold block with a diamond pickaxe, because the
# on-destroy-with event comes first, the rules for the gold block
# will not be applied (but the player will be denied nevertheless).
#
# --------------------------------------------------------------------------
#
# Some examples follow.
#
# REMEMBER: If a line has # in front, it will be ignored.
#
# --------------------------------------------------------------------------
# Deny lava buckets
#[lavabucket]
#ignore-groups=admins,mods
#on-use=deny,tell
# Deny some ore
#[coalore,goldore,ironore]
#ignore-groups=admins,mods
#on-break=notify,deny,log
+21
View File
@@ -0,0 +1,21 @@
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
+104
View File
@@ -0,0 +1,104 @@
<project name="WorldGuard" default="dist" basedir=".">
<description>WorldGuard fixes bugs with Minecraft SMP and provides for
protection.</description>
<property name="src.dir" location="src"/>
<property name="build.dir" location="build"/>
<property name="dist.dir" location="dist"/>
<property name="release.dir" location="release"/>
<property name="lib.dir" location="lib"/>
<property name="docs.dir" location="docs"/>
<fileset id="libs" dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
<target name="init">
<mkdir dir="${build.dir}"/>
</target>
<!-- Compile the source files -->
<target name="compile" depends="init">
<javac srcdir="${src.dir}" deprecation="true" includeantruntime="true" destdir="${build.dir}" debug="true">
<classpath>
<fileset refid="libs"/>
</classpath>
</javac>
</target>
<!-- Build the .jar -->
<target name="jar" depends="compile">
<mkdir dir="${dist.dir}"/>
<manifest file="manifest.mf" mode="replace">
<attribute name="Implementation-Title" value="WorldGuard"/>
<attribute name="Implementation-Version" value="${version}"/>
<attribute name="WorldGuard-Version" value="${version}"/>
<attribute name="Class-Path" value="WorldEdit.jar WorldGuard/WorldEdit.jar"/>
</manifest>
<delete file="${build.dir}/plugin.yml"/>
<copy tofile="${build.dir}/plugin.yml" file="plugin.yml"/>
<replace file="${build.dir}/plugin.yml" token="WGVERSIONMACRO" value="${version}"/>
<mkdir dir="${build.dir}/defaults"/>
<copy tofile="${build.dir}/defaults/config.yml" file="config.yml"/>
<copy tofile="${build.dir}/defaults/blacklist.txt" file="blacklist.txt"/>
<jar jarfile="${dist.dir}/WorldGuard.jar" basedir="${build.dir}" manifest="manifest.mf"/>
</target>
<!-- Create the .jar -->
<target name="dist">
<property name="version" value="nightly"/>
<antcall target="jar"/>
</target>
<!-- Build a release -->
<target name="release" depends="clean">
<input message="Enter version:" addproperty="version"/>
<antcall target="jar"/>
<delete dir="${release.dir}"/>
<mkdir dir="${release.dir}"/>
<copy tofile="${release.dir}/README.txt" file="README.txt"/>
<copy tofile="${release.dir}/LICENSE.txt" file="LICENSE.txt"/>
<copy tofile="${release.dir}/CHANGELOG.txt" file="CHANGELOG.txt"/>
<copy tofile="${release.dir}/blacklist_table.sql" file="blacklist_table.sql"/>
<copy tofile="${release.dir}/WorldGuard.jar" file="${dist.dir}/WorldGuard.jar"/>
<zip destfile="${release.dir}/worldguard-${version}.zip" basedir="${release.dir}" excludes="*.zip plugin.yml"/>
<mkdir dir="${release.dir}/src"/>
<copy todir="${release.dir}/src">
<fileset dir="${src.dir}"/>
</copy>
<zip destfile="${release.dir}/worldguard-${version}-src.zip" basedir="${release.dir}" excludes="*.zip plugin.yml"/>
</target>
<!-- Javadoc -->
<target name="javadoc">
<javadoc access="public" author="true" destdir="${docs.dir}" doctitle="WorldGuard API" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" source="1.6" sourcepath="src" splitindex="true" use="true" version="true">
<classpath>
<fileset refid="libs"/>
</classpath>
</javadoc>
</target>
<!-- Clean the output -->
<target name="clean">
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
<delete dir="${release.dir}"/>
<delete dir="${docs.dir}"/>
</target>
<!--<target name="-get-version-git" if="git-revision">
<sequential>
<exec executable="git" failifexecutionfails="false" outputproperty="git-revision">
<arg value="rev-parse"/>
<arg value="HEAD"/>
</exec>
<exec executable="git" outputproperty="git-revision-dirty">
<arg value="diff"/>
<arg value="- -shortstat"/>
</exec>
<condition else="dev-${git-revision}-modified" property="version" value="dev-${git-revision}">
<equals arg1="" arg2="${git-revision-dirty}"/>
</condition>
</sequential>
</target>-->
</project>
+99
View File
@@ -0,0 +1,99 @@
#
# WorldGuard's configuration file
#
# About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
# you use an editor like Notepad++ (recommended for Windows users), you
# must configure it to "replace tabs with spaces." In Notepad++, this can
# be changed in Settings > Preferences > Language Menu.
# - Don't get rid of the indents. They are indented so some entries are
# in categories (like "enforce-single-session" is in the "protection"
# category.
# - If you want to check the format of this file before putting it
# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:".
# - Lines starting with # are commentsand so they are ignored.
#
# WARNING:
# Remember to check the compatibility spreadsheet for WorldGuard to see
# if any features are currently broken in your version of Bukkit.
#
summary-on-start: on
protection:
enforce-single-session: on
item-durability: on
simulation:
sponge:
enable: on
redstone: off
radius: 3
physics:
no-physics-gravel: off
no-physics-sand: off
allow-portal-anywhere: off
disable-water-damage-blocks: []
ignition:
block-tnt: off
block-lighter: off
fire:
disable-all-fire-spread: off
disable-fire-spread-blocks: []
disable-lava-fire-spread: on
lava-spread-blocks: []
mobs:
block-creeper-explosions: off
block-creeper-block-damage: off
spawn:
login-protection: 3
spawn-protection: 0
kick-on-death: off
exact-respawn: off
teleport-to-home-on-death: off
player-damage:
disable-fall-damage: off
disable-lava-damage: off
disable-fire-damage: off
disable-drowning-damage: off
disable-suffocation-damage: off
disable-contact-damage: off
teleport-on-suffocation: off
regions:
enable: on
wand: 287
default:
build: true
chest-access: false
pvp: true
blacklist:
logging:
console:
enable: on
database:
enable: off
dsn: jdbc:mysql://localhost:3306/minecraft
user: root
password: pass
table: blacklist_events
file:
enable: on
path: worldguard/logs/%Y-%m-%d.log
open-files: 10
# See http://wiki.sk89q.com/wiki/WorldGuard/Permissions/Bukkit
permissions:
users:
sk89q:
permissions:
- /region
- /reloadwg
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="javadoc">
<target name="javadoc">
<javadoc access="public" author="true" classpath="P:\Projects\Minecraft\Libraries\GroupUsers.jar;P:\Projects\Minecraft\Libraries\jnbt.jar;P:\Projects\Minecraft\hMod\build\classes;P:\Projects\Minecraft\WorldEdit\build\classes;P:\Projects\Minecraft\Libraries\snakeyaml.jar;P:\Projects\Minecraft\Libraries\jopt-simple-3.2.jar;P:\Projects\Minecraft\Libraries\Permissions.jar;C:\Program Files\eclipse\plugins\org.hamcrest.core_1.1.0.v20090501071000.jar;P:\Projects\Minecraft\Libraries\json_simple-1.1.jar;P:\Projects\Minecraft\CraftBukkit\bin;P:\Projects\Minecraft\Libraries\truezip.jar;C:\Program Files\eclipse\plugins\org.junit_4.8.1.v4_8_1_v20100427-1100\junit.jar;P:\Projects\Minecraft\Bukkit\bin;P:\Projects\Minecraft\mc-dev" destdir="doc" doctitle="Worldguard API" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" packagenames="com.sk89q.worldguard.blacklist,com.sk89q.worldguard.domains,com.sk89q.worldguard.bukkit,com.sk89q.worldguard.protection,com.sk89q.worldguard.util,au.com.bytecode.opencsv,com.sk89q.worldguard,com.sk89q.worldguard.blacklist.loggers,com.sk89q.worldguard.blacklist.events" source="1.6" sourcepath="tests;src" splitindex="true" use="true" version="true"/>
</target>
</project>
-2
View File
@@ -1,2 +0,0 @@
Manifest-Version: 1.0
WorldGuard-Version: 1.1.2
+33
View File
@@ -0,0 +1,33 @@
name: WorldGuard
main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: WGVERSIONMACRO
commands:
stopfire:
description: Halts all fire spread until it is disabled or the server is restarted
usage: /<command>
allowfire:
description: Re-enables fire spread if he has been disabled with /stopfire
usage: /<command>
god:
description: Toggles god mode
usage: /<command> [other player]
heal:
description: Heal yourself or another
usage: /<command> [other player]
slay:
description: Slay yourself or another
usage: /<command> [other player]
stack:
description: Stacks items in the player's inventory
usage: /<command>
aliases: ;
region:
description: Adjust protected regions
usage: /<command> <define|claim|setparent|flag|delete|info|addowner|removeowner|addmember|removemember|list|save|load> ...
aliases: rg, regions
locate:
description: Set your compass towards a person
usage: /<command> <target>
reloadwg:
description: Reload WorldGuard's configuration
usage: /<command>
-267
View File
@@ -1,267 +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,Integer> lastAffected =
new HashMap<String,Integer>();
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("WorldGuard.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 left click.
*/
private String[] leftClickActions;
/**
* List of actions to perform on right click.
*/
private String[] rightClickActions;
/**
* @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 the destroyActions
*/
public String[] getDestroyActions() {
return destroyActions;
}
/**
* @param destroyActions the destroyActions to set
*/
public void setDestroyActions(String[] destroyActions) {
this.destroyActions = destroyActions;
}
/**
* @return the leftClickActions
*/
public String[] getLeftClickActions() {
return leftClickActions;
}
/**
* @param leftClickActions the leftClickActions to set
*/
public void setLeftClickActions(String[] leftClickActions) {
this.leftClickActions = leftClickActions;
}
/**
* @return the rightClickActions
*/
public String[] getRightClickActions() {
return rightClickActions;
}
/**
* @param rightClickActions the rightClickActions to set
*/
public void setRightClickActions(String[] rightClickActions) {
this.rightClickActions = rightClickActions;
}
/**
* 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.sendMessage(Colors.LightPurple + "WorldGuard: " + str);
}
}
}
/**
* Log a message.
*
* @param message
*/
public void log(String message) {
logger.log(Level.INFO, message);
}
/**
* Called on block destruction. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onDestroy(Block block, Player player) {
if (destroyActions == null) {
return true;
}
boolean ret = process(block.getType(), player, destroyActions);
lastAffected.put(player.getName(), block.getType());
return ret;
}
/**
* Called on left click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onLeftClick(int item, Player player) {
if (leftClickActions == null) {
return true;
}
boolean ret = process(item, player, leftClickActions);
lastAffected.put(player.getName(), item);
return ret;
}
/**
* Called on right right. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onRightClick(int item, Player player) {
if (rightClickActions == null) {
return true;
}
boolean ret = process(item, player, rightClickActions);
lastAffected.put(player.getName(), item);
return ret;
}
/**
* Internal method to handle the actions.
*
* @param id
* @param player
* @param actions
* @return
*/
private boolean process(int id, Player player, String[] actions) {
if (shouldIgnore(player)) {
return true;
}
String name = player.getName();
boolean repeating = lastAffected.containsKey(name)
&& lastAffected.get(name) == id;
boolean ret = true;
for (String action : actions) {
if (action.equalsIgnoreCase("deny")) {
ret = false;
} else if (action.equalsIgnoreCase("kick")) {
player.kick("Performed disallowed action with "
+ etc.getDataSource().getItem(id) + ".");
} else if (!repeating) {
if (action.equalsIgnoreCase("notify")) {
notifyAdmins(player.getName() + " on destroy: "
+ etc.getDataSource().getItem(id));
} else if (action.equalsIgnoreCase("log")) {
log(player.getName() + " on destroy: "
+ etc.getDataSource().getItem(id));
} else if (!repeating && action.equalsIgnoreCase("tell")) {
player.sendMessage("Can't do that with "
+ 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 = new HashMap<String,Integer>();
}
}
-107
View File
@@ -1,107 +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.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.BLOCK_CREATED, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.BLOCK_DESTROYED, listener, this,
PluginListener.Priority.HIGH);
loader.addListener(PluginLoader.Hook.DISCONNECT, listener, this,
PluginListener.Priority.HIGH);
}
/**
* Enables the plugin.
*/
@Override
public void enable() {
logger.log(Level.INFO, "WorldGuard version " + getVersion() + " loaded");
listener.loadConfiguration();
}
/**
* Disables the plugin.
*/
@Override
public void disable() {
BlacklistEntry.forgetAllPlayers();
}
/**
* 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)";
}
}
}
-584
View File
@@ -1,584 +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.logging.Handler;
import java.util.logging.ConsoleHandler;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Random;
import java.io.*;
import com.sk89q.worldguard.*;
import java.util.logging.FileHandler;
/**
* Event listener for Hey0's server mod.
*
* @author sk89q
*/
public class WorldGuardListener extends PluginListener {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Random number generator.
*/
private static Random rand = new Random();
/**
* Plugin host.
*/
private WorldGuard plugin;
/**
* Properties file for CraftBook.
*/
private PropertiesFile properties = new PropertiesFile("worldguard.properties");
/**
* List of blocks to remove when possible.
*/
private LinkedList<int[]> blockRemoveQueue = new LinkedList<int[]>();
private boolean enforceOneSession;
private boolean blockCreepers;
private boolean blockTNT;
private boolean blockLighter;
private boolean preventLavaFire;
private boolean disableAllFire;
private boolean simulateSponge;
private boolean blockLagFix;
private Set<Integer> fireNoSpreadBlocks;
private Set<Integer> allowedLavaSpreadOver;
private boolean classicWater;
private Map<Integer,BlacklistEntry> 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();
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);
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);
blockLagFix = properties.getBoolean("block-lag-fix", false);
try {
blacklist = loadBlacklist(new File("worldguard-blacklist.txt"));
} 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());
}
Logger blacklistLogger = Logger.getLogger("WorldGuard.Blacklist");
blacklistLogger.setUseParentHandlers(false);
for (Handler handler : blacklistLogger.getHandlers()) {
blacklistLogger.removeHandler(handler);
}
// Blacklist log to console
if (properties.getBoolean("blacklist-log-console", true)) {
Handler handler = new ConsoleHandler();
handler.setFormatter(new ConsoleLogFormat());
blacklistLogger.addHandler(handler);
}
// Blacklist log file
String logFile = properties.getString("blacklist-log-file", "").trim();
int limit = properties.getInt("blacklist-log-file-limit", 1024 * 1024 * 5);
int count = properties.getInt("blacklist-log-file-count", 10);
if (logFile.length() > 0) {
try {
Handler handler = new FileHandler(logFile, limit, count, true);
handler.setFormatter(new SimpleLogFormat());
blacklistLogger.addHandler(handler);
} catch (IOException e) {
logger.log(Level.WARNING, "Could not open blacklist log file: "
+ e.getMessage());
}
}
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 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) {
BlacklistEntry entry = blacklist.get(itemInHand);
if (entry != null) {
if (!entry.onRightClick(itemInHand, player)) {
// Water/lava bucket fix
if (itemInHand == 326 || itemInHand == 327) {
blockPlaced.setType(0);
blockPlaced.update();
}
return true;
}
}
}
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) {
BlacklistEntry entry = blacklist.get(player.getItemInHand());
if (entry != null) {
if (entry.onLeftClick(player.getItemInHand(), player)) {
return true;
}
}
entry = blacklist.get(block.getType());
if (entry != null) {
if (!entry.onDestroy(block, player)) {
return true;
}
}
}
if (blockLagFix
&& type != 64 // Wooden door
&& type != 71 // Iron door
&& type != 77 // Stone button
&& type != 69 // Lever
&& type != 7 // Bedrock
&& type != 51 // Fire
&& type != 46 // TNT
&& type != 59 // Crops
&& type != 62 // Burning furnace
&& type != 50 // Torch
&& type != 75 // Redstone torch
&& type != 76 // Redstone torch
) {
// 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) {
int dropped = type;
int count = 1;
if (type == 1) { dropped = 4; } // Stone
else if (type == 2) { dropped = 3; } // Grass
else if (type == 16) { dropped = 263; } // Coal ore
else if (type == 18) { // Leaves
if (rand.nextDouble() > 0.95) {
dropped = 6;
} else {
dropped = 0;
}
}
else if (type == 20) { dropped = 0; } // Glass
else if (type == 47) { dropped = 0; } // Bookshelves
else if (type == 52) { dropped = 0; } // Mob spawner
else if (type == 53) { dropped = 5; } // Wooden stairs
else if (type == 55) { dropped = 331; } // Redstone wire
else if (type == 56) { dropped = 264; } // Diamond ore
else if (type == 60) { dropped = 3; } // Soil
else if (type == 63) { dropped = 323; } // Sign post
else if (type == 67) { dropped = 4; } // Cobblestone stairs
else if (type == 68) { dropped = 323; } // Wall sign
else if (type == 73) { dropped = 331; count = 4; } // Redstone ore
else if (type == 74) { dropped = 331; count = 4; } // Glowing redstone ore
else if (type == 75) { dropped = 76; count = 4; } // Redstone torch
else if (type == 78) { dropped = 0; } // Snow
else if (type == 79) { dropped = 0; count = 4; } // Ice
else if (type == 82) { dropped = 337; count = 4; } // Clay
else if (type == 83) { dropped = 338; count = 4; } // Reed
else if (type == 89) { dropped = 348; } // Lightstone
etc.getServer().setBlockAt(0, block.getX(), block.getY(), block.getZ());
if (dropped > 0) {
for (int i = 0; i < count; i++) {
etc.getServer().dropItem(block.getX(), block.getY(), block.getZ(),
dropped, i);
}
// Drop flint with gravel
if (type == 13) {
if (rand.nextDouble() > 0.95) {
etc.getServer().dropItem(block.getX(), block.getY(), block.getZ(),
318, 1);
}
}
}
}
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 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 (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 lava wants to flow to a certain block.
* block status represents the type that wants to flow.
* (10 & 11 for lava and 8 & 9 for water)
*
* @param block
* the block beneath where the substance wants to flow to.
*
* for example:
* lava want to flow to block x,y,z then the param block is the block x,y-1,z.
*
* @return true if you dont want the substance to flow.
*/
public boolean onFlow(Block block) {
if (simulateSponge && (block.getStatus() == 8 || block.getStatus() == 9)) {
int ox = block.getX();
int oy = block.getY() + 1;
int oz = block.getZ();
Server server = etc.getServer();
for (int x = -4; x <= 4; x++) {
for (int y = -4; y <= 4; y++) {
for (int z = -4; z <= 4; z++) {
if (server.getBlockIdAt(ox + x, oy + y, oz + z) == 19) {
return true;
}
}
}
}
}
if (classicWater && (block.getStatus() == 8 || block.getStatus() == 9)) {
int blockBelow = etc.getServer().getBlockIdAt(block.getX(), block.getY(), block.getZ());
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
etc.getServer().setBlockAt(9, block.getX(), block.getY() + 1, block.getZ());
return false;
}
}
if (allowedLavaSpreadOver != null && (block.getStatus() == 10 || block.getStatus() == 11)) {
if (!allowedLavaSpreadOver.contains(block.getType())) {
return true;
}
}
return false;
}
/**
* Called on player disconnect
*
* @param player
*/
public void onDisconnect(Player player) {
BlacklistEntry.forgetPlayer(player);
}
/**
* Checks if a block can be destroyed.
*
* @param player
* @param block
* @return
*/
public 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();
}
}
/**
* Load the blacklist.
*
* @param file
* @return
* @throws IOException
*/
public Map<Integer,BlacklistEntry> loadBlacklist(File file)
throws IOException {
FileReader input = null;
Map<Integer,BlacklistEntry> blacklist = new HashMap<Integer,BlacklistEntry>();
try {
input = new FileReader(file);
BufferedReader buff = new BufferedReader(input);
String line;
List<BlacklistEntry> entries = null;
while ((line = buff.readLine()) != null) {
line = line.trim();
// Blank line
if (line.length() == 0) {
continue;
} else if (line.charAt(0) == ';' || line.charAt(0) == '#') {
continue;
}
if (line.matches("^\\[.*\\]$")) {
String[] items = line.substring(1, line.length() - 1).split(",");
entries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = etc.getDataSource().getItem(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
+ item);
break;
}
}
BlacklistEntry entry = new BlacklistEntry();
blacklist.put(id, entry);
entries.add(entry);
}
} else if (entries != null) {
String[] parts = line.split("=");
if (parts.length == 1) {
logger.log(Level.WARNING, "Found option with no value "
+ file.getName() + " for '" + line + "'");
continue;
}
boolean unknownOption = false;
for (BlacklistEntry entry : entries) {
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("on-left")) {
entry.setLeftClickActions(parts[1].split(","));
} else if(parts[0].equalsIgnoreCase("on-right")) {
entry.setRightClickActions(parts[1].split(","));
} else {
unknownOption = true;
}
}
if (unknownOption) {
logger.log(Level.WARNING, "Unknown option '" + parts[0]
+ "' in " + file.getName() + " for '" + line + "'");
}
} else {
logger.log(Level.WARNING, "Found option with no heading "
+ file.getName() + " for '" + line + "'");
}
}
return blacklist.isEmpty() ? null : blacklist;
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e2) {
}
}
}
}
+307
View File
@@ -0,0 +1,307 @@
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package au.com.bytecode.opencsv;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* A very simple CSV parser released under a commercial-friendly license.
* This just implements splitting a single line into fields.
*
* @author Glen Smith
* @author Rainer Pruy
*
*/
public class CSVParser {
private final char separator;
private final char quotechar;
private final char escape;
private final boolean strictQuotes;
private String pending;
private boolean inField = false;
private final boolean ignoreLeadingWhiteSpace;
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
public static final int INITIAL_READ_SIZE = 128;
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/**
* The default escape character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
/**
* The default strict quote behavior to use if none is supplied to the
* constructor
*/
public static final boolean DEFAULT_STRICT_QUOTES = false;
/**
* The default leading whitespace behavior to use if none is supplied to the
* constructor
*/
public static final boolean DEFAULT_IGNORE_LEADING_WHITESPACE = true;
/**
* Constructs CSVParser using a comma for the separator.
*/
public CSVParser() {
this(DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVParser with supplied separator.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVParser(char separator) {
this(separator, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVParser with supplied separator and quote char.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVParser(char separator, char quotechar) {
this(separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
*/
public CSVParser(char separator, char quotechar, char escape) {
this(separator, quotechar, escape, DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
* Allows setting the "strict quotes" flag
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param strictQuotes
* if true, characters outside the quotes are ignored
*/
public CSVParser(char separator, char quotechar, char escape, boolean strictQuotes) {
this(separator, quotechar, escape, strictQuotes, DEFAULT_IGNORE_LEADING_WHITESPACE);
}
/**
* Constructs CSVReader with supplied separator and quote char.
* Allows setting the "strict quotes" and "ignore leading whitespace" flags
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param strictQuotes
* if true, characters outside the quotes are ignored
* @param ignoreLeadingWhiteSpace
* if true, white space in front of a quote in a field is ignored
*/
public CSVParser(char separator, char quotechar, char escape, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) {
this.separator = separator;
this.quotechar = quotechar;
this.escape = escape;
this.strictQuotes = strictQuotes;
this.ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace;
}
/**
*
* @return true if something was left over from last call(s)
*/
public boolean isPending() {
return pending != null;
}
public String[] parseLineMulti(String nextLine) throws IOException {
return parseLine(nextLine, true);
}
public String[] parseLine(String nextLine) throws IOException {
return parseLine(nextLine, false);
}
/**
* Parses an incoming String and returns an array of elements.
*
* @param nextLine
* the string to parse
* @param multi
* @return the comma-tokenized list of elements, or null if nextLine is null
* @throws IOException if bad things happen during the read
*/
private String[] parseLine(String nextLine, boolean multi) throws IOException {
if (!multi && pending != null) {
pending = null;
}
if (nextLine == null) {
if (pending != null) {
String s = pending;
pending = null;
return new String[] {s};
} else {
return null;
}
}
List<String>tokensOnThisLine = new ArrayList<String>();
StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE);
boolean inQuotes = false;
if (pending != null) {
sb.append(pending);
pending = null;
inQuotes = true;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == this.escape) {
if( isNextCharacterEscapable(nextLine, inQuotes || inField, i) ){
sb.append(nextLine.charAt(i+1));
i++;
}
} else if (c == quotechar) {
if( isNextCharacterEscapedQuote(nextLine, inQuotes || inField, i) ){
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if (!strictQuotes) {
if(i>2 //not on the beginning of the line
&& nextLine.charAt(i-1) != this.separator //not at the beginning of an escape sequence
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
){
if (ignoreLeadingWhiteSpace && sb.length() > 0 && isAllWhiteSpace(sb)) {
sb = new StringBuilder(INITIAL_READ_SIZE); //discard white space leading up to quote
} else {
sb.append(c);
}
}
}
}
inField = !inField;
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuilder(INITIAL_READ_SIZE); // start work on next token
inField = false;
} else {
if (!strictQuotes || inQuotes){
sb.append(c);
inField = true;
}
}
}
// line is done - check status
if (inQuotes) {
if (multi) {
// continuing a quoted section, re-append newline
sb.append("\n");
pending = sb.toString();
sb = null; // this partial content is not to be added to field list yet
} else {
throw new IOException("Un-terminated quoted field at end of CSV line");
}
}
if (sb != null) {
tokensOnThisLine.add(sb.toString());
}
return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]);
}
/**
* precondition: the current character is a quote or an escape
* @param nextLine the current line
* @param inQuotes true if the current context is quoted
* @param i current index in line
* @return true if the following character is a quote
*/
private boolean isNextCharacterEscapedQuote(String nextLine, boolean inQuotes, int i) {
return inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar;
}
/**
* precondition: the current character is an escape
* @param nextLine the current line
* @param inQuotes true if the current context is quoted
* @param i current index in line
* @return true if the following character is a quote
*/
protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) {
return inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& ( nextLine.charAt(i+1) == quotechar || nextLine.charAt(i+1) == this.escape);
}
/**
* precondition: sb.length() > 0
* @param sb A sequence of characters to examine
* @return true if every character in the sequence is whitespace
*/
protected boolean isAllWhiteSpace(CharSequence sb) {
boolean result = true;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if ( !Character.isWhitespace(c) ) {
return false;
}
}
return result;
}
}
+282
View File
@@ -0,0 +1,282 @@
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package au.com.bytecode.opencsv;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* A very simple CSV reader released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
public class CSVReader implements Closeable {
private BufferedReader br;
private boolean hasNext = true;
private CSVParser parser;
private int skipLines;
private boolean linesSkiped;
/**
* The default line to start reading.
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Constructs CSVReader using a comma for the separator.
*
* @param reader
* the reader to an underlying CSV source.
*/
public CSVReader(Reader reader) {
this(reader, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVReader(Reader reader, char separator) {
this(reader, separator, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVReader(Reader reader, char separator, char quotechar) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator, quote char and quote handling
* behavior.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param strictQuotes
* sets if characters outside the quotes are ignored
*/
public CSVReader(Reader reader, char separator, char quotechar, boolean strictQuotes) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, strictQuotes);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
*/
public CSVReader(Reader reader, char separator,
char quotechar, char escape) {
this(reader, separator, quotechar, escape, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, line, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line) {
this(reader, separator, quotechar, escape, line, CSVParser.DEFAULT_STRICT_QUOTES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
* @param strictQuotes
* sets if characters outside the quotes are ignored
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes) {
this(reader, separator, quotechar, escape, line, strictQuotes, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
* @param strictQuotes
* sets if characters outside the quotes are ignored
* @param ignoreLeadingWhiteSpace
* it true, parser should ignore white space before a quote in a field
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) {
this.br = new BufferedReader(reader);
this.parser = new CSVParser(separator, quotechar, escape, strictQuotes, ignoreLeadingWhiteSpace);
this.skipLines = line;
}
/**
* Reads the entire file into a List with each element being a String[] of
* tokens.
*
* @return a List of String[], with each String[] representing a line of the
* file.
*
* @throws IOException
* if bad things happen during the read
*/
public List<String[]> readAll() throws IOException {
List<String[]> allElements = new ArrayList<String[]>();
while (hasNext) {
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null)
allElements.add(nextLineAsTokens);
}
return allElements;
}
/**
* Reads the next line from the buffer and converts to a string array.
*
* @return a string array with each comma-separated element as a separate
* entry.
*
* @throws IOException
* if bad things happen during the read
*/
public String[] readNext() throws IOException {
String[] result = null;
do {
String nextLine = getNextLine();
if (!hasNext) {
return result; // should throw if still pending?
}
String[] r = parser.parseLineMulti(nextLine);
if (r.length > 0) {
if (result == null) {
result = r;
} else {
String[] t = new String[result.length+r.length];
System.arraycopy(result, 0, t, 0, result.length);
System.arraycopy(r, 0, t, result.length, r.length);
result = t;
}
}
} while (parser.isPending());
return result;
}
/**
* Reads the next line from the file.
*
* @return the next line from the file without trailing newline
* @throws IOException
* if bad things happen during the read
*/
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
/**
* Closes the underlying reader.
*
* @throws IOException if the close fails
*/
public void close() throws IOException{
br.close();
}
}
+302
View File
@@ -0,0 +1,302 @@
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package au.com.bytecode.opencsv;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* A very simple CSV writer released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
public class CSVWriter implements Closeable {
public static final int INITIAL_STRING_SIZE = 128;
private Writer rawWriter;
private PrintWriter pw;
private char separator;
private char quotechar;
private char escapechar;
private String lineEnd;
/** The character used for escaping quotes. */
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/** The quote constant to use when you wish to suppress all quoting. */
public static final char NO_QUOTE_CHARACTER = '\u0000';
/** The escape constant to use when you wish to suppress all escaping. */
public static final char NO_ESCAPE_CHARACTER = '\u0000';
/** Default line terminator uses platform encoding. */
public static final String DEFAULT_LINE_END = "\n";
private ResultSetHelper resultService = new ResultSetHelperService();
/**
* Constructs CSVWriter using a comma for the separator.
*
* @param writer
* the writer to an underlying CSV source.
*/
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVWriter with supplied separator.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVWriter(Writer writer, char separator) {
this(writer, separator, DEFAULT_QUOTE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVWriter(Writer writer, char separator, char quotechar) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) {
this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd);
}
/**
* Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
this.rawWriter = writer;
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
/**
* Writes the entire list to a CSV file. The list is assumed to be a
* String[]
*
* @param allLines
* a List of String[], with each String[] representing a line of
* the file.
*/
public void writeAll(List<String[]> allLines) {
for (String[] line : allLines) {
writeNext(line);
}
}
protected void writeColumnNames(ResultSet rs)
throws SQLException {
writeNext(resultService.getColumnNames(rs));
}
/**
* Writes the entire ResultSet to a CSV file.
*
* The caller is responsible for closing the ResultSet.
*
* @param rs the recordset to write
* @param includeColumnNames true if you want column names in the output, false otherwise
*
* @throws java.io.IOException thrown by getColumnValue
* @throws java.sql.SQLException thrown by getColumnValue
*/
public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException {
if (includeColumnNames) {
writeColumnNames(rs);
}
while (rs.next())
{
writeNext(resultService.getColumnValues(rs));
}
}
/**
* Writes the next line to the file.
*
* @param nextLine
* a string array with each comma-separated element as a separate
* entry.
*/
public void writeNext(String[] nextLine) {
if (nextLine == null)
return;
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement);
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
private boolean stringContainsSpecialCharacters(String line) {
return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1;
}
protected StringBuilder processLine(String nextElement)
{
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
return sb;
}
/**
* Flush underlying stream to writer.
*
* @throws IOException if bad things happen
*/
public void flush() throws IOException {
pw.flush();
}
/**
* Close the underlying stream writer flushing any buffered content.
*
* @throws IOException if bad things happen
*
*/
public void close() throws IOException {
flush();
pw.close();
rawWriter.close();
}
/**
* Checks to see if the there has been an error in the printstream.
*/
public boolean checkError() {
return pw.checkError();
}
public void setResultService(ResultSetHelper resultService) {
this.resultService = resultService;
}
}
@@ -0,0 +1,34 @@
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package au.com.bytecode.opencsv;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*
*
*
*
*/
public interface ResultSetHelper {
public String[] getColumnNames(ResultSet rs) throws SQLException;
public String[] getColumnValues(ResultSet rs) throws SQLException, IOException;
}
@@ -0,0 +1,185 @@
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package au.com.bytecode.opencsv;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* helper class for processing JDBC ResultSet objects
*
*
*/
public class ResultSetHelperService implements ResultSetHelper {
public static final int CLOBBUFFERSIZE = 2048;
// note: we want to maintain compatibility with Java 5 VM's
// These types don't exist in Java 5
private static final int NVARCHAR = -9;
private static final int NCHAR = -15;
private static final int LONGNVARCHAR = -16;
private static final int NCLOB = 2011;
public String[] getColumnNames(ResultSet rs) throws SQLException {
List<String> names = new ArrayList<String>();
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
names.add(metadata.getColumnName(i+1));
}
String[] nameArray = new String[names.size()];
return names.toArray(nameArray);
}
public String[] getColumnValues(ResultSet rs) throws SQLException, IOException {
List<String> values = new ArrayList<String>();
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
values.add(getColumnValue(rs, metadata.getColumnType(i + 1), i + 1));
}
String[] valueArray = new String[values.size()];
return values.toArray(valueArray);
}
private String handleObject(Object obj){
return obj == null ? "" : String.valueOf(obj);
}
private String handleBigDecimal(BigDecimal decimal) {
return decimal == null ? "" : decimal.toString();
}
private String handleLong(ResultSet rs, int columnIndex) throws SQLException {
long lv = rs.getLong(columnIndex);
return rs.wasNull() ? "" : Long.toString(lv);
}
private String handleInteger(ResultSet rs, int columnIndex) throws SQLException {
int i = rs.getInt(columnIndex);
return rs.wasNull() ? "" : Integer.toString(i);
}
private String handleDate(ResultSet rs, int columnIndex) throws SQLException {
java.sql.Date date = rs.getDate(columnIndex);
String value = null;
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
value = dateFormat.format(date);
}
return value;
}
private String handleTime(Time time) {
return time == null ? null : time.toString();
}
private String handleTimestamp(Timestamp timestamp) {
SimpleDateFormat timeFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
return timestamp == null ? null : timeFormat.format(timestamp);
}
private String getColumnValue(ResultSet rs, int colType, int colIndex)
throws SQLException, IOException {
String value = "";
switch (colType)
{
case Types.BIT:
case Types.JAVA_OBJECT:
value = handleObject(rs.getObject(colIndex));
break;
case Types.BOOLEAN:
boolean b = rs.getBoolean(colIndex);
value = Boolean.valueOf(b).toString();
break;
case NCLOB: // todo : use rs.getNClob
case Types.CLOB:
Clob c = rs.getClob(colIndex);
if (c != null) {
value = read(c);
}
break;
case Types.BIGINT:
value = handleLong(rs, colIndex);
break;
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.REAL:
case Types.NUMERIC:
value = handleBigDecimal(rs.getBigDecimal(colIndex));
break;
case Types.INTEGER:
case Types.TINYINT:
case Types.SMALLINT:
value = handleInteger(rs, colIndex);
break;
case Types.DATE:
value = handleDate(rs, colIndex);
break;
case Types.TIME:
value = handleTime(rs.getTime(colIndex));
break;
case Types.TIMESTAMP:
value = handleTimestamp(rs.getTimestamp(colIndex));
break;
case NVARCHAR: // todo : use rs.getNString
case NCHAR: // todo : use rs.getNString
case LONGNVARCHAR: // todo : use rs.getNString
case Types.LONGVARCHAR:
case Types.VARCHAR:
case Types.CHAR:
value = rs.getString(colIndex);
break;
default:
value = "";
}
if (value == null)
{
value = "";
}
return value;
}
private static String read(Clob c) throws SQLException, IOException
{
StringBuilder sb = new StringBuilder( (int) c.length());
Reader r = c.getCharacterStream();
char[] cbuf = new char[CLOBBUFFERSIZE];
int n;
while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
sb.append(cbuf, 0, n);
}
return sb.toString();
}
}
@@ -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();
}
}
+88
View File
@@ -0,0 +1,88 @@
// $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();
@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();
}
}
@@ -0,0 +1,301 @@
// $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.Map;
import java.util.HashMap;
import java.util.List;
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 abstract class Blacklist {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* List of entries by block ID.
*/
private Map<Integer,List<BlacklistEntry>> blacklist
= new HashMap<Integer,List<BlacklistEntry>>();
/**
* Logger.
*/
private BlacklistLogger blacklistLogger = new BlacklistLogger();
/**
* Last event.
*/
private BlacklistEvent lastEvent;
/**
* Used to prevent flooding.
*/
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
/**
* Returns whether the list is empty.
*
* @return
*/
public boolean isEmpty() {
return blacklist.isEmpty();
}
/**
* Get the entries for an item or list.
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
}
/**
* Get the logger.
*
* @return
*/
public BlacklistLogger getLogger() {
return blacklistLogger;
}
/**
* Method to handle the event.
*
* @param event
* @param forceRepeat
* @param silent
* @return
*/
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.check(event, forceRepeat, silent)) {
ret = false;
}
}
return ret;
}
/**
* Load the blacklist.
*
* @param file
* @return
* @throws IOException
*/
public void load(File file) throws IOException {
FileReader input = null;
Map<Integer,List<BlacklistEntry>> blacklist =
new HashMap<Integer,List<BlacklistEntry>>();
try {
input = new FileReader(file);
BufferedReader buff = new BufferedReader(input);
String line;
List<BlacklistEntry> currentEntries = null;
while ((line = buff.readLine()) != null) {
line = line.trim();
// Blank line
if (line.length() == 0) {
continue;
} else if (line.charAt(0) == ';' || line.charAt(0) == '#') {
continue;
}
if (line.matches("^\\[.*\\]$")) {
String[] items = line.substring(1, line.length() - 1).split(",");
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
+ item);
break;
}
}
BlacklistEntry entry = new BlacklistEntry(this);
if (blacklist.containsKey(id)) {
blacklist.get(id).add(entry);
} else {
List<BlacklistEntry> entries = new ArrayList<BlacklistEntry>();
entries.add(entry);
blacklist.put(id, entries);
}
currentEntries.add(entry);
}
} else if (currentEntries != null) {
String[] parts = line.split("=");
if (parts.length == 1) {
logger.log(Level.WARNING, "Found option with no value "
+ file.getName() + " for '" + line + "'");
continue;
}
boolean unknownOption = false;
for (BlacklistEntry entry : currentEntries) {
if (parts[0].equalsIgnoreCase("ignore-groups")) {
entry.setIgnoreGroups(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-break")) {
entry.setBreakActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-destroy-with")) {
entry.setDestroyWithActions(parts[1].split(","));
} 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")) {
entry.setAcquireActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("message")) {
entry.setMessage(parts[1].trim());
} else if (parts[0].equalsIgnoreCase("comment")) {
entry.setComment(parts[1].trim());
} else {
unknownOption = true;
}
}
if (unknownOption) {
logger.log(Level.WARNING, "Unknown option '" + parts[0]
+ "' in " + file.getName() + " for '" + line + "'");
}
} else {
logger.log(Level.WARNING, "Found option with no heading "
+ file.getName() + " for '" + line + "'");
}
}
this.blacklist = blacklist;
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e2) {
}
}
}
/**
* Get the last event.
*
* @return
*/
public BlacklistEvent getLastEvent() {
return lastEvent;
}
/**
* Notify administrators.
*
* @param event
*/
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.
*
* @param player
*/
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,381 @@
// $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;
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()]);
}
/**
* @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[] 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
*/
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) {
return false;
}
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
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 event
* @param forceRepeat
* @param silent
* @return
*/
public boolean check(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 = true;
// Nothing to do
if (actions == null) {
return true;
}
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// 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,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;
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.
*
* @param handler
*/
public void clearHandlers() {
handlers.clear();
}
/**
* Log an event.
*
* @param player
* @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,31 +17,32 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard;
package com.sk89q.worldguard.blacklist;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
* 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();
public class BlacklistTrackedEvent {
private BlacklistEvent event;
private long time;
text.append("[");
text.append(dateFormat.format(new Date(record.getMillis())));
text.append("] ");
text.append(record.getMessage());
text.append("\r\n");
return text.toString();
/**
* Construct the object.
*
* @param id
* @param time
*/
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
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,38 @@
// $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
*/
public String getDescription() {
return "break";
}
}
@@ -0,0 +1,38 @@
// $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
*/
public String getDescription() {
return "interact with";
}
}
@@ -0,0 +1,38 @@
// $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
*/
public String getDescription() {
return "place";
}
}
@@ -0,0 +1,38 @@
// $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
*/
public String getDescription() {
return "destroy with";
}
}
@@ -0,0 +1,38 @@
// $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
*/
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,38 @@
// $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
*/
public String getDescription() {
return "drop";
}
}
@@ -0,0 +1,38 @@
// $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
*/
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,119 @@
// $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");
/**
* Log an event.
*
* @param player
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "WorldGuard: " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "WorldGuard: " + 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,198 @@
// $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;
/**
* 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, LocalPlayer player, Vector pos, 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, player.getName());
stmt.setInt(3, pos.getBlockX());
stmt.setInt(4, pos.getBlockY());
stmt.setInt(5, pos.getBlockZ());
stmt.setInt(6, item);
stmt.setInt(7, (int)(System.currentTimeMillis() / 1000));
stmt.setString(8, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
+ e.getMessage());
}
}
/**
* Log an event.
*
* @param player
* @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) {
}
}
}
@@ -0,0 +1,300 @@
// $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.io.*;
import java.util.regex.*;
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.*;
/**
*
* @author sk89q
*/
public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Regex for patterns in the path.
*/
private static Pattern pattern = Pattern.compile("%.");
/**
* Date format.
*/
private static SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyyy-MM-dd HH:mm:ss");
/**
* Number of files to keep open at a time.
*/
private int cacheSize = 10;
/**
* Path pattern.
*/
private String pathPattern;
/**
* Cache of writers.
*/
private TreeMap<String,FileLoggerWriter> writers =
new TreeMap<String,FileLoggerWriter>();
/**
* Construct the object.
*
* @param pathPattern
*/
public FileLoggerHandler(String pathPattern) {
this.pathPattern = pathPattern;
}
/**
* Construct the object.
*
* @param pathPattern
* @param cacheSize
*/
public FileLoggerHandler(String pathPattern, int cacheSize) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
this.pathPattern = pathPattern;
this.cacheSize = cacheSize;
}
/**
* Build the path.
*
* @return
*/
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
Matcher m = pattern.matcher(pathPattern);
StringBuffer buffer = new StringBuffer();
// Pattern replacements
while (m.find()) {
String group = m.group();
String rep = "?";
if (group.matches("%%")) {
rep = "%";
} else if (group.matches("%u")) {
rep = playerName.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));
} else if (group.matches("%m")) {
rep = String.format("%02d", calendar.get(Calendar.MONTH));
} else if (group.matches("%d")) {
rep = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH));
} else if (group.matches("%W")) {
rep = String.format("%02d", calendar.get(Calendar.WEEK_OF_YEAR));
} else if (group.matches("%H")) {
rep = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
} else if (group.matches("%h")) {
rep = String.format("%02d", calendar.get(Calendar.HOUR));
} else if (group.matches("%i")) {
rep = String.format("%02d", calendar.get(Calendar.MINUTE));
} else if (group.matches("%s")) {
rep = String.format("%02d", calendar.get(Calendar.SECOND));
}
m.appendReplacement(buffer, rep);
}
m.appendTail(buffer);
return buffer.toString();
}
/**
* Log a message.
*
* @param player
* @param message
*/
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
try {
String date = dateFormat.format(new Date());
String line = "[" + date + "] " + player.getName() + ": " + message
+ (comment != null ? " (" + comment + ")" : "") + "\r\n";
FileLoggerWriter writer = writers.get(path);
// Writer already exists!
if (writer != null) {
try {
BufferedWriter out = writer.getWriter();
out.write(line);
out.flush();
writer.updateLastUse();
return;
} catch (IOException e) {
// Failed initial rewrite... let's re-open
}
}
// Make parent directory
File file = new File(path);
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
FileWriter stream = new FileWriter(path, true);
BufferedWriter out = new BufferedWriter(stream);
out.write(line);
out.flush();
writer = new FileLoggerWriter(path, out);
writers.put(path, writer);
// Check to make sure our cache doesn't get too big!
if (writers.size() > cacheSize) {
Iterator<Map.Entry<String,FileLoggerWriter>> it =
writers.entrySet().iterator();
// Remove some entries
for (; it.hasNext(); ) {
Map.Entry<String,FileLoggerWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
}
it.remove();
// Trimmed enough
if (writers.size() <= cacheSize) {
break;
}
}
}
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to log blacklist event to '"
+ path + "': " + e.getMessage());
}
}
/**
* Gets the coordinates in text form for the log.
*
* @param pos
* @return
*/
private String getCoordinates(Vector pos) {
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
private void logEvent(BlacklistEvent event, String text, int id, Vector pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + getFriendlyItemName(id)
+ " " + getCoordinates(pos), comment);
}
/**
* Log an event.
*
* @param player
* @param event
*/
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);
}
}
/**
* 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 handles.
*/
public void close() {
for (Map.Entry<String,FileLoggerWriter> entry : writers.entrySet()) {
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
}
}
writers.clear();
}
}
@@ -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.blacklist.loggers;
import java.io.*;
/**
*
* @author sk89q
*/
public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Path.
*/
public String path;
/**
* Writer.
*/
private BufferedWriter writer;
/**
* Last use.
*/
private long lastUse;
/**
* Construct the object.
*
* @param writer
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
this.path = path;
this.writer = writer;
lastUse = System.currentTimeMillis();
}
/**
* File path.
*
* @return
*/
public String getPath() {
return path;
}
/**
* @return the writer
*/
public BufferedWriter getWriter() {
return writer;
}
/**
* @return the lastUse
*/
public long getLastUse() {
return lastUse;
}
/**
* Update last use time.
*
* @return
*/
public void updateLastUse() {
lastUse = System.currentTimeMillis();
}
/**
* Comparison function.
*
* @param other
* @return
*/
public int compareTo(FileLoggerWriter other) {
if (lastUse > other.lastUse) {
return 1;
} else if (lastUse < other.lastUse) {
return -1;
} else {
return 0;
}
}
}
@@ -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;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.blacklist.Blacklist;
public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void broadcastNotification(String msg) {
for (Player player : plugin.getServer().getOnlinePlayers()) {
if (plugin.hasPermission(player, "/worldguardnotify")) {
player.sendMessage(msg);
}
}
}
}
@@ -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.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);
}
}
@@ -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.bukkit;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.Location;
import org.bukkit.Server;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
public class BukkitUtil {
private BukkitUtil() {
}
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
}
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
return null;
}
return players.get(0);
}
}
@@ -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.bukkit;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/**
* Sends all logger messages to a player.
*
* @author sk89q
*/
public class LoggerToChatHandler extends Handler {
/**
* Player.
*/
private Player player;
/**
* Construct the object.
*
* @param player
*/
public LoggerToChatHandler(Player player) {
this.player = player;
}
/**
* Close the handler.
*/
public void close() {
}
/**
* Flush the output.
*/
public void flush() {
}
/**
* Publish a log record.
*/
public void publish(LogRecord record) {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.WHITE + record.getMessage());
}
}
@@ -0,0 +1,476 @@
// $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.Iterator;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.block.BlockDamageLevel;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.World;
import org.bukkit.event.block.*;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.*;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
public class WorldGuardBlockListener extends BlockListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Called when a block is damaged (or broken)
*
* @param event Relevant event details
*/
@Override
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
if (!plugin.itemDurability && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
ItemStack held = player.getItemInHand();
if (held.getTypeId() > 0) {
held.setDurability((short) -1);
player.setItemInHand(held);
}
}
if (plugin.useRegions && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Vector pt = BukkitUtil.toVector(event.getBlock());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (plugin.blacklist != null && event.getDamageLevel() == BlockDamageLevel.BROKEN) {
if (!plugin.blacklist.check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
event.getBlock().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
if (!plugin.blacklist.check(
new DestroyWithBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
player.getItemInHand().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a block flows (water/lava)
*
* @param event Relevant event details
*/
@Override
public void onBlockFlow(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
if (plugin.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -plugin.spongeRadius; cx <= plugin.spongeRadius; cx++) {
for (int cy = -plugin.spongeRadius; cy <= plugin.spongeRadius; cy++) {
for (int cz = -plugin.spongeRadius; cz <= plugin.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& (!plugin.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;
}
}*/
if (plugin.preventWaterDamage.size() > 0 && isWater) {
int targetId = world.getBlockTypeIdAt(
blockTo.getX(), blockTo.getY(), blockTo.getZ());
if (plugin.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (plugin.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = world.getBlockTypeIdAt(
blockTo.getX(), blockTo.getY() - 1, blockTo.getZ());
if (!plugin.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a block gets ignited
*
* @param event Relevant event details
*/
@Override
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
//Player player = event.getPlayer();
World world = block.getWorld();
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (plugin.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (plugin.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (plugin.blockLighter && cause == IgniteCause.FLINT_AND_STEEL) {
event.setCancelled(true);
return;
}
if (plugin.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (plugin.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| plugin.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
event.setCancelled(true);
return;
}
}
/*if (plugin.useRegions) {
Vector pt = toVector(block);
if (player != null && !plugin.hasPermission(player, "/regionbypass")) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (cause == IgniteCause.FLINT_AND_STEEL
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FLINT_AND_STEEL
&& !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LIGHTER)) {
event.setCancelled(true);
return;
}
}
f (isFireSpread && !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.LAVA && !plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LAVA_FIRE)) {
event.setCancelled(true);
return;
}
}*/
}
/**
* Called when a block is destroyed from burning
*
* @param event Relevant event details
*/
public void onBlockBurn(BlockBurnEvent event) {
if (plugin.disableFireSpread) {
event.setCancelled(true);
return;
}
if (plugin.fireSpreadDisableToggle) {
event.setCancelled(true);
return;
}
if (plugin.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (plugin.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when block physics occurs
*
* @param event Relevant event details
*/
@Override
public void onBlockPhysics(BlockPhysicsEvent event) {
int id = event.getChangedTypeId();
if (id == 13 && plugin.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && plugin.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && plugin.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
}
/**
* Called when a block is interacted with
*
* @param event Relevant event details
*/
public void onBlockInteract(BlockInteractEvent event) {
Block block = event.getBlock();
LivingEntity entity = event.getEntity();
if (entity instanceof Player
&& (block.getType() == Material.CHEST
|| block.getType() == Material.DISPENSER
|| block.getType() == Material.FURNACE
|| block.getType() == Material.BURNING_FURNACE
|| block.getType() == Material.NOTE_BLOCK)) {
Player player = (Player)entity;
if (plugin.useRegions) {
Vector pt = toVector(block);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).allowsFlag(AreaFlags.FLAG_CHEST_ACCESS)
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
if (plugin.blacklist != null && entity instanceof Player) {
Player player = (Player)entity;
if (!plugin.blacklist.check(
new BlockInteractBlacklistEvent(plugin.wrapPlayer(player), toVector(block),
block.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a player places a block
*
* @param event Relevant event details
*/
@Override
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
if (plugin.useRegions) {
Vector pt = toVector(blockPlaced);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (plugin.blacklist != null) {
if (!plugin.blacklist.check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(blockPlaced),
blockPlaced.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (plugin.simulateSponge && blockPlaced.getTypeId() == 19) {
if (plugin.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
return;
}
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
clearSpongeWater(world, ox, oy, oz);
}
}
/**
* Called when a player right clicks a block
*
* @param event Relevant event details
*/
@Override
public void onBlockRightClick(BlockRightClickEvent event) {
Player player = event.getPlayer();
if (plugin.useRegions && event.getItemInHand().getTypeId() == plugin.regionWand) {
Vector pt = toVector(event.getBlock());
ApplicableRegionSet app = plugin.regionManager.getApplicableRegions(pt);
List<String> regions = plugin.regionManager.getApplicableRegionsIDs(pt);
if (regions.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (app.canBuild(plugin.wrapPlayer(player)) ? "Yes" : "No"));
StringBuilder str = new StringBuilder();
for (Iterator<String> it = regions.iterator(); it.hasNext(); ) {
str.append(it.next());
if (it.hasNext()) {
str.append(", ");
}
}
player.sendMessage(ChatColor.YELLOW + "Applicable regions: " + str.toString());
} else {
player.sendMessage(ChatColor.YELLOW + "WorldGuard: No defined regions here!");
}
}
}
/**
* Called when redstone changes
* From: the source of the redstone change
* To: The redstone dust that changed
*
* @param event Relevant event details
*/
@Override
public void onBlockRedstoneChange(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockTo = event.getToBlock();
if (plugin.simulateSponge && plugin.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()) {
clearSpongeWater(world, ox + cx, oy + cy, oz + cz);
}
}
}
}
return;
}
}
/**
* Remove water around a sponge.
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void clearSpongeWater(World world, int ox, int oy, int oz) {
for (int cx = -plugin.spongeRadius; cx <= plugin.spongeRadius; cx++) {
for (int cy = -plugin.spongeRadius; cy <= plugin.spongeRadius; cy++) {
for (int cz = -plugin.spongeRadius; cz <= plugin.spongeRadius; cz++) {
Block block = world.getBlockAt(ox + cx, oy + cy, oz + cz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
world.getBlockAt(ox + cx, oy + cy, oz + cz)
.setTypeId(0);
}
}
}
}
}
}
@@ -0,0 +1,285 @@
// $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.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
public class WorldGuardEntityListener extends EntityListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Override
public void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
event.setCancelled(true);
return;
}
if (plugin.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
return;
}
if (plugin.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
}
}
@Override
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (plugin.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_PVP)) {
((Player)attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Monster) {
if (attacker instanceof Creeper && plugin.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (plugin.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
public void onEntityDamageByProjectile(EntityDamageByProjectileEvent event) {
Entity defender = event.getEntity();
Entity attacker = event.getDamager();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (plugin.useRegions) {
Vector pt = toVector(defender.getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_PVP)) {
((Player)attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
return;
}
}
}
}
}
public void onEntityDamage(EntityDamageEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
if (defender instanceof Player) {
Player player = (Player)defender;
if (plugin.invinciblePlayers.contains(player.getName())) {
event.setCancelled(true);
return;
}
if (plugin.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (plugin.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (plugin.disableDrowningDamage && type == DamageCause.DROWNING) {
event.setCancelled(true);
return;
}
if (plugin.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
findFreePosition(player);
event.setCancelled(true);
return;
}
if (plugin.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
if (type == DamageCause.DROWNING
&& plugin.amphibiousPlayers.contains(player.getName())) {
event.setCancelled(true);
return;
}
}
}
@Override
public void onEntityExplode(EntityExplodeEvent event) {
if (event.getEntity() instanceof LivingEntity) {
if (plugin.blockCreeperBlockDamage) {
event.setCancelled(true);
return;
}
if (plugin.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (plugin.useRegions) {
Vector pt = toVector(event.getEntity().getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_CREEPER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
} else { // Shall assume that this is TNT
if (plugin.blockTNT) {
event.setCancelled(true);
return;
}
if (plugin.useRegions && event.getEntity() != null) {
Vector pt = toVector(event.getEntity().getLocation());
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_TNT)) {
event.setCancelled(true);
return;
}
}
}
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
* a series of two free blocks. The player will be teleported to
* that free position.
*
* @param player
*/
public 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) {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
player.teleportTo(loc);
}
return;
}
y++;
}
}
}
@@ -0,0 +1,161 @@
// $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.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.*;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.AreaFlags;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
/**
* Handles all events thrown in relation to a Player
*/
public class WorldGuardPlayerListener extends PlayerListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Called when a player joins a server
*
* @param event Relevant event details
*/
@Override
public void onPlayerJoin(PlayerEvent event) {
Player player = event.getPlayer();
if (plugin.fireSpreadDisableToggle) {
player.sendMessage(ChatColor.YELLOW
+ "Fire spread is currently globally disabled.");
}
if (plugin.inGroup(player, "wg-invincible")) {
plugin.invinciblePlayers.add(player.getName());
}
if (plugin.inGroup(player, "wg-amphibious")) {
plugin.amphibiousPlayers.add(player.getName());
}
}
/**
* Called when a player leaves a server
*
* @param event Relevant event details
*/
@Override
public void onPlayerQuit(PlayerEvent event) {
Player player = event.getPlayer();
plugin.invinciblePlayers.remove(player.getName());
plugin.amphibiousPlayers.remove(player.getName());
if (plugin.blacklist != null) {
plugin.blacklist.forgetPlayer(plugin.wrapPlayer(player));
}
}
/**
* Called when a player uses an item
*
* @param event Relevant event details
*/
@Override
public void onPlayerItem(PlayerItemEvent event) {
Player player = event.getPlayer();
Block block = event.getBlockClicked();
ItemStack item = event.getItem();
if (!plugin.itemDurability) {
// Hoes
if (item.getTypeId() >= 290 && item.getTypeId() <= 294) {
item.setDurability((byte)-1);
player.setItemInHand(item);
}
}
if (plugin.useRegions && !event.isBlock() && block != null) {
Vector pt = toVector(block.getRelative(event.getBlockFace()));
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.hasPermission(player, "/regionbypass")
&& !plugin.regionManager.getApplicableRegions(pt).canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED
+ "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
if (plugin.blacklist != null && item != null && block != null) {
if (!plugin.blacklist.check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(block.getRelative(event.getBlockFace())),
item.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (plugin.useRegions && item != null && block != null && item.getTypeId() == 259) {
Vector pt = toVector(block.getRelative(event.getBlockFace()));
if (!plugin.regionManager.getApplicableRegions(pt)
.allowsFlag(AreaFlags.FLAG_LIGHTER)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a player attempts to log in to the server
*
* @param event Relevant event details
*/
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
if (plugin.enforceOneSession) {
String name = player.getName();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (pl.getName().equalsIgnoreCase(name)) {
pl.kickPlayer("Logged in from another location.");
}
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -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();
}
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,183 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedMap;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.AreaFlags.State;
/**
* Represents a set of regions and their rules as applied to one point.
*
* @author sk89q
*/
public class ApplicableRegionSet {
private GlobalFlags global;
private Vector pt;
private SortedMap<String,ProtectedRegion> regions;
/**
* Construct the object.
*
* @param pt
* @param regions
* @param global
*/
public ApplicableRegionSet(Vector pt, SortedMap<String,ProtectedRegion> regions,
GlobalFlags global) {
this.pt = pt;
this.regions = regions;
this.global = global;
}
/**
* Checks if a player can build in an area.
*
* @param player
* @return
*/
public boolean canBuild(LocalPlayer player) {
return isFlagAllowed(AreaFlags.FLAG_BUILD, global.canBuild, player);
}
/**
* Checks a flag.
*
* @param player
* @return
*/
public boolean allowsFlag(String flag) {
boolean def = true;
if (flag.equals(AreaFlags.FLAG_CHEST_ACCESS)) {
def = global.canAccessChests;
} else if (flag.equals(AreaFlags.FLAG_PVP)) {
def = global.canPvP;
}
return isFlagAllowed(flag, def, null);
}
/**
* Checks to see if a flag is permitted.
*
* @param def default state if there are no regions defined
* @param player null to not check owners and members
* @return
*/
private boolean isFlagAllowed(String flag, boolean def, LocalPlayer player) {
boolean found = false;
boolean allowed = false; // Used for ALLOW override
if (player == null) {
allowed = def;
}
int lastPriority = 0;
// 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>();
for (ProtectedRegion region : regions.values()) {
// Ignore non-build regions
if (player != null && region.getFlags().get(AreaFlags.FLAG_PASSTHROUGH) == State.ALLOW) {
continue;
}
// Forget about regions that are not covered
if (!region.contains(pt)) {
continue;
}
// Allow DENY to override everything
if (region.getFlags().get(flag) == State.DENY) {
return false;
}
// Forget about regions that allow it, although make sure the
// default state is now to allow
if (region.getFlags().get(flag) == State.ALLOW) {
allowed = true;
found = true;
continue;
}
// Ignore lower priority regions
if (found && region.getPriority() < lastPriority) {
break;
}
if (player != null) {
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;
lastPriority = region.getPriority();
}
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();
}
}
}
@@ -0,0 +1,145 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Holds the flags for a region.
*
* @author sk89q
*/
public class AreaFlags {
public enum State {
NONE,
ALLOW,
DENY,
};
public static final String FLAG_PASSTHROUGH = "z";
public static final String FLAG_BUILD = "b";
public static final String FLAG_PVP = "p";
public static final String FLAG_MOB_DAMAGE = "m";
public static final String FLAG_CREEPER_EXPLOSION = "c";
public static final String FLAG_TNT = "t";
public static final String FLAG_LIGHTER = "l";
public static final String FLAG_FIRE_SPREAD = "f";
public static final String FLAG_LAVA_FIRE = "F";
public static final String FLAG_CHEST_ACCESS = "C";
/**
* Get the user-friendly name of a flag. If a name isn't known, then
* the flag is returned unchanged.
*
* @param flag
* @return
*/
public static String getFlagName(String flag) {
if (flag.equals(FLAG_PASSTHROUGH)) {
return "passthrough";
} else if (flag.equals(FLAG_BUILD)) {
return "build";
} else if (flag.equals(FLAG_PVP)) {
return "PvP";
} else if (flag.equals(FLAG_MOB_DAMAGE)) {
return "mob damage";
} else if (flag.equals(FLAG_CREEPER_EXPLOSION)) {
return "creeper explosion";
} else if (flag.equals(FLAG_TNT)) {
return "TNT";
} else if (flag.equals(FLAG_LIGHTER)) {
return "lighter";
} else if (flag.equals(FLAG_FIRE_SPREAD)) {
return "fire spread";
} else if (flag.equals(FLAG_LAVA_FIRE)) {
return "lava fire spread";
} else if (flag.equals(FLAG_CHEST_ACCESS)) {
return "chest access";
} else {
return flag;
}
}
/**
* Gets a flag from an alias. May return null.
*
* @param name
* @return
*/
public static String fromAlias(String name) {
if (name.equalsIgnoreCase("passthrough")) {
return FLAG_PASSTHROUGH;
} else if (name.equalsIgnoreCase("build")) {
return FLAG_BUILD;
} else if (name.equalsIgnoreCase("pvp")) {
return FLAG_PVP;
} else if (name.equalsIgnoreCase("mobdamage")) {
return FLAG_MOB_DAMAGE;
} else if (name.equalsIgnoreCase("creeper")) {
return FLAG_CREEPER_EXPLOSION;
} else if (name.equalsIgnoreCase("tnt")) {
return FLAG_TNT;
} else if (name.equalsIgnoreCase("lighter")) {
return FLAG_LIGHTER;
} else if (name.equalsIgnoreCase("firespread")) {
return FLAG_FIRE_SPREAD;
} else if (name.equalsIgnoreCase("lavafirespread")) {
return FLAG_LAVA_FIRE;
} else if (name.equalsIgnoreCase("chest")) {
return FLAG_CHEST_ACCESS;
} else {
return null;
}
}
private Map<String, State> states = new HashMap<String, State>();
public State get(String flag) {
State state = states.get(flag);
if (state == null) {
return State.NONE;
}
return state;
}
public void set(String flag, State state) {
if (state == State.NONE) {
states.remove(flag);
} else {
states.put(flag, state);
}
}
public Set<Map.Entry<String, State>> entrySet() {
return states.entrySet();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AreaFlags)) {
return false;
}
AreaFlags other = (AreaFlags)obj;
return other.states.equals(this);
}
}
@@ -0,0 +1,414 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.HashMap;
import java.util.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 au.com.bytecode.opencsv.CSVWriter;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
import com.sk89q.worldguard.protection.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.util.ArrayReader;
/**
* Represents a protected area database that uses CSV files.
*
* @author sk89q
*/
public class CSVDatabase implements ProtectionDatabase {
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.
*/
@Override
public void save() throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(file));
try {
for (Map.Entry<String,ProtectedRegion> entry : regions.entrySet()) {
String id = entry.getKey();
ProtectedRegion region = entry.getValue();
if (!(region instanceof ProtectedCuboidRegion)) {
logger.warning("The CSV database only supports cuboid regions.");
continue;
}
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion)region;
BlockVector min = cuboid.getMinimumPoint();
BlockVector max = cuboid.getMaximumPoint();
writer.writeNext(new String[] {
id,
"cuboid.2",
String.valueOf(min.getBlockX()),
String.valueOf(min.getBlockY()),
String.valueOf(min.getBlockZ()),
String.valueOf(max.getBlockX()),
String.valueOf(max.getBlockY()),
String.valueOf(max.getBlockZ()),
String.valueOf(cuboid.getPriority()),
cuboid.getParent() != null ? cuboid.getParent().getId() : "",
writeDomains(cuboid.getOwners()),
writeDomains(cuboid.getMembers()),
writeFlags(cuboid.getFlags()),
cuboid.getEnterMessage() != null ? cuboid.getEnterMessage() : "",
cuboid.getLeaveMessage() != null ? cuboid.getLeaveMessage() : "",
});
}
} finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
/**
* Load the database from file.
*/
@Override
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();
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);
region.setFlags(parseFlags(flagsData));
region.setOwners(this.parseDomains(ownersData));
region.setEnterMessage(enterMessage);
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);
region.setFlags(parseFlags(flagsData));
region.setOwners(this.parseDomains(ownersData));
region.setMembers(this.parseDomains(membersData));
region.setEnterMessage(enterMessage);
region.setLeaveMessage(leaveMessage);
regions.put(id, region);
// Link children to parents later
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;
}
/**
* Load the list of regions into a region manager.
*
* @throws IOException
*/
public void load(RegionManager manager) throws IOException {
load();
manager.setRegions(regions);
}
/**
* Save the list of regions from a region manager.
*
* @throws IOException
*/
public void save(RegionManager manager) throws IOException {
regions = manager.getRegions();
save();
}
/**
* Used to parse the specified domain in the CSV file.
*
* @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
* @return
*/
private AreaFlags parseFlags(String data) {
if (data == null) {
return new AreaFlags();
}
AreaFlags flags = new AreaFlags();
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 flag;
if (k == '_') {
if (i == data.length() - 1) {
logger.warning("_ read ahead fail");
break;
}
flag = "_" + data.charAt(i + 1);
i++;
} else {
flag = String.valueOf(k);
}
flags.set(flag, curState);
}
}
return flags;
}
/**
* 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
*/
private String nullEmptyString(String str) {
if (str == null) {
return null;
} else if (str.length() == 0) {
return null;
} else {
return str;
}
}
/**
* Used to write the list of flags.
*
* @param flags
* @return
*/
private String writeFlags(AreaFlags flags) {
StringBuilder str = new StringBuilder();
for (Map.Entry<String, State> entry : flags.entrySet()) {
str.append(writeFlag(entry.getValue(), entry.getKey()));
}
return str.toString();
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Get a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = regions;
}
}
@@ -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.protection;
import java.util.Comparator;
class DescendingPriorityComparator implements Comparator<ProtectedRegion> {
/**
* Compares two regions.
*
* @param other
* @return
*/
public int compare(ProtectedRegion r1, ProtectedRegion r2) {
if (r1.getPriority() == r2.getPriority()) {
return 0;
} else if (r1.getPriority() > r2.getPriority()) {
return -1;
} else {
return 1;
}
}
}
@@ -0,0 +1,183 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* A very simple implementation of the region manager that uses a flat list
* and iterates through the list to identify applicable regions. This method
* is not very efficient.
*
* @author sk89q
*/
public class FlatRegionManager implements RegionManager {
/**
* List of protected regions.
*/
private SortedMap<String,ProtectedRegion> regions;
/**
* Global flags.
*/
private GlobalFlags global;
/**
* Construct the manager.
*/
public FlatRegionManager(GlobalFlags global) {
regions = new TreeMap<String,ProtectedRegion>();
this.global = global;
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = new TreeMap<String,ProtectedRegion>(regions);
}
/**
* Adds a region.
*
* @param id
* @param region
*/
public void addRegion(ProtectedRegion region) {
regions.put(region.getId(), region);
}
/**
* Removes a region and its children.
*
* @param id
*/
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id);
regions.remove(id);
if (region != null) {
for (Map.Entry<String, ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().getParent() == region) {
removeRegion(entry.getKey());
}
}
}
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
public boolean hasRegion(String id) {
return regions.containsKey(id);
}
/**
* Get a region by its ID.
*
* @param id
*/
public ProtectedRegion getRegion(String id) {
return regions.get(id);
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
public ApplicableRegionSet getApplicableRegions(Vector pt) {
return new ApplicableRegionSet(pt, regions, global);
}
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
for (Map.Entry<String,ProtectedRegion> entry : regions.entrySet()) {
if (entry.getValue().contains(pt)) {
applicable.add(entry.getKey());
}
}
return applicable;
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param region
* @param player
* @return
*/
public boolean overlapsUnownedRegion(ProtectedRegion region, LocalPlayer player) {
for (ProtectedRegion other : regions.values()) {
if (other.getOwners().contains(player)) {
continue;
}
try {
if (ProtectedRegion.intersects(region, other)) {
return true;
}
} catch (UnsupportedIntersectionException e) {
// TODO: Maybe do something here
}
}
return false;
}
/**
* Get the number of regions.
*
* @return
*/
public int size() {
return regions.size();
}
}
@@ -0,0 +1,31 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
/**
* Used for default flags.
*
* @author sk89q
*/
public class GlobalFlags {
public boolean canBuild = true;
public boolean canAccessChests = false;
public boolean canPvP = true;
}
@@ -0,0 +1,110 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import com.sk89q.worldedit.*;
/**
* Represents a cuboid region that can be protected.
*
* @author sk89q
*/
public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Store the first point.
*/
private BlockVector min;
/**
* Store the second point.
*/
private BlockVector max;
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param pos1
* @param pos2
* @param priority
*/
public ProtectedCuboidRegion(String id, BlockVector min, BlockVector max) {
super(id);
this.min = min;
this.max = max;
}
/**
* Get the lower point of the cuboid.
*
* @return min point
*/
public BlockVector getMinimumPoint() {
return min;
}
/**
* Set the lower point of the cuboid.
*
* @param pt
*/
public void setMinimumPoint(BlockVector pt) {
min = pt;
}
/**
* Get the upper point of the cuboid.
*
* @return max point
*/
public BlockVector getMaximumPoint() {
return max;
}
/**
* Set the upper point of the cuboid.
*
* @param pt
*/
public void setMaximumPoint(BlockVector pt) {
max = pt;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
int x = pt.getBlockX();
int y = pt.getBlockY();
int z = pt.getBlockZ();
return x >= min.getBlockX() && x <= max.getBlockX()
&& y >= min.getBlockY() && y <= max.getBlockY()
&& z >= min.getBlockZ() && z <= max.getBlockZ();
}
/**
* Return the type of region as a user-friendly name.
*
* @return type of region
*/
public String getTypeName() {
return "cuboid";
}
}
@@ -0,0 +1,320 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
/**
* Represents a region of any shape and size that can be protected.
*
* @author sk89q
*/
public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Holds the region's ID.
*/
private String id;
/**
* Priority.
*/
private int priority = 0;
/**
* Parent region.
*/
private ProtectedRegion parent;
/**
* List of owners.
*/
private DefaultDomain owners = new DefaultDomain();
/**
* List of members.
*/
private DefaultDomain members = new DefaultDomain();
/**
* Area flags.
*/
private AreaFlags flags = new AreaFlags();
/**
* Area message.
*/
private String enterMessage;
/**
* Area message.
*/
private String leaveMessage;
/**
* Construct a new instance of this region.
*
* @param id
*/
public ProtectedRegion(String id) {
this.id = id;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the priority
*/
public int getPriority() {
return priority;
}
/**
* @param priority the priority to set
*/
public void setPriority(int priority) {
this.priority = priority;
}
/**
* @return the parent
*/
public ProtectedRegion getParent() {
return parent;
}
/**
* Set the parent. This checks to make sure that it will not result
* in circular inheritance.
*
* @param parent the parent to set
* @throws CircularInheritanceException
*/
public void setParent(ProtectedRegion parent) throws CircularInheritanceException {
if (parent == null) {
this.parent = null;
return;
}
if (parent == this) {
throw new CircularInheritanceException();
}
ProtectedRegion p = parent.getParent();
while (p != null) {
if (p == this) {
throw new CircularInheritanceException();
}
p = p.getParent();
}
this.parent = parent;
}
/**
* Se flags.
* @param flags
*/
public void setFlags(AreaFlags flags) {
this.flags = flags;
}
/**
* @return the enterMessage
*/
public String getEnterMessage() {
return enterMessage;
}
/**
* @param enterMessage the enterMessage to set
*/
public void setEnterMessage(String enterMessage) {
this.enterMessage = enterMessage;
}
/**
* @return the leaveMessage
*/
public String getLeaveMessage() {
return leaveMessage;
}
/**
* @param leaveMessage the leaveMessage to set
*/
public void setLeaveMessage(String leaveMessage) {
this.leaveMessage = leaveMessage;
}
/**
* @return the owners
*/
public DefaultDomain getOwners() {
return owners;
}
/**
* @param owners the owners to set
*/
public void setOwners(DefaultDomain owners) {
this.owners = owners;
}
/**
* @return the members
*/
public DefaultDomain getMembers() {
return members;
}
/**
* @param owners the owners to set
*/
public void setMembers(DefaultDomain members) {
this.members = members;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param player
* @return
*/
public boolean isOwner(LocalPlayer player) {
if (owners.contains(player)) {
return true;
}
ProtectedRegion parent = getParent();
while (parent != null) {
if (parent.getOwners().contains(player)) {
return true;
}
parent = parent.getParent();
}
return false;
}
/**
* Checks whether a player is a member of the region or any of its parents.
*
* @param player
* @return
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
return true;
}
ProtectedRegion parent = getParent();
while (parent != null) {
if (parent.getOwners().contains(player)
|| parent.getMembers().contains(player)) {
return true;
}
parent = parent.getParent();
}
return false;
}
/**
* Get flags.
*
* @return
*/
public AreaFlags getFlags() {
return flags;
}
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
*/
public abstract boolean contains(Vector pt);
/**
* Compares to another region.
*
* @param other
* @return
*/
public int compareTo(ProtectedRegion other) {
if (priority == other.priority) {
return 0;
} else if (priority > other.priority) {
return -1;
} else {
return 1;
}
}
/**
* Return the type of region as a user-friendly, lowercase name.
*
* @return type of region
*/
public abstract String getTypeName();
/**
* Checks if two region intersects.
*
* @param region1
* @param region2
* @throws UnsupportedIntersectionException
* @return
*/
public static boolean intersects(ProtectedRegion region1, ProtectedRegion region2)
throws UnsupportedIntersectionException {
if (region1 instanceof ProtectedCuboidRegion
&& region2 instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion r1 = (ProtectedCuboidRegion)region1;
ProtectedCuboidRegion r2 = (ProtectedCuboidRegion)region2;
BlockVector min1 = r1.getMinimumPoint();
BlockVector max1 = r1.getMaximumPoint();
BlockVector min2 = r2.getMinimumPoint();
BlockVector max2 = r2.getMaximumPoint();
return !(min1.getBlockX() > max2.getBlockX()
|| min1.getBlockY() > max2.getBlockY()
|| min1.getBlockZ() > max2.getBlockZ()
|| max1.getBlockX() < min2.getBlockX()
|| max1.getBlockY() < min2.getBlockY()
|| max1.getBlockZ() < min2.getBlockZ());
} else {
throw new UnsupportedIntersectionException();
}
}
/**
* Thrown when setting a parent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
}
}
@@ -0,0 +1,68 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.io.IOException;
import java.util.Map;
/**
* Represents a database to read and write lists of regions from and to.
*
* @author sk89q
*/
public interface ProtectionDatabase {
/**
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws IOException
*/
public void load() throws IOException;
/**
* Save the list of regions.
*
* @throws IOException
*/
public void save() throws IOException;
/**
* Load the list of regions into a region manager.
*
* @throws IOException
*/
public void load(RegionManager manager) throws IOException;
/**
* Save the list of regions from a region manager.
*
* @throws IOException
*/
public void save(RegionManager manager) throws IOException;
/**
* Get a list of regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions();
/**
* Set the list of regions.
*
* @param regions
*/
public void setRegions(Map<String,ProtectedRegion> regions);
}
@@ -0,0 +1,112 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.List;
import java.util.Map;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* An interface for getting, setting, and looking up regions. The most
* simple implementation uses a flat list and iterates through the entire
* list to look for applicable regions, but a more complicated (and more
* efficient) implementation may use space partitioning techniques.
*
* @author sk89q
*/
public interface RegionManager {
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String, ProtectedRegion> getRegions();
/**
* Set a list of protected regions.
*
* @return
*/
public void setRegions(Map<String,ProtectedRegion> regions);
/**
* Adds a region.
*
* @param id
* @param region
*/
public void addRegion(ProtectedRegion region);
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
public boolean hasRegion(String id);
/**
* Get a region by its ID.
*
* @param id
*/
public ProtectedRegion getRegion(String id);
/**
* Removes a region, including inheriting children.
*
* @param id
*/
public void removeRegion(String id);
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
public ApplicableRegionSet getApplicableRegions(Vector pt);
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
public List<String> getApplicableRegionsIDs(Vector pt);
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param region
* @param player
* @return
*/
public boolean overlapsUnownedRegion(ProtectedRegion region, LocalPlayer player);
/**
* Get the number of regions.
*
* @return
*/
public int size();
}
@@ -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,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,78 @@
// $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.Set;
import java.util.HashSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class TestPlayer extends LocalPlayer {
private String name;
private Set<String> groups = new HashSet<String>();
public TestPlayer(String name) {
this.name = name;
}
public void addGroup(String group) {
groups.add(group.toLowerCase());
}
@Override
public String getName() {
return name;
}
@Override
public boolean hasGroup(String group) {
return groups.contains(group.toLowerCase());
}
@Override
public Vector getPosition() {
// TODO Auto-generated method stub
return null;
}
@Override
public void kick(String msg) {
// TODO Auto-generated method stub
}
@Override
public void ban(String msg) {
// TODO Auto-generated method stub
}
@Override
public void printRaw(String msg) {
// TODO Auto-generated method stub
}
@Override
public String[] getGroups() {
// TODO Auto-generated method stub
return null;
}
}
@@ -0,0 +1,157 @@
// $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 org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.TestPlayer;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
public class ApplicableRegionSetTest {
static String COURTYARD_ID = "courtyard";
static String FOUNTAIN_ID = "fountain";
static String NO_FIRE_ID = "nofire";
static String MEMBER_GROUP = "member";
static String COURTYARD_GROUP = "courtyard";
Vector inFountain = new Vector(2, 2, 2);
Vector inCourtyard = new Vector(7, 7, 7);
Vector outside = new Vector(15, 15, 15);
Vector inNoFire = new Vector(150, 150, 150);
RegionManager manager;
ProtectedRegion courtyard;
ProtectedRegion fountain;
TestPlayer player1;
TestPlayer player2;
@Before
public void setUp() throws Exception {
manager = new FlatRegionManager(new GlobalFlags());
setUpPlayers();
setUpCourtyardRegion();
setUpFountainRegion();
setUpNoFireRegion();
}
void setUpPlayers() {
player1 = new TestPlayer("tetsu");
player1.addGroup(MEMBER_GROUP);
player1.addGroup(COURTYARD_GROUP);
player2 = new TestPlayer("alex");
player2.addGroup(MEMBER_GROUP);
}
void setUpCourtyardRegion() {
DefaultDomain domain = new DefaultDomain();
domain.addGroup(COURTYARD_GROUP);
ProtectedRegion region = new ProtectedCuboidRegion(COURTYARD_ID,
new BlockVector(0, 0, 0), new BlockVector(10, 10, 10));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_BUILD, State.NONE);
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
region.setFlags(flags);
region.setOwners(domain);
manager.addRegion(region);
courtyard = region;
}
void setUpFountainRegion() throws Exception {
DefaultDomain domain = new DefaultDomain();
domain.addGroup(MEMBER_GROUP);
ProtectedRegion region = new ProtectedCuboidRegion(FOUNTAIN_ID,
new BlockVector(0, 0, 0), new BlockVector(5, 5, 5));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.DENY);
region.setFlags(flags);
region.setMembers(domain);
manager.addRegion(region);
fountain = region;
fountain.setParent(courtyard);
}
void setUpNoFireRegion() throws Exception {
ProtectedRegion region = new ProtectedCuboidRegion(NO_FIRE_ID,
new BlockVector(100, 100, 100), new BlockVector(200, 200, 200));
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.DENY);
region.setFlags(flags);
manager.addRegion(region);
}
@Test
public void testNonBuildFlag() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertFalse(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
// Inside no fire zone
appl = manager.getApplicableRegions(inNoFire);
assertFalse(appl.allowsFlag(AreaFlags.FLAG_FIRE_SPREAD));
}
@Test
public void testPlayer1BuildAccess() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.canBuild(player1));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertTrue(appl.canBuild(player1));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.canBuild(player1));
}
@Test
public void testPlayer2BuildAccess() {
ApplicableRegionSet appl;
// Outside
appl = manager.getApplicableRegions(outside);
assertTrue(appl.canBuild(player2));
// Inside courtyard
appl = manager.getApplicableRegions(inCourtyard);
assertFalse(appl.canBuild(player2));
// Inside fountain
appl = manager.getApplicableRegions(inFountain);
assertTrue(appl.canBuild(player2));
}
}
@@ -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.protection;
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.AreaFlags.State;
public class CSVDatabaseTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testLoadSave() throws Exception {
File temp = File.createTempFile("worldguard_csv_test", ".tmp");
temp.deleteOnExit();
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
regions.put("test1", getTestRegion1());
regions.put("test2", getTestRegion2());
CSVDatabase writeDB = new CSVDatabase(temp);
writeDB.setRegions(regions);
writeDB.save();
CSVDatabase readDB = new CSVDatabase(temp);
readDB.load();
Map<String,ProtectedRegion> loaded = readDB.getRegions();
ProtectedRegion region1 = loaded.get("test1");
checkTestRegion1(region1);
}
private void checkTestRegion1(ProtectedRegion region) {
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.DENY);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
assertEquals(region.getFlags(), flags);
}
private ProtectedRegion getTestRegion1() {
BlockVector min = new BlockVector(1, 2, 3);
BlockVector max = new BlockVector(4, 5, 6);
ProtectedRegion region = new ProtectedCuboidRegion("test2", min, max);
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.DENY);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
DefaultDomain domain = new DefaultDomain();
domain.addGroup("members");
domain.addGroup("sturmehs");
domain.addPlayer("hollie");
domain.addPlayer("chad");
domain.addPlayer("tetsu");
region.setOwners(domain);
region.setEnterMessage("hello there!");
region.setPriority(444);
return region;
}
private ProtectedRegion getTestRegion2() {
BlockVector min = new BlockVector(7, 8, 9);
BlockVector max = new BlockVector(10, 11, 12);
ProtectedRegion region = new ProtectedCuboidRegion("test2", min, max);
AreaFlags flags = new AreaFlags();
flags.set(AreaFlags.FLAG_FIRE_SPREAD, State.ALLOW);
flags.set(AreaFlags.FLAG_PVP, State.ALLOW);
flags.set(AreaFlags.FLAG_LIGHTER, State.DENY);
region.setFlags(flags);
DefaultDomain domain = new DefaultDomain();
domain.addGroup("admins");
domain.addPlayer("jon");
domain.addPlayer("ester");
domain.addPlayer("amy");
region.setOwners(domain);
region.setEnterMessage("Testing");
region.setPriority(555);
return region;
}
}
-32
View File
@@ -1,32 +0,0 @@
#
# This is the blacklist for WorldGuard. Comments start with # and they
# are ignored so you can put your own notes.
#
# Format:
# [item1,item2,itemN]
# option1=options
# event1=action1,action2,actionN
# eventN=action1,action2,actionN
#
# Events/Options:
# - ignore-groups (comma-delimited list of groups to not affect)
# - on-destroy (when a block of this type is destroyed)
# - on-left (when this item is held and the player is left clicking)
# - on-right (when this item is held and the player is right clicking)
#
# Actions:
# - deny (deny completely)
# - notify (notify admins)
# - log (log to console/file)
# - kick (kick player)
# - tell (tell a player that that's not allowed)
#
# Some examples follow.
#
#[lavabucket]
#on-left=deny,log,kick
#on-right=deny,tell
#[coalore,goldore,ironore]
#on-destroy=notify,deny,log
#[cobblestone]
#on-right=deny,tell,log