Compare commits

...
854 Commits
Author SHA1 Message Date
sk89q ee2ed762c2 Added a better and more complete implementation for attributes with sane class names. 2013-02-07 12:11:25 -08:00
sk89q a0dceaa713 Added StringAttr.
The name of the class could be better.
2013-02-06 17:29:48 -08:00
sk89q 4b15855b2f Revert "Removed parents from regions."
Removal of parents will make upgrading extremely difficult and so consider them pending for the itme being.

This reverts commit df54d4de91.
2013-02-06 17:19:09 -08:00
sk89q 7acfb3586c Cleanup Attribute Javadocs. 2013-02-06 17:17:28 -08:00
sk89q a841aa7215 Added Stereotypes for group support for flags/attributes.
They are not yet functional because they require some extra mechanics not yet written (access to factories and whatnot).
2013-02-06 17:17:12 -08:00
sk89q f752c305d7 Made ApplicationRegionSet implement Collection<Region>, and made it keep the given list sorted. 2013-02-05 20:39:13 -08:00
sk89q 840700b719 Might as well make ApplicableRegionSet implement Collection<Region>. 2013-02-05 20:32:33 -08:00
sk89q 8f73a15ba3 Gutted ApplicableRegionSet. 2013-02-05 20:29:11 -08:00
sk89q 4e008f6c52 Made the class Javadoc of AbstractRegionQueryCache sane. 2013-02-05 20:20:31 -08:00
sk89q df54d4de91 Removed parents from regions.
After a minor discussion, parent-child relationships are being removed because they:
(1) confuse users
(2) make everything much more difficult to program
(3) do not allow for a use case that is not already doable with priorities
2013-02-05 20:06:11 -08:00
sk89q 0768e08e71 Minor cleanup. 2013-02-05 20:04:19 -08:00
sk89q 040e35f65b Added some misisng methods to DataValuedAttribute and added a test. 2013-02-05 16:25:59 -08:00
sk89q 919c03a57b Made Attribute abstract, rewrote Javadocs. 2013-02-05 16:16:45 -08:00
sk89q a13f556c7b Added AttributeTest. 2013-02-05 13:30:59 -08:00
sk89q 5bfb9e48f4 RegionTest cleanup. 2013-02-05 13:30:41 -08:00
sk89q ff209abb8c Added support for attributes to Region. 2013-02-05 13:18:46 -08:00
sk89q 7987258fe2 Added equals(), hashCode(), and toString() to Attribute. 2013-02-05 13:04:04 -08:00
sk89q 4cba9d01ec Replaced flags with attributes. 2013-02-05 13:00:44 -08:00
sk89q e703999c8f Added a simple test for com.sk89q.worldguard.region.Region. Flags are not yet tested. 2013-02-03 23:46:39 -08:00
sk89q bfc8691118 Added org.mockito:mockito-all v1.9.5 as test dependency. 2013-02-03 23:46:14 -08:00
sk89q 061b303faa Removed old broken unit tests.
We may look at them in the future once those tests are needed again.
2013-02-03 23:45:38 -08:00
sk89q 3b985f7eab Fixed potential resource leak in LegacyMySqlStoreFactory.getSql(). 2013-02-03 23:26:26 -08:00
sk89q a027721f37 Renamed RegionIndex.queryOverlapping() -> queryIntersects() and added an implementation under AbstractRegionIndex using IndexableShape.intersectsEdges(). 2013-02-03 23:24:32 -08:00
sk89q 129412ba79 Canning isOwnerOfAll() and isMemberOfAll() of ApplicableRegionSet. 2012-11-17 16:46:31 -08:00
sk89q e0ab79bd36 Canning RegionUtil, which is now completely useless. 2012-11-17 16:45:37 -08:00
sk89q 28a1f225ee Removed very broken and now irrelevant regions migration code. 2012-11-17 16:41:17 -08:00
sk89q 355168a3ac Removed isMember()/isOwner() as it is no longer relevant (to be placed with FlagResolvers). 2012-11-17 16:37:38 -08:00
sk89q 27c6819df9 Removed /claim. To be rewritten very differently. 2012-11-17 16:37:02 -08:00
sk89q 122c1aa003 Removed some left over CommandBook listener registration in WorldGuardPlugin. 2012-11-17 16:36:04 -08:00
sk89q 644d6ee512 Commented out regions-related code in ReportWriter as it is no longer valid. 2012-11-17 16:35:48 -08:00
sk89q 58cc4392c8 Removing RegionQueryUtil, which might not be needed anymore. 2012-11-17 16:35:24 -08:00
sk89q e228315dfd Removed CommandBook integration for /whois for now. 2012-11-17 16:35:03 -08:00
sk89q 8a308cd521 Remove old pre-5.x migration routines from WorldGuardPlugin. 2012-11-17 16:34:28 -08:00
sk89q c3d3c1812f Removing migration support for WorldGuard 4.x and below. 2012-11-17 16:33:37 -08:00
sk89q cc5958bc2f Removed FlagStateManager for now. To be added later. 2012-11-17 16:32:15 -08:00
sk89q 2d8911c9ce Added LegacyMySqlStoreFactory, moved .sql files to src/main/resources/sql. 2012-11-17 16:29:20 -08:00
sk89q c6a0c61028 Made LegacyMySqlStore compile. Domain not yet supported. 2012-11-17 16:28:54 -08:00
sk89q 0c0cbcc1b0 Added com.jolnox:bonecp as dependency. 2012-11-17 16:28:24 -08:00
sk89q 5882e30357 Add initialize() to RegionStoreFactory to allow some setup actions. 2012-11-17 16:27:50 -08:00
sk89q 4faf0a9b2e YamlStore needs to call reindex() after loading. 2012-11-17 16:27:25 -08:00
sk89q 2e4093e953 Removed FatalConfigurationLoadingException and InvalidTableFormatException. 2012-11-16 17:00:50 -08:00
sk89q 1a9a3274a6 YamlStoreFactory added.
Example usage:
StoreFactory factory = new YamlStoreFactory(new File("regions"), "worlds/%s/regions.yml"));
2012-11-16 16:42:37 -08:00
sk89q 8671fbc396 Implemented YamlStore.close(), which does nothing. 2012-11-16 16:41:05 -08:00
sk89q 50c4b3c738 RegionStore and RegionStoreFactory now extend Closeable. 2012-11-16 16:40:29 -08:00
sk89q 23f0791231 Changed MySQLStore to LegacyMySqlStore.
We're going to need a new MySqlStore that is not so poorly written. This is going to need a lot of work.
2012-11-16 16:07:34 -08:00
sk89q fa11dd6d62 Made YamlStore fit its interfaces so that there are no more compile errors.
It is, however, not yet ready, because it doesn't yet support custom flags or load in the old domain data.
2012-11-16 16:05:51 -08:00
sk89q 58fa6d1c0b Extracted RegionStore.save(Collection<Region> added, Collection<Region> updated, Collection<Region> removed) into PartiallyUpdatableStore.
This is necessary because some stores need to always save the entire database at a time (namely the YAML store), and adding an "all" parameter to the partial save method would mean that partial stores could not be supported in the future.
2012-11-16 15:52:37 -08:00
sk89q 723f17b782 Region indices now implement Collection<Region>.
In addition, PriorityRTreeIndex now extends FlatIndex! That should reduce some code duplication.
2012-11-16 15:40:09 -08:00
sk89q fe2e399451 RegionIndex now extends Iterable<Region>. 2012-11-16 13:49:33 -08:00
sk89q 6fa7faad12 Removed ProtectionDatabaseException and AbstractProtectionDatabase. 2012-11-16 13:43:14 -08:00
sk89q c864a1c252 RegionStore.save(Region added[], Region updated[], Region removed[]) throws IOException as well. 2012-11-16 13:42:59 -08:00
sk89q 386288b89a RegionStore's load() and save() methods can now throw IOExceptions.
ProtectionDatabaseException will be removed shortly.
2012-11-16 13:42:23 -08:00
sk89q b3425b2630 Region is no longer abstract, added Region.setFlagUnsafe(). 2012-11-16 13:39:26 -08:00
sk89q f8105c3de0 Fixed Javadocs for shapes. 2012-11-16 13:38:44 -08:00
sk89q bcf35085ed Indices now have a separate reindex() method because large changes to the index have to be supported.
Therefore, indices are no longer thread-safe. They don't need to be.
2012-11-16 13:36:26 -08:00
sk89q b7064cb102 Removed LegacyCsvStore and RegionDBUtil. 2012-11-16 10:12:59 -08:00
sk89q 6c282cfe0a Moved Region's package to com.sk89q.worldguard.region. 2012-11-16 10:11:08 -08:00
sk89q f8e0410d23 Finished com.sk89q.worldguard.region.shapes. 2012-11-16 09:28:46 -08:00
sk89q e8274e76ca Moved ProtectedRegion forward with some changes. 2012-11-15 17:17:56 -08:00
sk89q 393b15ac7a Added IndexableShape and its abstract brother. 2012-11-13 23:19:11 -08:00
sk89q 38f40908ee Say bye to com.sk89q.worldguard.domains.*. 2012-11-13 23:17:34 -08:00
sk89q caee1df596 Moved MySQLToYAMLMigrator to com.sk89q.worldguard.migration. 2012-11-13 01:03:24 -08:00
sk89q d9d655b6b2 Added RegionStore and RegionStoreFactory. 2012-11-13 01:02:41 -08:00
sk89q cc9bbec1c9 Added support for RegionIndexFactories. 2012-11-13 00:57:29 -08:00
sk89q 2a504ffbde Moved migration classes to com.sk89q.worldguard.migration. 2012-11-13 00:51:19 -08:00
sk89q 5f11c5710b Changed RegionIndex.{add|remove} to take in multiple regions to update, which may be faster for some index types. 2012-11-12 21:33:05 -08:00
sk89q 5d3409be57 Moved region.indexes package to region.indices. 2012-11-12 21:29:02 -08:00
sk89q ad921a2111 Updated the existing index code to work with the new RegionIndex interface. 2012-11-12 21:28:27 -08:00
sk89q 50ec8e5875 Added commons-lang:commons-lang:2.3 dependency. 2012-11-12 21:27:59 -08:00
sk89q fc9e28ddb9 Started with defining the new RegionIndex.
This definitely no longer compiles.
2012-11-12 20:08:34 -08:00
sk89q 35e02459ea Moved region classes to com.sk89q.worldguard.region. Preparing for some big changes.
The new classes will not (and should not) be backwards compatible, so the classes might as well be changed all around.
2012-11-12 01:24:34 -08:00
sk89q 0781ebc289 Added ?in-region and ?has-flag, and added the support to make protection models work. 2012-11-11 16:27:31 -08:00
sk89q 915e332a6b Fixed issue with block-place RL event not being given a source entity. 2012-11-11 16:26:34 -08:00
sk89q 19859164ab Moved settings loading in WorldConfiguration to loadSettings(), add preliminary loading of protection models. 2012-11-10 23:32:40 -08:00
sk89q bb7f972897 Added resource models/ to distributed JAR. 2012-11-10 23:32:12 -08:00
sk89q e355bb0055 Fixed missing exception message for an unknown action/criteria class in RuleEntryLoader. 2012-11-10 23:31:43 -08:00
sk89q 9b1b665da7 Removed some chest protection code, which will be replaced with RuleLists. 2012-11-10 22:35:57 -08:00
sk89q 6daf80229d Fixed condition issue in EntityCriteria that broke entity type checking. 2012-11-10 21:29:31 -08:00
sk89q dc1f3f54b1 Redesigned how RuleLists were compiled and created to be less roundabout. 2012-11-10 21:29:00 -08:00
sk89q 579143a5dd Added support for the region query cache on Bukkit's side and added it to BukkitContext. 2012-11-10 10:48:25 -08:00
sk89q f4e52f5cd7 Added Javadocs to BukkitContext. 2012-11-10 00:31:50 -08:00
sk89q abea9689cb Removed blacklist/region code for now, to be converted to RuleLists.
Additionally, a chat rule list event was added, the vehicle destruction event was routed to rule lists, and so was the bed enter event.
2012-11-09 14:49:45 -08:00
sk89q 2c7767f89f Added RegionQueryCache, which will be used to for cached regions-contain-point lookups. 2012-11-09 12:18:54 -08:00
sk89q 5e75bf36c3 Added proposed protection models. 2012-11-06 22:04:25 -08:00
sk89q a5814c4b32 Made the resolution of criteria parameters as all logical ANDs. 2012-11-06 10:29:41 -08:00
sk89q 70ae1c46a2 Fixed incorrect warning about unrecognized "entity" parameter in TellActionLoader. 2012-11-06 00:52:44 -08:00
sk89q fc5c59ec85 Added support for the item attribute of the Context and routed PlayerInteract into item-use,. 2012-11-06 00:51:40 -08:00
sk89q 2d9a28b0e6 Support accessing the item attribute of the context with match-item and update-item. 2012-11-04 16:07:42 -08:00
sk89q cbcc524798 Standardize the default resolver of entities/blocks to 'target'. 2012-11-04 13:00:52 -08:00
sk89q 69940f2fac Standardized default resolver values. 2012-11-04 12:33:35 -08:00
sk89q 35628d09be Route BlockDispenseEvent to RuleLists item-drop. 2012-11-04 12:17:05 -08:00
sk89q ef43ba2700 player-spawn -> player-join 2012-11-04 11:05:21 -08:00
sk89q 2c2484b026 player-death is very redundant. Changing to entity-death. 2012-11-04 11:03:40 -08:00
sk89q b181bfc914 Added dynamics.disable-mycelium-spread to match master branch. 2012-11-04 01:03:08 -08:00
sk89q 7fcf686d8d Added physics.vine-like-rope-ladders to make ladders work like vines. 2012-11-03 23:28:35 -07:00
sk89q 4f5a751519 Added RuleLists, which are a more flexible version of blacklists, with a cleanup of code.
RuleLists abstract events, and provide a way to unify WorldGuard's various code paths eventually.

There's also a general cleanup of everything and added support for changing the per-world configurations and blacklists (fixes WORLDGUARD-2232). WORLDGUARD-2203 is implicitly fixed by this, although not entirely fully as this does not yet replace blacklists.

Most configuration settings have been rewritten as RuleList rules and can be found in src/main/resources/builtin_rules.yml. Some configuration changes were made: anti-wolf-dumbness was deprecated in favor of wolves-practically-invincible, and ocelots-practically-invincible was added.

Sponges can now re-place water when they are removed, fixing WORLDGUARD-2202.
2012-11-03 23:21:32 -07:00
sk89q a035bcc671 [maven-release-plugin] prepare for next development iteration 2012-11-03 12:38:06 -07:00
sk89q 9bcc6b9605 [maven-release-plugin] prepare release 5.6 2012-11-03 12:37:52 -07:00
sk89q 282c3a864e Updated CHANGELOG.txt for 5.6. 2012-11-03 12:15:43 -07:00
sk89q eb083a8934 Updated README.html to mention the moved spawn-protection setting, added more explanations. 2012-11-03 12:15:43 -07:00
sk89q 0fc71ff79e Note the issue tracker in README.html. 2012-11-03 12:15:43 -07:00
sk89q 68a7455496 Added backwards compatibility for versions below MC1.4. 2012-11-03 12:15:43 -07:00
Dark Arc fcfc3acbb8 Improved Performance of some operations
Replaced quite a few whiles and fors with for-eachs giving a performance gain. Also fixed a few issues with the MySQLDatabase and made several other minor improvements.
2012-11-03 00:19:40 -04:00
sk89q aa53c0aa6a We have a new issue tracker. 2012-11-02 18:15:02 -07:00
Dark Arc f098905a92 Fixes WORLDGUARD-2205
Mob Damage from projectiles is now properly blocked in regions where applicable.
2012-11-02 21:07:38 -04:00
Dark Arc eec78092b5 Allow damage to be less than 1
This resolves problems with mods that use fake damage events to check with WorldGuard what's going on.
2012-11-02 20:57:24 -04:00
sk89q 34fa5eceb8 Fixed WORLDGUARD-2255, where region.getId() was lowercase'd each pass of a for loop in MySQLDatabase.updatePoly2dPoints(). 2012-11-02 14:13:53 -07:00
Dark Arc c32d2dd6f8 Fixes WORLDGUARD-2254
Players will now be told that they are in a no-PvP area if they are in one and attempting to attack someone, or that the player they are attacking is in a no-PvP area, if that is the case instead.
2012-11-02 17:06:35 -04:00
Dark Arc da80d3536a Fixes WORLDGUARD-2253
Players who are not in god mode will once again receive damage in PVP areas from Ender Pearls.
2012-11-02 17:06:33 -04:00
sk89q e9361022d2 Protected against using (right-clicking) paintings and item frames. 2012-11-02 13:41:53 -07:00
sk89q dd0c1a5ab5 Fixed Withers still breaking blocks if they smash their bodies into them. Fixes WORLDGUARD-2245. 2012-11-02 12:20:59 -07:00
Wojciech Stryjewski bb9dff7b8c Deleting a region flag also deletes group flag
The group flags set with /region flag -g have no effect if the
normal flag is not also set, nor will they be displayed with
/region info once the normal flag is deleted. However, if a
group flag was to remain set in the database, the next time a
user sets the normal flag, they might be surprised to suddenly
see the corresponding group set as well.

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

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

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

With this code change, if a group flag has been set on "entry" for
example, it might be shown as "Flags: entry -g OWNERS: ALLOW".
2012-11-01 22:43:23 -07:00
BangL 1502ec12a9 Added support for the hanging events, an item frame destroy region flag, and a mobs.block-item-frame-destroy setting.
Now also using Bukkit 1.4.2-R0.2-SNAPSHOT and WorldEdit 5.4.4-SNAPSHOT.
2012-11-01 22:35:15 -07:00
sk89q 6d09b18479 Check for both LARGE_FIREBALL and FIREBALL for the EntityType in the entity listener.
This is to counteract a breaking Bukkit change.
2012-10-30 09:24:10 -07:00
Dark Arc 08ce207636 Fixed bugs in the PRTreeRegionManager class:
* Point would not be returned if the player was at point which exceeded the flat decimal maximum of a region.
* The getAplicableRegionIDs method would not return the parents of a region.
* All test would fail
2012-10-29 12:14:11 -07:00
sk89q f199b977eb Added more tests for the PRTreeRegionManager to fail. 2012-10-29 12:14:10 -07:00
sk89q 5715e2c835 WorldGuard has good unit tests for regions, why not use them for PRTreeRegionManager?
LET'S WATCH THE WORLD BURN.
2012-10-29 12:14:10 -07:00
sk89q b8642b7ca3 Tiny change to PRTree version to make it load a Java6 compile. 2012-10-29 12:14:10 -07:00
Wizjany 2c4d4708d8 Added parent region checking to PRTree manager as per Dark_Arc's specifications. 2012-10-29 12:14:10 -07:00
Darth Android 0edb6e6157 Include the PRTree library in generated artifacts 2012-10-29 12:14:10 -07:00
Darth Android 4f394b5668 Update PRTree library to v1.5
Updated PRTreeRegionManager code to support 3D points and regions
Changed region manager to PRTreeRegionManager
2012-10-29 12:14:09 -07:00
Glitchfinder 9834c30e3a Adding and fixing support for new and existing explosion types. 2012-10-28 20:23:36 -07:00
sk89q f3f1b0870f Changed default region wand to leather (#334). 2012-10-28 14:12:10 -07:00
sk89q 915d314c18 Removed <modules> that magically appeared thanks to Eclipse. 2012-10-28 14:07:41 -07:00
sk89q 02b3ae6aa5 Added mobs.block-wither-block-damage. 2012-10-28 14:01:17 -07:00
sk89q f725e73653 Move to WG 5.6-SNAPSHOT and Bukkit 1.4.2-R0.1-SNAPSHOT. 2012-10-28 14:01:17 -07:00
sk89q c5858ef202 Removed <packaging> from pom.xml. 2012-10-28 13:56:46 -07:00
sk89q ba2fd2ca2e Brought README.md and CONTRIBUTING.md inline with latest updates. 2012-10-28 13:54:06 -07:00
Wojciech Stryjewski 1075d36748 Fix spurious comma in "Flags:" /region info output
When the "/region info" command displays any flags in the region,
it always prints an extra leading comma character after the
"Flags:" prompt.
2012-10-24 12:48:38 -05:00
sk89q 3ee3799e55 I'm OCD like that. Changed WG->${project.name} in readme, added license ver. to README.md. 2012-10-24 00:29:20 -07:00
sk89q 6654b0a67a More readme cleanup. 2012-10-24 00:29:20 -07:00
sk89q 9577c93edb Better place for README.md logo URL. 2012-10-24 00:29:20 -07:00
sk89q 7cd67281bc Move extraneous files to contrib/, added region_storage_update_20110325.sql to assembly. 2012-10-24 00:29:20 -07:00
sk89q d21c226183 Modernized README.html. 2012-10-24 00:29:19 -07:00
sk89q 4322236b9e Updated the ancient README.html. 2012-10-24 00:29:19 -07:00
sk89q 05e408ee65 Updated README.md. 2012-10-24 00:29:19 -07:00
sk89q 3d1012ba94 Cleaned up pom.xml and updated CommandBook to 2.1. 2012-10-24 00:29:19 -07:00
sk89q 94937e41ef Changed the region MySQL database to marshal and unmarshal values using YAML, which should fix the notable problems regarding non-string flag data types. 2012-10-24 00:28:43 -07:00
sk89q 3957aa83fc Say hi to travis-ci. 2012-10-24 00:28:43 -07:00
Rutr 8aa79d1c4c Fixed detection damager(when attac by magic) http://redmine.sk89q.com/issues/901 2012-10-19 09:02:19 +02:00
sk89q 578eeff0e1 [maven-release-plugin] prepare for next development iteration 2012-10-07 10:47:07 -07:00
sk89q 5f2f1c67f5 [maven-release-plugin] prepare release 5.5.4 2012-10-07 10:46:51 -07:00
sk89q c92b9c3d97 Updated CHANGELOG.txt. 2012-10-07 10:40:00 -07:00
sk89q 0951d00da3 Fixed permissions for region loading/saving. 2012-10-06 21:47:37 -07:00
zml2008 6df9c3660b Merge pull request #201 from eric-wieser/patch-1
Did `wcfg.useRegions` really need to be checked twice?
2012-09-16 12:31:17 -07:00
Alexander 19be2bf96e Updated fireball item blocking 2012-08-23 12:41:36 +02:00
Fletch to 99 e10ed6ac7a Report the amount of plugins loaded 2012-08-12 16:56:22 -03:00
sk89q 479ebf4d89 Copying and pasting is bad. Fixed references of worldedit -> worldguard in new pom.xml changes. 2012-08-11 00:28:02 -07:00
sk89q 1f1e36e9f7 Updated pom.xml for license, distributionManagement, maven-site-plugin. 2012-08-11 00:26:06 -07:00
TomyLobo 27e634ae03 Fixed a warning. 2012-08-11 04:37:49 +02:00
unknown e60b20b37b Add 'use' flag to cakes 2012-08-10 22:33:55 +02:00
zml2008 684214ff6a Update for async player chat stupidity 2012-08-04 19:56:48 -07:00
sk89q ba5be6071f Added regions.use-creature-spawn-event configuration setting. 2012-07-23 13:45:04 -07:00
TomyLobo 6c8d13690e Fixed eggs, snowballs and the likes being dupable with /stack. 2012-07-16 16:08:04 +02:00
TomyLobo 3e0b2ef3e4 Upped Bukkit dependency version to 1.2.4-R4.1. 2012-07-14 00:16:45 +02:00
sk89q c5304d2775 [maven-release-plugin] prepare for next development iteration 2012-07-07 10:55:58 -07:00
sk89q ca95ae04a5 [maven-release-plugin] prepare release 5.5.3 2012-07-07 10:55:45 -07:00
sk89q 1ab9f85ca6 Updated CHANGELOG. 2012-07-07 10:39:37 -07:00
sk89q 01ff1b2f8f Added host key check. 2012-07-07 10:33:18 -07:00
Zak Ford 9b17fe68e7 Added configuration option to allow plugin creature spawns 2012-07-01 16:02:24 -04:00
zml2008 0fed35a80f Add bypass handling to the gamemode flag
Set a player's previous gamemode when exiting a gamemode region to the server's default gamemode if there is not a previous gamemode already set
2012-06-15 14:14:13 -07:00
TomyLobo 25280c9fa9 Set Bukkit dependency to R2.1.
That's the current CraftBukkit++ version.
2012-06-11 03:31:50 +02:00
TomyLobo a98ebfdb21 Updated dependencies and added support for fireball item blocking (id 385). 2012-06-07 13:26:28 +02:00
Eric Wieser acb1d18654 Did wcfg.useRegions really need to be checked twice? 2012-04-28 18:18:51 +02:00
TomyLobo 18b5a4e106 Added @Ignore to TestPlayer.
Stupid old mavens...
2012-04-23 11:07:05 +02:00
md_5 bab420a359 Add item drop pickup flag for regions.
Closes #200
2012-04-20 20:25:25 -07:00
zml2008 4f14f1f736 Correctly convert \n to a newline for String flags 2012-04-16 17:00:41 -07:00
zml2008 166831447c Split the region greeting with \n
Improve input handling of EnumFlag
Don't block gamemode changing after the gamemode flag is no longer in
effect but while the move event is still firing
2012-04-15 21:19:02 -07:00
zml2008 f2bd5961d0 Add GameMode flag 2012-04-15 21:19:02 -07:00
zml2008 2cc990a530 Prevent commands in the allow commands list from being blocked and vice versa 2012-04-15 21:19:02 -07:00
TomyLobo f0e6008563 Updated bukkit dependency to 1.2.5-R1.2-SNAPSHOT. 2012-04-15 19:36:15 +02:00
zml2008 93f19cca0a [maven-release-plugin] prepare for next development iteration 2012-04-10 18:30:42 -07:00
zml2008 1cbe508f82 [maven-release-plugin] prepare release 5.5.2 2012-04-10 18:30:36 -07:00
zml2008 0c178c3155 Added recent commits to the changelog 2012-04-10 18:20:57 -07:00
zml2008 e67304389d Added send-chat and receive-chat flags 2012-04-07 14:43:51 -07:00
zml2008 ad5b1cdcba Make sure to update CommandBook installed status in onEnable 2012-04-07 13:46:25 -07:00
zml2008 fe1e09289f Add entity-painting-destroy flag to prevent entities from destroying paintings 2012-04-07 13:45:46 -07:00
zml2008 583ea76e4b Added potion splash flag to prevent splash potions from affecting entities 2012-04-07 12:11:00 -07:00
zml2008 a7d198893e Revert "Added allow-flight boolean flag for regions"
This conflicted with plugins maually setting a player's allow flight setting
This reverts commit 16ce56c1ad.
2012-03-31 07:53:42 -07:00
Nicholas Steicke fe62c8d0c5 Fixed regions with same name in different worlds not behaving correctly
Fixed database connection timing out

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

Added a generic exception for Fatal errors when loading configuration

Exit the server when we encounter a fatal configuration exception
2012-03-27 17:18:39 -07:00
Deaygo 16ce56c1ad Added allow-flight boolean flag for regions
Closes #198
2012-03-24 18:45:56 -07:00
zml2008 15f0bfb9db Update changelog for release 2012-03-23 21:47:34 -07:00
TomyLobo 22db589742 Restructured /rg list.
- When used with a player name to filter things down, it displays indexes that can be used as "#index" in place of region names now.
- No longer displayer "+-regionname" for regions the target player is the owner of.
2012-03-23 15:13:46 +01:00
TomyLobo 69119e6db7 Added ProtectedRegion.isOwner/Member(String playerName). 2012-03-23 15:13:45 +01:00
TomyLobo 690da2332b Added Domain.contains(String playerName). 2012-03-23 15:13:45 +01:00
sk89q f2fead1444 Changed broadcastNotification() to also check if the player has permission via superperms, in addition to being in the Permissible set. 2012-03-18 13:13:13 -07:00
TomyLobo c4f6267921 A cancellable event is now fired if WorldGuard disallows PvP. 2012-03-17 09:16:03 +01:00
TomyLobo 0dc65d083f Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
Same with worldguard.region.setparent.<id>
2012-03-12 15:08:35 +01:00
TomyLobo 40c1d93f02 Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
/region claim/remove/redefine are exempt from this and require exact matches.
2012-03-12 15:05:59 +01:00
TomyLobo 2024a93126 Fixed an error that occured when clearing a non-existant region's parent. 2012-03-12 15:05:32 +01:00
TomyLobo 88d79a42e6 Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region. 2012-03-12 10:40:03 +01:00
TomyLobo b01b2cce9b Added region/role-based permissions to /region teleport. 2012-03-12 10:39:23 +01:00
TomyLobo c5b1089c96 Changed source and target java version to 1.6 and set the WE dependency to 5.3-SNAPSHOT. 2012-03-12 08:04:08 +01:00
TomyLobo 679e43758b BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
This means all teleport and spawn flags are cleared.
This also means that world, yaw and pitch are now saved with these flags.
2012-03-12 06:52:36 +01:00
TomyLobo 90e6e5a96c /region info -s now selects the region being queried. 2012-03-12 05:53:58 +01:00
TomyLobo 4fb003c4df Added /region teleport <id>. 2012-03-11 19:31:02 +01:00
TomyLobo 9d5f349a04 Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z. 2012-03-11 19:08:25 +01:00
TomyLobo f4f4a47a7f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:08:24 +01:00
TomyLobo 6a3e987668 /region info changes
- Fixed /region info <world> <id> checking the wrong permission
- Condensed /region info output a bit
- Cleaned up the source a bit
2012-03-11 19:07:25 +01:00
TomyLobo 83f943965f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:07:25 +01:00
zml2008 c9fdff169f Prevent block ignition from lightning strikes if lightning is blocked in region.
Fixes #1175
2012-03-10 21:33:24 -08:00
zml2008 5454832918 Fix trailing whitespace and correctly check both permisions systems in WorldGurdPlugin.broadcastNotification() 2012-03-10 17:56:02 -08:00
zml2008 3d6d774b17 Use ignoreCancelled for event cancelled checking 2012-03-08 19:29:53 -08:00
zml2008 1463547af4 Destroy fire blocks when fire-spread is disallowed 2012-03-08 19:03:05 -08:00
TomyLobo 0bcf4b3597 Added a "none" category to region group flags (aliases noone and deny). 2012-03-08 10:30:57 +01:00
TomyLobo 824e8dcb4b Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles. 2012-03-08 10:18:27 +01:00
TomyLobo 4b2f0c8020 Let's not confuse certain highlighters. 2012-03-08 02:05:33 +01:00
Wizjany 7fd424cf65 Added FallingSand to list of intensive entities to be removed with /halt-activiy. 2012-03-03 21:27:35 -05:00
zml2008 5ff2855eb0 Fix entry and exit group flags not working, fix vehicle destroy flag not being allowed with canBuild 2012-03-03 16:46:06 -08:00
TomyLobo 8c8c162a54 Replaced all usage of CreatureType by EntityType. 2012-03-02 20:21:04 +01:00
TomyLobo 37d52f3688 Commented an unused local variable. 2012-03-02 20:10:51 +01:00
TomyLobo f361cbfa71 Removed unused imports. 2012-03-02 20:03:18 +01:00
sk89q ddefbfe2cf Fixed NPE with null ItemStack for pumpkin scuba in EntityDamageEvent. 2012-03-02 10:33:14 -08:00
sk89q 10296cb736 Made auto-god-mode disabled by default again. 2012-03-01 20:57:34 -08:00
zml2008 49dc0599c9 Remove leftover 128 value, fix RegionGroup.ALL handling 2012-03-01 20:49:01 -08:00
zml2008 14348e170b Revert a few of the region flag changes. This should fix issues people have been having at least for now. 2012-03-01 20:11:51 -08:00
zml2008 59d1f0d817 5.5.1 release, bump to 5.5.2-SNAPSHOT to fix stuff 2012-03-01 20:11:50 -08:00
sk89q e024f134a4 Fixed another NPE with the infinite stack remover. 2012-03-01 20:06:02 -08:00
sk89q cf5a5b5b47 Fixed NPE in PlayerInteractEvent regarding infinite stack removal. 2012-03-01 19:52:53 -08:00
sk89q e957f92496 Added sign protection check disable. 2012-03-01 18:51:44 -08:00
TomyLobo 9484bb9941 Fixed some more warnings. 2012-02-25 18:58:22 +01:00
TomyLobo d781f9822f Removed some unused imports. 2012-02-25 18:54:46 +01:00
Wizjany 7845ef2de4 Revert b918b2914.
That breaks it, look at the other use flags before making changes.
2012-02-22 11:36:30 -05:00
zml2008 a9d4ecf33d Improved some group flag defaults to match pre-change behavior 2012-02-20 15:17:34 -08:00
zml2008 6f4a62c7a3 Cleaned up javadoc, deprecated duplicate methods, other cleanup 2012-02-20 15:14:55 -08:00
zml2008 6b4f872742 Added a RegionGroupFlag to evey region flag
Using the /region flag command with -g, the region group that the region flag applies to can be set
Many canBuild checks that occurred with other flag checks have been
replced with this. Some flag checks may be incorrect, and other parts of
this system may need improvement.
2012-02-19 23:31:55 -08:00
zml2008 ef4f00f8f5 Add region information to CommandBook's /whois if CommandBook is eanbled 2012-02-19 21:26:45 -08:00
zml2008 a27deb3936 Removed suppress-tick-sync-warnings setting
This setting often didn't work for people, and has been replaced in CraftBukkit's bukkit.yml with settings.warn-on-overload
2012-02-19 21:24:53 -08:00
TomyLobo 18814c7373 Set WorldGuardPlayerListener.PlayerMoveHandler to default visibility, to fix a warning about unused methods. 2012-02-14 02:32:35 +01:00
TomyLobo 1d9908e1f6 Merged the handlers for EndermanPickup/PlaceEvent into a EntityChangeBlockEvent handler. 2012-02-14 02:32:24 +01:00
TomyLobo 29529e4a06 Removed unused imports. 2012-02-14 02:23:35 +01:00
TomyLobo 74b1003c4c Upped dependency versions for bukkit and worldedit. 2012-02-14 02:21:54 +01:00
NolanSyKinsley 27ffdec323 Fixes shooting onto pvp areas from nopvp areas 2012-02-13 13:54:44 -08:00
zml2008 d9e5fc2b60 [maven-release-plugin] prepare for next development iteration 2012-02-11 16:22:22 -08:00
zml2008 646b3e3064 [maven-release-plugin] prepare release 5.5 2012-02-11 16:22:17 -08:00
zml2008 d3475208ef Add correct git tag defaults to the release plugin config 2012-02-11 16:16:47 -08:00
zml2008 7246da472d Added changelog for 5.5 2012-02-11 16:11:42 -08:00
zml2008 e1f917894a Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader 2012-02-11 12:20:56 -08:00
zml2008 c14d25f860 Now using Bukkit's tagged logging 2012-02-11 12:20:56 -08:00
TomyLobo 57ed91cd28 Updated to new event system 2012-02-11 12:20:56 -08:00
MonsieurApple 47c84beb43 Merge pull request #190 from skeight/master
Fix for bug #728 (Multiverse + Worldguard region with exit flag set)
2012-02-10 11:40:34 -08:00
skeight 1e3032bdce More whitespace fixes... 2012-02-10 11:30:43 -08:00
skeight ed69684843 Fixing up whitespace 2012-02-10 11:29:48 -08:00
skeight 2eea5c7bf7 Fix for bug #728. Multiverse + WorldGuard region exit flag. 2012-02-10 09:06:05 -08:00
zml2008 16da53ae4e Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0 2012-02-06 20:41:39 -08:00
Nicholas Steicke f45464b0d9 Added MySQL region storage method.
Also added ProtectionDatabaseException, and made use of it across the project
Closes #180
2012-02-07 00:11:55 +01:00
Wesley Wolfe 2351ade6fe Fix inconsistent permission check
Closes #188
2012-02-07 00:11:54 +01:00
Turtle9598 c19ccf9278 Made explosions display their animations even when the event was blocked.
Closes #184
2012-02-07 00:11:54 +01:00
zml2008 5c92762ba9 Configuration should be fixed for real. Finally. 2012-02-07 00:11:54 +01:00
zml2008 e665f966e6 These checks may not work correctly, so reverted 2012-02-07 00:11:53 +01:00
zml2008 7dcca7e505 Fixed default entries not appearing in the global configuration 2012-02-07 00:11:53 +01:00
zml2008 e25049b1d6 Added fallback support for those who don't have a version of CommandBook with GodComponent 2012-02-07 00:11:50 +01:00
zml2008 da9bc4a138 Added LIGHTNING flag to DefaultFlag's flagsList
Fixes #1026
2012-02-06 23:06:12 +01:00
zml2008 1224d3b443 Corrected formatting of configuration files
Fixes #1025
2012-02-06 23:05:39 +01:00
zml2008 d33be37694 Removed /god, /heal, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded. 2012-02-06 23:05:30 +01:00
zml2008 551ff26a65 Removed remaining usages of org.bukkit.util.config.Configuration 2012-01-23 16:46:13 -08:00
zml2008 74082f9c68 Updated Bukkit repo 2012-01-20 23:45:39 -08:00
zml2008 b93331e184 Removed some unused configuration options 2012-01-11 18:04:14 -08:00
zml2008 d5d26168b3 Added permission worldguard.region.wand to the region wand
Closes #930
2012-01-10 21:15:00 -08:00
TomyLobo 9d848e222b Fixed ProtectedRegion.compareTo.
It properly implements the Comparable interface now.
In particular, it now fulfills the criterion "sgn(x.compareTo(y)) == -sgn(y.compareTo(x))".
2012-01-09 14:47:59 +01:00
TomyLobo 46a2510e85 Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
Thanks FearThe1337 for noticing.
2012-01-09 14:10:23 +01:00
TomyLobo 0789a453a2 Added a .gitattributes file
This will make your diffs show method names instead of class names on the hunk headers.
2012-01-03 14:47:46 +01:00
zml2008 b30f7fe9c7 Removed usage of Material. 2011-12-31 17:57:09 -08:00
zml2008 525bd199b2 Added exp-drops flag to disable experience drops per-region. 2011-12-31 13:50:43 -08:00
TomyLobo dffd8b59f5 Fixed some warnings. 2011-12-26 11:02:38 +01:00
TomyLobo df206724bd Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
This fixes a warning about raw types.
2011-12-26 10:57:52 +01:00
zml2008 41f31250a9 Added support for fireballs shot by players being blocked by the PVP flag. 2011-12-24 22:49:37 -08:00
zml2008 b29007275f Added dynamic command registration and updated for WE 5.0 API 2011-12-24 22:49:37 -08:00
TomyLobo 35f268319e Split off ender dragon block damage from creeper block damage. 2011-12-18 23:16:12 +01:00
zml2008 6e8a185b63 [maven-release-plugin] prepare for next development iteration 2011-12-17 20:16:48 -08:00
zml2008 120fff1fc4 [maven-release-plugin] prepare release 5.4 2011-12-17 20:16:41 -08:00
zml2008 f879bd5e3a Updated changelog for release 2011-12-17 19:37:24 -08:00
Turtle9598 01f9fd561d Made WorldGuard check to see if both the attacker & defender are in a pvp area. 2011-12-14 20:15:42 -05:00
DerFlash 6802a7d747 Raised the priority of WorldGuard's respawn event listener. 2011-12-11 08:34:14 -08:00
DerFlash b918b29014 Fixed not being able to fill milk buckets in build deny regions
Though added a check for use flag here
2011-12-11 08:29:42 -08:00
zml2008 4895a3313b Forgot to update /slay, /wg report, and /stoplag to new commands system 2011-12-10 12:52:32 -08:00
zml2008 59673c9e66 Simplified autogod config check 2011-12-09 17:57:40 -08:00
Turtle9598 b126255be7 Fixed god mode being assigned to ops if auto enable is false and there is no permissions system
This fixes Bug #873
2011-12-10 01:15:14 +01:00
TomyLobo 606c9f3fd8 Revert "Readded the legacy console sender."
This reverts commit b1256eedcf.
Reason: this breaks if someone modifies CommandSender
The only advantage of having this class is to keep WorldGuard working with old 1.8 builds and pre-1.8 builds.
2011-12-08 14:38:05 +01:00
zml2008 aa306a8df7 Added additional worldguard.stack.damaged permissions to allow stacking of tools with a different damage value 2011-12-07 22:27:00 -08:00
zml2008 b1256eedcf Readded the legacy console sender. 2011-12-07 22:25:41 -08:00
zml2008 4454df341f Commented ProtectedPolygonalRegion.volume() out until someone can fix it. 2011-12-07 21:33:47 -08:00
TomyLobo 5bcac17f1c Fixed compilation with Bukkit >= CB1564.
Sorry, this breaks compatibility with builds < CB1193.
2011-12-08 02:34:26 +01:00
TomyLobo 875b9f326c Removed deprecation of RegionManager.getApplicableRegions.
The underlying functionality has since been implemented.
Also: woo, no more warnings
2011-12-05 06:03:52 +01:00
zml2008 a0d27c6f86 Added WorldEdit as a softdepend. This may fix some issues where WorldEdit's classes cannot be found. 2011-12-04 21:02:39 +01:00
zml2008 1d47d12189 Hopefully fixed WorldConfiguration.getKeys 2011-12-04 10:02:07 -08:00
zml2008 67f78ae8b5 Added per-group region claim maximums 2011-12-04 00:54:33 -08:00
zml2008 5948855da7 Added some more 1.0.0 blocks I forgot 2011-12-02 18:55:29 -08:00
zml2008 f6ec46cdf6 Now actually registering world events 2011-11-30 20:18:03 -08:00
zml2008 ebd2755eb2 Wrong this. 2011-11-30 19:24:53 -08:00
zml2008 78f5827d3d Always the imports... 2011-11-30 19:04:50 -08:00
zml2008 0829070c67 Added some OSX filesystem dust to gitignore and fixed pom.xml comment 2011-11-30 19:01:05 -08:00
zml2008 8b4332e842 Updated for new commands format 2011-11-30 18:59:02 -08:00
zml2008 f904c91443 Updated for Bukkit 1.0 and handling new 1.0 block types in USE flag 2011-11-30 18:59:02 -08:00
Eric Puidokas 944539453e Fixed feed-delay flag 2011-11-29 19:40:08 -08:00
TomyLobo 5856b002df Added .gitignore 2011-11-28 04:39:03 +01:00
TomyLobo 12f68bc227 Fixed a warning 2011-11-28 04:37:30 +01:00
TomyLobo de6e20d60a Improved error messages for group and state flags. 2011-10-30 04:07:37 +01:00
Eric Puidokas 35e6ef5cd8 Implemented edge intersection checking 2011-10-19 23:48:02 +02:00
Eric Puidokas 27251dda2e Refactored and fixed getIntersectingRegions 2011-10-19 23:47:13 +02:00
Eric Puidokas 4bb967ab4a Added Cuboid -> Polygonal intersect tests 2011-10-19 16:21:14 +02:00
Eric Puidokas 7c1f878610 Fixed ProtectedCuboidRegion->ProtectedCuboidRegion intersection checking 2011-10-19 16:21:14 +02:00
Wizjany e8c4c9b218 Fixed sticky pistons not being blocked by the flag in some cases 2011-10-18 17:49:05 -04:00
Eric Puidokas bc37d365ab Added unit tests for ProtectedCuboidRegion.getIntersectingRegions 2011-10-18 02:43:00 +02:00
TomyLobo d9ae1bbd9f Made LegacyConsoleSender compatible with patched Bukkit versions that add methods to CommandSender again.
Don't remove this again, wizjany.
2011-10-16 12:26:22 +02:00
zml2008 e492b30178 Added food level support to godmode and /heal 2011-10-15 23:51:28 -07:00
TomyLobo 920860c298 Fixed some warnings 2011-10-13 15:39:52 -04:00
Wizjany 5f8a6e3423 Workaround for tnt activating as soon as it was placed, regardless of cancellation. 2011-10-11 20:11:07 -04:00
Wizjany 3e7a5056d5 Fixed changelog not getting packaged with the release. 2011-10-09 11:51:43 -04:00
Wizjany 2ec6f04763 Implement non-economy 'buying' of regions via addowner 2011-10-09 11:51:43 -04:00
Wizjany ecef9c9792 Hopefully fix region managers not being created correctly. 2011-10-04 17:43:27 -04:00
Wizjany 810501a508 Added the missing timer to the food flags. 2011-10-04 16:26:54 -04:00
Wizjany 6285a66d76 Fixed allowed/blocked commands not being checked early enough. 2011-10-02 13:36:09 -04:00
zml2008 72e4922e8e Fixed config generation for Windows users 2011-10-02 01:30:10 -07:00
sk89q c1f1885633 [maven-release-plugin] prepare for next development iteration 2011-10-01 20:52:04 -07:00
sk89q 56e514a500 [maven-release-plugin] prepare release 5.3 2011-10-01 20:51:49 -07:00
sk89q 5ede100d56 Changed WorldGuard to use WE 4.7 in the pom.xml. 2011-10-01 20:50:35 -07:00
sk89q f1456b8101 Updated CHANGELOG.txt for 5.3. 2011-10-01 20:26:07 -07:00
Eric Puidokas ef8eb76b16 Added protection.disable-obsidian-generators option 2011-10-01 17:16:45 -04:00
Wizjany b4f2188f72 Added vehicle destroy flag and made players in vehicles subject to movement flags. 2011-10-01 17:16:37 -04:00
zml2008 38c30f5ecd Should fix broken config generation some people have been getting 2011-10-01 16:17:16 -04:00
Wizjany 94c794de6f Trailing whitespace removal 2011-09-27 06:13:19 -04:00
Wizjany fb535e620c Use per-world permissions if supported. 2011-09-26 01:32:48 -04:00
Wizjany 5a42980d78 Fix hunger flags and death messages. 2011-09-26 00:19:57 -04:00
Wizjany 299d2a1f01 That should probably be there 2011-09-25 23:42:50 -04:00
Wizjany 164ff5ea9a Added missing dependency 2011-09-25 23:37:25 -04:00
Wizjany 6c89ef908a Clean up and preparation for release. 2011-09-25 23:31:21 -04:00
Wizjany 3441ae11f2 Added legacy console sender (à la CommandBook). 2011-09-25 22:27:21 -04:00
Wizjany c028331ef9 Added config option and flag to prevent spread of grass. 2011-09-24 22:51:36 -04:00
Wizjany 9343c300cd Added command to flush state manager in case of emergency. 2011-09-24 22:01:07 -04:00
zml2008 63693cc529 Updated for Bukkit changes 2011-09-24 15:57:41 -07:00
Wizjany e6de06aae8 Apply weather settings on world load. 2011-09-22 20:34:38 -04:00
Wizjany 89ce7312d1 Added config options to disable xp drops (even though they should no longer lag) and death messages. 2011-09-21 16:48:56 -04:00
Wizjany b884787377 Fixed 1.8 chests not being blocked and future-proofed some other things. 2011-09-21 15:29:45 -04:00
Wizjany a1427e7743 - Added flags for hunger that do the same that the health ones do (but with hunger)
- Added a config option and a flag to prevent endermen from picking up or placing blocks."
2011-09-20 15:44:54 -04:00
Wizjany 0c02190e19 Added fence gates to USE flag. 2011-09-19 00:58:48 -04:00
zml2008 1f7cce9535 Added experience orbs to the intensive entities list 2011-09-16 20:02:46 -07:00
Wizjany 9fea677b60 Fixed being able to eat protected cake. 2011-09-16 19:18:08 -04:00
Wizjany 6b9a3aff58 Made priming TNT by punching it with flint and steel throw a block break blacklist event. 2011-08-27 16:00:42 -04:00
Wizjany b938271b4d Punching fire in a region without build permissions should no longer douse the fire. 2011-08-27 13:44:40 -04:00
Wizjany 297e06ba71 Fix infinite sign bug. 2011-08-26 22:35:28 -04:00
Wizjany a521ab76a5 Fixed interact and use blacklist events being grouped together incorrectly when right clicking a container. 2011-08-26 20:03:38 -04:00
Wizjany b1c8fc82c4 Fixed piston events being cancelled when they shouldn't be 2011-08-25 18:48:17 -04:00
Wizjany d4ba90c21d Sort /region info player list alphabetically. 2011-08-24 23:48:09 -04:00
Wizjany 14dc868d45 Fixed polygon region edges being unprotected on certain edges. Thanks Droolio. 2011-08-24 17:50:25 -04:00
Wizjany 61a60ecdd6 Fallback to the global region for flags other than StateFlags. Thanks imjake9. 2011-08-24 17:40:01 -04:00
Wizjany 2b56247e21 Allow '/region info' for existing but now illegally-named regions. Thanks Moo0. 2011-08-20 02:22:45 -04:00
Wizjany e0066e6173 Disallowed overwriting regions without specifying redefine. 2011-08-20 02:17:39 -04:00
Wizjany b5b92f91dc Added flag for pistons and fixed a typo in config. 2011-08-20 01:58:46 -04:00
Wizjany 7b12510182 Made sleep flag proactive enough to keep them from blowing the nether up. 2011-08-16 19:24:13 -04:00
TomyLobo e2fc6a3ff0 Fixed heal/damage regions being shifted by half a block towards northeast. 2011-08-15 10:13:39 +02:00
TomyLobo 5acd3a7f6c Fixed warnings. 2011-08-15 09:08:33 +02:00
EduardBaer ce49ca0998 Fix BlockInteractBlacklistEvent 2011-08-11 22:52:20 -04:00
Wizjany eacce487ed Ignore NPE onCreatureSpawn and attempt to get more information about it instead. 2011-08-11 22:52:19 -04:00
Wizjany 602b1d8a27 Bugfixes. Allowed/blocked commands should now respect global flags. Region invincibility/godmode compatibility should now work instead of throwing NPEs. 2011-08-11 22:05:31 -04:00
Wizjany dec469caef Added worldguard.region.flag.regions permissions and flags.<flag>.own for consistency. The old ones will probably be deprecated at some point. Also cleaned up /wg report output slightly. 2011-08-10 20:16:05 -04:00
Wizjany 4194b2ca86 Added the option to disable the use of player move events. Note that this also disables features which use it such as the region entry/exit and greeting/farewell flags. 2011-08-10 20:16:05 -04:00
Wizjany 17741822c1 Allow invincibility flag to disable god mode (when set to deny) unless the player has the worldguard.god.override-regions permission. 2011-08-10 17:43:46 -04:00
Wizjany 3757056e46 Fixed up explosion handling. 2011-08-09 21:02:26 -04:00
Wizjany 0eb68ef864 Added min and max health flags to go along with the other healing flags. Also organized the flag list for readability. 2011-08-09 19:48:10 -04:00
Wizjany 3f77a9b721 Made /stack respect max stack sizes unless the user has worldguard.stack.illegitimate which will stack normally unstackable items. 2011-08-08 12:46:18 -04:00
Wizjany 321b3acf0a Buckets now check the region that the water will end up in, not the block that was clicked 2011-08-08 09:12:10 -04:00
Wizjany dfbbeeb473 Moved around projectile damage events in accordance to Bukkit 2011-08-07 18:42:32 -04:00
Wizjany 31d3f2e7c6 Cancel scheduled tasks on disable 2011-08-07 17:08:18 -04:00
Wizjany 40a66b9be4 Updated snow fall and added flags for snow/ice forming/melting and mushroom growth 2011-08-06 11:29:14 -04:00
sk89q 049a1fb2ed Merge pull request #134 from halvors/cleanup
Cleanup, commented out some unused fields.
2011-07-17 10:50:36 -07:00
halvors 3fc68af05f More imports cleanup. 2011-07-16 23:07:29 +02:00
halvors c3f0c8a7a1 Oops, missed some changes. 2011-07-16 22:39:30 +02:00
halvors cba1a95838 Cleanup, commented out some unused fields. 2011-07-16 22:26:10 +02:00
sk89q 345f4a2e0e Removed some debugging messages. 2011-06-29 17:00:58 -07:00
sk89q 162d53b66e Made TNT blocking more aggressive. Also fixed explosion event. 2011-06-29 16:59:31 -07:00
sk89q bed6782a00 Made /stoplag handle TNT removal better. 2011-06-29 16:17:36 -07:00
Wizjany d90b960597 Moved fireball handling to somewhere that actually gets called by it... 2011-06-29 15:43:01 -04:00
Wizjany 3325feb1cb Re-enable god mode on a reload for those who need it. 2011-06-28 01:05:51 -04:00
Wizjany 62d181eb81 Made it easier for plugins to access the API without using WorldEdit vectors 2011-06-28 00:59:16 -04:00
Wizjany 1e24e9c128 Added config option to block fireball world damage only. Thanks Qalthos 2011-06-28 00:58:13 -04:00
sk89q cfffba25cf Added regions.invincibility-removes-mobs so you can turn on invincibility without creating the possibility about farming. 2011-06-27 13:41:27 -07:00
sk89q 671b4fe2db Added region invincibility flag. 2011-06-27 13:36:43 -07:00
sk89q 5b300bc5d1 Changed the per-world configuration loader to also put configuration entries in the main configuration. 2011-06-27 13:13:31 -07:00
sk89q a5332c2166 Added player-damage.disable-tnt-damage. 2011-06-27 12:57:33 -07:00
sk89q 141d5ccd25 [maven-release-plugin] prepare for next development iteration 2011-06-27 12:09:57 -07:00
sk89q c75b9c2328 [maven-release-plugin] prepare release 5.2.2 2011-06-27 12:09:47 -07:00
sk89q 0863db8cf0 Changed configuration saving so empty lists will be added to the configuration files. 2011-06-27 12:09:03 -07:00
sk89q 53d6a272e6 [maven-release-plugin] prepare for next development iteration 2011-06-27 11:47:48 -07:00
sk89q 71467a7ae7 [maven-release-plugin] prepare release 5.2.1 2011-06-27 11:47:37 -07:00
sk89q 56fa3458ab Updated CHANGELOG.txt for 5.2.1. 2011-06-27 11:37:22 -07:00
sk89q 82e04ac4e5 Changed /region {add|rem}{member|owner} to allow putting owners/members on the global region. 2011-06-27 11:23:33 -07:00
sk89q 564d4442fc Added a bunch of unit tests for regions. 2011-06-27 11:10:20 -07:00
sk89q df8fdd086b Fixed some flag algorithm issues, added the possibility of owners and members on the global region in order to affect build. 2011-06-27 11:10:20 -07:00
sk89q a31476251e Fixed DefaultDomain.size() not counting players. 2011-06-27 11:10:19 -07:00
sk89q 360a655627 Added the ability to add owners/members to the global region for handling guest groups. 2011-06-27 11:10:19 -07:00
sk89q 3b871b9c00 Added more region unit tests. 2011-06-27 11:10:19 -07:00
sk89q 65834a2087 Undeprecated ApplicableRegionSet.allows(StateFlag) 2011-06-27 11:10:19 -07:00
e9d85da691 Merge pull request #107 from Moo0/infobounds
Add region bounds to "/region info"
2011-06-27 09:31:02 -07:00
sk89q cfa78af654 [maven-release-plugin] prepare for next development iteration 2011-06-27 00:00:47 -07:00
sk89q 45d9119150 [maven-release-plugin] prepare release 5.2 2011-06-27 00:00:38 -07:00
sk89q ea487eb6a4 Fixed the %online% macro requiring a player. 2011-06-26 23:41:30 -07:00
sk89q 4e295ea1eb Updated for 5.2. 2011-06-26 23:20:43 -07:00
sk89q 32265414bd Added Javadocs, cleaned up comments. 2011-06-26 23:19:49 -07:00
sk89q 80e706e962 Improved the API. 2011-06-26 22:50:21 -07:00
sk89q 110838715b Gave the ability to use color colors and macros in greeting and farewell messages. 2011-06-26 21:49:34 -07:00
sk89q b90334c8a8 Made WorldGuard catch setHeader() not being yet defined. 2011-06-26 21:49:33 -07:00
sk89q 3ce0530d5f Updated for 5.2. 2011-06-26 21:49:33 -07:00
sk89q 7eaa84d5b1 Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread, disable-snow-melting, disable-ice-formation. 2011-06-26 21:49:32 -07:00
sk89q ad325dfedb Added paintings to blacklist support. 2011-06-26 21:49:32 -07:00
sk89q 5bb7eb6f01 Added default.disable-health-regain. 2011-06-26 21:49:32 -07:00
sk89q 342cfc0801 Added auto-invincible-permission setting, which lets you use the permission 'worldguard.auto-invincible' to become invincible. 2011-06-26 21:49:31 -07:00
sk89q f5c6a9f507 Flames won't appear if you are /god'ed now. 2011-06-26 21:49:31 -07:00
e843ff372e Merge pull request #113 from Moo0/limitoverride
Region limit override permission.
2011-06-26 19:35:40 -07:00
sk89q ed27ffed65 Updated the blacklist with a new ignore-perms option. No more groups! Use permissions! 2011-06-26 18:36:06 -07:00
sk89q 7995ecd867 Updated CHANGELOG.txt. 2011-06-26 17:33:59 -07:00
sk89q fcef6679c4 Updated README.html. 2011-06-26 16:48:51 -07:00
sk89q 742b6a2e27 Made negative healing possible. 2011-06-26 16:39:41 -07:00
sk89q 258fbc8870 Improved the entry/exit flags so that it's harder to break it. Thanks to Siriuo. 2011-06-26 16:29:28 -07:00
sk89q 0fa43ee287 Added a warning about modifying region database files manually. 2011-06-26 15:11:05 -07:00
sk89q fb39261dc7 Fixed floating point inaccuracy in onPlayerMove(). 2011-06-26 14:38:56 -07:00
sk89q 7fce4bf53e Added exit flag to deny exiting a region. 2011-06-26 14:11:11 -07:00
sk89q 13840cf61b Changed the configuration header messages to be more helpful to new users. 2011-06-26 12:59:20 -07:00
sk89q e26f6b5e8d Added 'entry' flag to deny entry. 2011-06-26 12:32:01 -07:00
sk89q 767c49f9fa Added region command whitelisting and the bypass for command checks. 2011-06-26 10:45:12 -07:00
sk89q c9178da608 Added command blocking. 2011-06-26 10:40:08 -07:00
sk89q 855bc59a53 [maven-release-plugin] prepare for next development iteration 2011-06-26 03:15:25 -07:00
sk89q 798c22e94b [maven-release-plugin] prepare release 5.1.1 2011-06-26 03:15:15 -07:00
sk89q ea3be11294 Blanked default configuration files. 2011-06-26 03:13:34 -07:00
sk89q 335073b3b0 [maven-release-plugin] prepare for next development iteration 2011-06-26 03:02:11 -07:00
sk89q 2b6ee344b7 [maven-release-plugin] prepare release 5.1 2011-06-26 03:02:02 -07:00
sk89q 8f55b82e2f Updated for 5.1. 2011-06-26 02:52:40 -07:00
sk89q ba9cd1f3e2 Updated the README.html. 2011-06-26 02:52:13 -07:00
sk89q e0e7ae98e7 Changed configuration files to save and also to inherit from the main configuration. 2011-06-26 02:24:50 -07:00
sk89q b05e439da9 Cleaned up pom.xml and updated maven-assembly-plugin to 2.2.1. 2011-06-26 01:31:59 -07:00
sk89q fb5dbbdf58 Removed .gitignore. 2011-06-26 01:28:24 -07:00
sk89q 9cb9dd0a58 Updated the README.html. 2011-06-26 01:27:55 -07:00
sk89q 276d42561e Added more aggressive TNT flag check. 2011-06-26 00:47:58 -07:00
sk89q 44b98165ba Added region protection to sign change event. 2011-06-26 00:24:09 -07:00
sk89q b5088340fd Fixed deny-spawn. 2011-06-25 23:27:01 -07:00
sk89q b7dd63ebd9 Changed event registration to catch errors. 2011-06-25 21:46:14 -07:00
Wizjany ba376a6326 Registering some other new events 'safely' 2011-06-22 21:29:22 -04:00
sk89q 87a43e8e8f Made SNOW_FORM be registered programatically so it can be used on CraftBukkit versions lacking that. 2011-06-22 08:46:37 -07:00
sk89q b62ada53c3 Re-ordered plugin enable process. 2011-06-22 08:43:10 -07:00
sk89q 4f3198b1bd wiz makes a good point -- PROBABLY should not delete players. 2011-06-20 19:35:14 -07:00
sk89q c9f99e0903 Added /stoplag or /halt-activity to cease all intensive operations (such as fire spread, water flow, mob spawning, etc.) and to remove mobs (except wolves) and item drops proactively for those situations when you (or someone else) messes up really badly. 2011-06-20 19:25:05 -07:00
Moo0 3b4c58b721 Add region limit override permission. 2011-06-20 17:22:33 +01:00
Wizjany 6496bbd87f Added config option to disable mob damage for people not using regions 2011-06-15 13:02:59 -04:00
Wizjany 4ad8d362f7 Reverted change to use flag 2011-06-12 14:36:26 -04:00
Wizjany d9aeb6afaa Fixed NPE in last commit 2011-06-11 16:24:06 -04:00
Wizjany d971389746 Prevent players from using bonemeal on grass if they aren't allowed to build in a region 2011-06-11 14:13:46 -04:00
sk89q 233a2bdbe7 Fixed an important bug with the algorithm for handling region priorities. 2011-06-11 01:21:08 -07:00
sk89q 2277183330 Added some more region priority unit tests. 2011-06-11 01:21:08 -07:00
Wizjany b2cd3d31fd Standardizing override permission nodes (with backwards compatibility) 2011-06-10 16:00:14 -04:00
Wizjany 02f6b3be42 Fixed USE flag being DENY in undefined regions 2011-06-10 15:50:03 -04:00
Wizjany 22e84321fc Removed duplicate handling of lighter fire 2011-06-10 01:41:59 -04:00
Wizjany c472dc89ad Changed the way some flags were handled and canceled 2011-06-09 17:02:19 -04:00
Wizjany b89d9d44b0 Now with 99.9% less Unknown Paste ID 2011-06-09 00:12:06 -04:00
Wizjany a2c21f8ceb Made anti-dumb wolf checks only apply to tamed wolves 2011-06-08 23:55:07 -04:00
sk89q e35596b0fa Allowed blocking weapon usage with the blacklist. 2011-06-07 16:08:50 -07:00
Wizjany b95a7f063b Fixed disabling durability resetting things which use durability otherwise 2011-06-07 16:32:43 -04:00
sk89q e4bbd36d47 <= 0 health? It's too late bby 2011-06-06 16:53:11 -07:00
sk89q 9790ab29a2 Now a very proactive (but not still reserved) infinite stack checker. 2011-06-06 14:46:06 -07:00
sk89q 24cc2d3b36 Changed the proactive infinite stack check to occur on inventory open. 2011-06-06 14:35:57 -07:00
sk89q 12779699e3 Improved the infinite item stack remover by making it a bit more proactive. 2011-06-06 14:31:17 -07:00
sk89q 2188690d20 Changed leave messages to be printed BEFORE enter messages. Suggested by Protected. 2011-06-06 11:30:00 -07:00
sk89q 7059fdfd9e Removed old/redundant code. 2011-06-06 11:29:11 -07:00
sk89q 9e1bde4b00 Merge remote-tracking branch 'remotes/origin/master' 2011-06-06 11:15:40 -07:00
sk89q 45790b60b0 Restored the configuration class name change so plugins don't have to be updated. 2011-06-06 11:08:38 -07:00
sk89q c5f3a27d6b Rewrote greeting/farewell and notify-enter/notify-leave flags. 2011-06-05 17:18:27 -07:00
sk89q d9136aa407 Optimized flags scheduler. 2011-06-05 16:38:28 -07:00
sk89q 183f48a998 Rewrote how healing flags were handled. 2011-06-05 16:31:42 -07:00
Wizjany 3c5bc507a5 Added trap doors to USE flag 2011-06-03 18:05:28 -04:00
Wizjany 548dd0365c Fixed another infinite sign... 2011-06-02 19:34:29 -04:00
Wizjany 4591fc603f Added permission nodes as an alternative to wg-invincible and -amphibious groups. 2011-05-31 19:58:12 -04:00
Wizjany 26946feecc Merge leafdecay flag from zml2008 2011-05-27 19:06:38 -04:00
sk89q dd14f3c469 Fixed priorities and parent-child regions, I believe. More testing is required. Removed dated CSVDatabaseTest. 2011-05-26 21:55:23 -07:00
Moo0 69af41f1e5 Remove permission. 2011-05-24 16:25:45 +01:00
sk89q 474562455d Abstracted chest protection. 2011-05-23 23:32:45 -07:00
sk89q c75d612541 Cleaned up code. The configuration classes were also renamed as they did much more than just configuration. 2011-05-23 23:32:44 -07:00
sk89q 8de6ce9868 Cleaned up code from a merge. 2011-05-23 23:30:54 -07:00
sk89q 97bde50708 Fixed some chest protection issues. 2011-05-23 23:30:54 -07:00
sk89q b23e35cf26 Improved chest-sign protection. 2011-05-23 23:30:53 -07:00
sk89q b58e04707d Timer flags timer removed. It will be restored when it gets rewritten to not leak memory and to handle messages better. 2011-05-23 23:30:53 -07:00
MonsieurApple 846cf63268 Merge pull request #109 from wizjany/master
Ghast fireballs and explosion cancelling
2011-05-23 20:04:24 -07:00
Wizjany 4850bdefdf Added config option to disable explosion-caused damage to players. 2011-05-23 22:26:02 -04:00
Wizjany 424b580eb9 Added ghast fireball handling (instead of grouping with tnt) and fixed god mode player ignition. 2011-05-23 22:25:56 -04:00
MonsieurApple 7f8ad468ca Merge pull request #108 from Moo0/derp
Bug in ProtectedCuboidRegion/getIntersectingRegions.
2011-05-23 13:55:05 -07:00
Moo0 e07e2bd7d1 Someone used the wrong variable in a for. 2011-05-23 21:44:02 +01:00
Moo0 7074963fb1 Add region bounds to "/region info" 2011-05-23 19:48:02 +01:00
MonsieurApple 88acbe655d Merge pull request #106 from kuyanatan/master
Fixed config misspell
2011-05-21 11:15:51 -07:00
Natan 903ebc68a4 Worldgurad != worldguard. 2011-05-21 10:48:07 -07:00
MonsieurApple 49bdccf020 Merge pull request #103 from wizjany/master
Fixed some derpy fire handling
2011-05-17 07:05:09 -07:00
MonsieurApple ba3818884d Merge pull request #99 from Moo0/listbyname
Filter "/region list" by user.
2011-05-16 17:11:13 -07:00
MonsieurApple 64ce904ec1 Merge pull request #104 from wizjany/opPerms
Added config for op permissions
2011-05-16 17:09:59 -07:00
Wizjany 8c5f7ef020 Added config for op permissions 2011-05-16 20:03:45 -04:00
Wizjany 98426f6dcc Added config for op permissions 2011-05-16 19:43:04 -04:00
Wizjany f3ec873ac2 Fixed some derpy fire handling. 2011-05-16 16:27:17 -04:00
MonsieurApple 30961483e1 Merge pull request #101 from wizjany/master
Fixed some commands not accepting flags they should
2011-05-14 11:42:01 -07:00
Wizjany 33e0750959 General commands now use flags as intended 2011-05-14 13:19:02 -04:00
MonsieurApple e59a07e232 Merge pull request #100 from wizjany/master
Painting events and snow fall flag
2011-05-13 05:20:20 -07:00
Wizjany 3b05b9be11 Added support for painting and added a flag for snow falling. 2011-05-13 00:37:48 -04:00
Moo0 943bbd9889 Show regions user is member of, as well as those user is owner of. 2011-05-08 18:55:48 +01:00
Moo0 763cf8dbda Add ability to filter '/region list' by user. 2011-05-08 18:44:08 +01:00
sk89q 5117518d8f Cleaned up code, removed OpenCSV code from WorldGuard. Now it's a dependency (that's compiled into the .jar). 2011-05-03 15:36:04 -07:00
sk89q 936996da17 Moved the unit tests to their proper place as recommended by the Maven gods. 2011-05-03 02:07:21 -07:00
sk89q 019a7e59b7 Alright, here's a surprise. Everything is now on Maven. 2011-05-03 02:04:55 -07:00
sk89q 428a47f889 Merge branch 'master' of https://github.com/wizjany/worldguard 2011-05-03 01:31:49 -07:00
Steven Mattera 2be2cb19b2 Uncommented line 445 on WorldGuardEntityListener 2011-05-03 01:30:07 -07:00
Steven Mattera 66ee09d050 Fixed TimedFlagsTimer to enable HEAL_DELAY,HEAL_AMOUNT,GREETING,FAREWELL,NOTIFY_GREET,NOTIFY_FAREWELL, and PASSTHROUGH Flags. 2011-05-03 01:30:07 -07:00
Steven Mattera 906dab28c1 Added MOB_SPAWNING state flag. 2011-05-03 01:30:06 -07:00
6db8e1d842 Merge pull request #94 from yetanotherx/chest-blacklist.
Don't deny placing a blacklisted item if the block clicked is a chest.
2011-05-03 01:32:00 -07:00
Yetanotherx a665e86096 Don't deny placing a blacklisted item if the block clicked is a chest. People often complain that "i was just trying to open my chest" when they were holding water. 2011-04-30 12:26:39 -04:00
sk89q b7481dbd2e Updated config. 2011-04-24 13:14:12 -07:00
Wizjany b1e509c6f8 Updated for 1.5 and added existing lightning protection. 2011-04-25 04:08:28 +08:00
Wizjany 1f69622a34 Added a lot of missing things to player listener. 2011-04-25 04:06:48 +08:00
Wizjany 215b2b5f75 Added config to stop players from trampling crops. Animals don't work yet (blame CraftBukkit) 2011-04-25 04:04:48 +08:00
Wizjany 1e8c91e92f Added override for flint and steel blocking. 2011-04-25 04:04:47 +08:00
Wizjany 19d447d67d Added handling for weather events. Depends on my craftbukkit pull request. 2011-04-24 15:55:26 -04:00
Wizjany 925fa2ee1b Updated for 1.5 and added existing lightning protection. 2011-04-24 15:53:32 -04:00
Wizjany 1cedf0e9a0 Added a lot of missing things to player listener. 2011-04-23 19:50:58 -04:00
Wizjany ca8bb7f5f0 Added config to stop players from trampling crops. Animals don't work yet (blame CraftBukkit) 2011-04-15 00:20:15 -04:00
Wizjany 9e15a4a557 Added override for flint and steel blocking. 2011-04-14 21:17:11 -04:00
sk89q af5d0c4b0e Re-added cake eat blocking on left click. 2011-04-13 03:11:05 -07:00
sk89q 08ab359534 Fixed region priorities, but it needs a test. 2011-04-13 03:07:17 -07:00
Steven Mattera 28c44e0b2f Added MOB_SPAWNING state flag. 2011-04-13 18:07:13 +08:00
Moo0 7038f49a1a Fix for "/region claim" claiming overlapping region when none exists. 2011-04-13 18:05:12 +08:00
sk89q af25c15286 Merge branch 'master' of https://github.com/wizjany/worldguard 2011-04-13 03:00:27 -07:00
sk89q ffc5281d59 Added protection.remove-infinite-stacks. 2011-04-11 12:34:11 -07:00
sk89q ad659cd32e Fixed a major bug with the sign chest protection. It replaced the second line of the sign with "[Lock]". 2011-04-11 11:55:12 -07:00
sk89q afd3cbd311 Added sign chest protection (needed it for my server). Just put [Lock] on the first line and names on the next three. The first name line must be the sign creator's, so you can track who made what. Friend lists are not yet supported. People with names longer than 15 characters (I believe 16 is the max.) are out of luck. 2011-04-11 10:13:42 -07:00
sk89q a5a5f7e24a Made /wg report look better. 2011-04-09 02:25:47 -07:00
sk89q 1e203b58c3 Fixed a bug, partially, regarding unloaded worlds. 2011-04-07 00:22:15 -07:00
Wizjany 104b7c2cf2 Fixed falling into void and wolves still taking damage. Requires Craftbukkit 638+ 2011-04-07 00:35:52 -04:00
Wizjany 355c89ecab Added missing default global config option to file. 2011-04-07 00:35:52 -04:00
sk89q 1241e18f9c Added /worldguard report [-p] 2011-04-03 17:20:13 -07:00
sk89q 6566acf7eb Added more aliases to /region subcommands. 2011-04-03 11:05:48 -07:00
sk89q 4332ed92f2 Added /region select. 2011-04-03 11:04:18 -07:00
sk89q 2e7f96aab0 Fixed /region setparent. 2011-04-03 10:35:06 -07:00
Wizjany 3cb9b90ef0 Added config to disable damage from falling into the void. 2011-04-03 05:48:32 -04:00
sk89q 21a04cc8c8 Added anti-wolf-dumbness. 2011-04-02 22:44:45 -07:00
sk89q dcc1b59627 Fixed region bypass. 2011-04-02 19:46:26 -07:00
sk89q e8fb3e6d24 Added a region high frequency flags setting to disable high frequency flags. Enable it if you've got the system resources to support it. This covers the fire spread, lava fire spread, lava flow, and water flow flags. 2011-04-02 18:45:11 -07:00
sk89q 93d084d5ba Caught CircularInheritanceException exception. 2011-04-02 18:02:16 -07:00
sk89q e45ecf9c86 Added the ability to clear parents with /region setparent. 2011-04-02 18:01:59 -07:00
sk89q beb10e22f2 Changed the /region flag flags list to check permissions. 2011-04-02 18:00:48 -07:00
sk89q 64b12f8497 Improved vehicle place flag to handle boats. 2011-04-02 17:57:58 -07:00
sk89q 0821a08df2 Updated /god to remove fire. 2011-04-02 17:53:09 -07:00
sk89q 50870a9b32 Fixed flag resolution algorithm not catching NoSuchElementException correctly. Now the spawn flag works. Note that the IDs for the spawn and farewell/greeting flags were changed. 2011-04-02 17:49:11 -07:00
sk89q b823446e28 Fixed flags, added separate lava flow flag. 2011-04-02 17:43:01 -07:00
sk89q 48b00874e5 Removed extra space. 2011-04-02 17:23:56 -07:00
sk89q deba6c79f3 Re-implemented the region spawn location flag. 2011-04-02 17:21:05 -07:00
sk89q c0be10ad94 Changed /god to mention /ungod. 2011-04-02 17:05:11 -07:00
sk89q 5010d35ff3 Added a basic API. 2011-04-02 16:26:35 -07:00
sk89q 42d26a1f4f Moved blacklist logger configuration back to be per-world. 2011-04-02 16:24:37 -07:00
sk89q 92c25d2df4 Updated default configuration file. 2011-04-02 16:22:27 -07:00
sk89q 5b5349fc34 Improved amphibious stuff, added pumpkin scuba. 2011-04-02 16:07:59 -07:00
sk89q cc6ac93b7a Fixed auto-god mode and auto-amphibious mode. 2011-04-02 15:58:52 -07:00
sk89q 1b843b3586 Fixed /god. 2011-04-02 15:54:41 -07:00
sk89q 3b9a426547 Fixed some flags and permissions. 2011-04-02 15:39:44 -07:00
sk89q 989ba0103d Added snakeyaml.jar to the build.xml file. 2011-04-02 14:19:01 -07:00
sk89q b584b996a3 Fixed parenting not saving. 2011-04-02 14:11:12 -07:00
sk89q 896c7fc467 Improved the cake processing mix to be less bitter. 2011-04-02 13:48:40 -07:00
sk89q bd2393342f Fixed the blacklist. 2011-04-02 13:35:57 -07:00
sk89q 762b10cb17 Fixed CSV->YAML conversion. 2011-04-02 12:15:40 -07:00
sk89q 9322eedb4e Fixed an error with the legacy flags. 2011-04-02 11:48:06 -07:00
sk89q 4e2a902b75 Fixed flag resolution algorithm. 2011-04-02 11:47:14 -07:00
sk89q d3b8bd6f39 Fixed more default flag values. 2011-04-02 10:41:33 -07:00
sk89q 0fa64dad7f Fixed the default values for the flags. 2011-04-02 10:40:30 -07:00
sk89q 792e8663e6 Re-implemented the block/player interact hooks that changed in Bukkit recently. 2011-04-02 10:17:02 -07:00
sk89q 4dc999b0d9 Fixed up default configuration files. 2011-04-02 02:40:01 -07:00
sk89q 7c15c2de41 Re-added /worldguard set of commands. 2011-04-02 02:33:23 -07:00
sk89q 43137c3e53 Rolled in Stefan's changes. 2011-04-02 02:07:42 -07:00
sk89q 521ecd438e Added proper support for global regions and a region ID validation regex. 2011-04-02 02:03:32 -07:00
sk89q 949c6599b3 Disallowed '.' in region IDs. 2011-04-02 01:41:13 -07:00
sk89q ea79efe693 /stack re-added. 2011-04-02 01:36:05 -07:00
sk89q b4a89462f8 /locate re-added, but it doesn't seem to work. (Potential Bukkit bug.) 2011-04-02 01:26:22 -07:00
sk89q 70bd3d0e9a Re-added /slay and /heal. 2011-04-02 01:20:11 -07:00
sk89q c33474e0f9 Added /god back in. 2011-04-02 01:16:10 -07:00
sk89q 3d0ebe5c91 Made /stopfire and /allowfire say the world that it was toggled for. 2011-04-02 00:42:19 -07:00
sk89q a9ab0702e0 /region update added. 2011-04-02 00:33:07 -07:00
sk89q 9272741a3c Added more region commands. 2011-04-02 00:18:28 -07:00
sk89q 2b72a99608 Re-added /region setparent. 2011-04-01 23:39:13 -07:00
sk89q 4c38e10fe1 Re-added /region save and /region load. 2011-04-01 23:31:28 -07:00
sk89q 7806b48d34 Re-added /region remove. 2011-04-01 23:23:23 -07:00
sk89q 9803d6b731 Improved YAML loading/saving. 2011-04-01 22:46:45 -07:00
sk89q 649db3aca2 Fixed an extraneous space in an insignificant message. 2011-04-01 22:46:26 -07:00
sk89q b75ab68e7a Completed marshalling implementations for all the flags and changed the LocationFlag to a VectorFlag. 2011-04-01 22:34:31 -07:00
sk89q 8ffc42d349 Added marshalling implementations for most of the flags, fixed configuration issue in WorldConfiguration. 2011-04-01 22:21:30 -07:00
sk89q 145c9750cd Added YAML protection database driver. 2011-04-01 22:12:29 -07:00
sk89q 12647c3a6c Project files and .gitignore should not be in the repo. 2011-04-01 18:28:23 -07:00
sk89q 056f8a57c7 Removed JSON database support. Restored flag loading support to the CSV database so that they can be ported over to the new format. 2011-04-01 18:24:34 -07:00
sk89q 94f0acf9f3 Fixed permissions not being loaded. 2011-04-01 18:05:24 -07:00
sk89q 40bf65d56a Updated for latest Bukkit. 2011-04-01 17:51:33 -07:00
sk89q 726e3a5c20 Added /region flag. DON'T USE THIS VERSION ON A PRODUCTION SERVER. 2011-04-01 13:39:29 -07:00
sk89q d1cab0da7f More stuff works. 2011-03-30 12:01:11 -07:00
sk89q ede4873c6a More progress. 2011-03-27 23:49:30 -07:00
sk89q fd8c827bf1 Updated createDefaultConfiguration() to create parent directories. 2011-03-27 11:18:30 -07:00
sk89q 20afbdf264 More is working! DO NOT USE THIS YET or I will have to personally slap you. 2011-03-26 19:33:29 -07:00
sk89q 0dd92e5189 Work in progress. EVERYTHING IS BROKEN. 2011-03-26 16:59:06 -07:00
sk89q 4b1ba5acb0 Fixed permissions not being load()ed. 2011-03-22 09:34:40 -07:00
sk89q edc94594eb Some cleanup. 2011-03-17 02:31:38 -07:00
DarkLiKally 837efb75d1 Updated iConomy.jar and added quickfix for timed flags crash 2011-03-14 12:01:43 +01:00
DarkLiKally 252208a479 Fixed DoubleRegionFlags 2011-03-10 16:18:30 +01:00
Redecouverte 2641cb7d4f fixed permissions for commands, hasPermission() does "worldguard." + perm so do prefix with "worldguard." 2011-03-09 13:36:10 +01:00
Redecouverte 9c91f06c5d re-added Init() functions to flags class, do not remove it, or the flags class will NOT be loaded on startup which will cause unexpected behaviour 2011-03-09 13:30:07 +01:00
sk89q 7fab4144ae Fixed bad merge. 2011-03-08 10:06:40 -08:00
sk89q 81eb2cad1a Some initial code reorganization. Todo: Have CSVDatabase handle flags so they can be ported over, and do the commands system a cleaner way. 2011-03-08 10:03:49 -08:00
DarkLiKally eda7db7aca Updated MobType to CreateType 2011-03-08 08:54:33 +01:00
DarkLiKally 45a7653dcd Updated iConomy.jar to 4.4.3 (Arcadia) 2011-03-07 08:38:39 +01:00
Valentin Churavy 36fef995e4 fixed nullpointer exception in GlobalRegionManager.java 2011-03-06 15:25:41 +01:00
DarkLiKally af2e862ca2 Updated iConomy.jar to 4.3(.1) 2011-03-04 12:04:30 +01:00
DarkLiKally 7f48ce06be Updated iConomy.jar to 4.2 2011-03-03 10:02:39 +01:00
Redecouverte 1c5ae9ef67 make sure the Flags class is always loaded on startup 2011-03-02 17:37:31 +01:00
Redecouverte 3bf18c41bb flags are now type-safe 2011-03-02 17:24:33 +01:00
DarkLiKally 7ab49f1909 Fixed command /buyregion 2011-03-02 16:44:02 +01:00
DarkLiKally 44b5e5548d added message if player has not enough money for the region 2011-03-02 16:28:01 +01:00
DarkLiKally 50ca9d129b Updated /buyregion command 2011-03-02 15:57:37 +01:00
DarkLiKally 7b725d655c Fixed sign alternative for /buyregion 2011-03-02 13:43:21 +01:00
DarkLiKally 3e9c7aa74b Fixed error with player-eat-check 2011-03-01 19:58:54 +01:00
DarkLiKally 916ed2652e Added check if player eats something 2011-03-01 19:43:50 +01:00
DarkLiKally 59a1726e8c Fixed heal flag (for max. player health(20)) 2011-03-01 15:18:34 +01:00
DarkLiKally 20f91b5258 Fixed denyspawn flag 2011-03-01 12:45:20 +01:00
Redecouverte 353ce7e825 removed legacy comments 2011-02-28 21:15:41 +01:00
Redecouverte 94be4ab18e updated permissions_list.txt 2011-02-28 20:39:30 +01:00
DarkLiKally df7409607f Added administrator notification functionality and flag for greets and farewells 2011-02-28 20:28:14 +01:00
Redecouverte 79b937e8d2 yet another fix for state flag fallback 2011-02-28 19:57:20 +01:00
DarkLiKally 83c6c9c743 Removed unused imports from WorldGuardVehicleListener.java 2011-02-28 19:47:25 +01:00
Redecouverte 6a2affc0f9 new global flags are now read from .yml files 2011-02-28 19:36:46 +01:00
Redecouverte 8ad713c183 implemented passthrough flag 2011-02-28 19:32:59 +01:00
DarkLiKally f8fb746f64 Fixed WorldGuardVehicleListener.java 2011-02-28 19:19:45 +01:00
DarkLiKally c6b3507bf4 Added placeVehicle Flag 2011-02-28 19:15:37 +01:00
Redecouverte 2dc95da6e0 moved registerEvents() int event listeners 2011-02-28 19:05:07 +01:00
Redecouverte 8f9bfcf474 enum flags now also take lovercase names 2011-02-28 18:51:37 +01:00
Redecouverte a8b54757e9 fixed /region info and region flag fallback 2011-02-28 18:36:19 +01:00
Redecouverte 19cfd9edc6 renamed new map to not confuse gson 2011-02-28 18:14:44 +01:00
Redecouverte 03d0f962e5 some more fixes for the new flag containers 2011-02-28 18:08:52 +01:00
Redecouverte 0ff24627ca fixed npe with new flag containers 2011-02-28 17:47:51 +01:00
Redecouverte 4d8cd430b7 renamed isFlagAllowed() to isStateFlagAllowed() 2011-02-28 17:25:31 +01:00
Redecouverte 30b0e5d0b1 rewrote flag system to end the madness 2011-02-28 17:19:51 +01:00
Redecouverte cdf067bba8 fixed crash in removeRegion 2011-02-28 11:00:37 +01:00
Redecouverte e4d05e14ac now using new command system 2011-02-28 10:45:00 +01:00
DarkLiKally 82dc78523f Added sign alternative for /buyregion
Added flag for lever and button usability
2011-02-28 10:42:34 +01:00
Redecouverte 676e744c02 replaced string comparison with instanceof 2011-02-28 00:52:26 +01:00
Redecouverte 0d80265ff2 updated permissions example in config.yml, fixed typo in CommandTpRegion, removed debug output in RegionCommandHandler 2011-02-28 00:49:24 +01:00
DarkLiKally 442521a73c Added getIntersectingRegions() method for polygonal and cuboid regions 2011-02-27 21:03:46 +01:00
Redecouverte dcef083e30 fixed worldguard.notify and worldguard.bypass permissions, optimized getApplicableRegionSet() calls 2011-02-27 19:31:49 +01:00
Redecouverte 162cd20f80 added permissions worldguard.region.priority.own and worldguard.region.priority.all 2011-02-27 18:43:39 +01:00
Redecouverte c74433422a region priority is now set correctly in /region claim 2011-02-27 18:40:32 +01:00
Redecouverte f338650b24 hopefully final fix for tnt block 2011-02-27 18:20:07 +01:00
Redecouverte 65c0d77d3e updated protection classes for getIntersectingRegions() 2011-02-27 18:16:09 +01:00
Redecouverte 09a150b6e9 updated config.yml, removed old permissions 2011-02-27 17:59:01 +01:00
Redecouverte 06173a446a blacklist can now be used as whitelist 2011-02-27 17:48:07 +01:00
Redecouverte d6adea447e json data is now reloaded if manually edited 2011-02-27 17:25:13 +01:00
Redecouverte d042b785ed updated tnt fix, updated respawn teleport 2011-02-27 17:00:34 +01:00
Redecouverte 881846d301 fixed tnt block npe thanks to Brettflan, added claim-only-inside-existing-regions and max-region-count-per-player region options, updated ApplicableRegionSet for regions 2011-02-27 16:24:07 +01:00
DarkLiKally 2092cc43b3 Updated for iConomy 4.0 2011-02-27 09:54:43 +01:00
DarkLiKally dc637d0f2b Fixed wall sign protection 2011-02-26 16:54:18 +01:00
DarkLiKally 987a20b33c Added ability to set a max. claim volume 2011-02-26 15:35:48 +01:00
DarkLiKally dbf65f798f Optimized the countBlocks() method for polygonal regions 2011-02-26 14:56:49 +01:00
DarkLiKally 97aa259b2d Added method to count the blocks in a polygonal region 2011-02-26 14:54:25 +01:00
Redecouverte 770a108bad /region info now names locations correctly 2011-02-26 13:18:31 +01:00
DarkLiKally 71aaa574b2 Added method to count the blocks in a cuboid region 2011-02-26 13:11:27 +01:00
Redecouverte a02fe633e2 fixed spawn/teleport flags 2011-02-26 12:49:14 +01:00
Redecouverte 0669bab563 added aliases /rd, /rc, /rf, /ri, /rl, /rp for region commands 2011-02-26 12:24:49 +01:00
Redecouverte a258400443 fixed npe for onPlayerRespawn 2011-02-26 12:00:02 +01:00
Redecouverte d02c5057c6 for
/region flag id name subname some string with spacaes

valueStr now contains 'some string with spaces'

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

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

INFO: I had not enough time to test it
2011-02-25 01:36:47 +01:00
DarkLiKally 5f12d99e73 Added water flow flag 2011-02-24 23:14:26 +01:00
Valentin Churavy 933987ac0a /tpr <id> spawn does now need the permissions /tpregion.spawn and also
added /region flag <id> spawn delete
2011-02-24 23:04:50 +01:00
Valentin Churavy 3a10a0969a add /tpr <region id> spawn 2011-02-24 22:53:20 +01:00
Valentin Churavy ba4907e67b add region.contains(location) for /region flag <id> spawn set 2011-02-24 22:29:49 +01:00
Valentin Churavy 99b37147d3 added /tpregion <region id> and /region flag <regionid> teleport
<set|delete>
2011-02-24 22:17:55 +01:00
Valentin Churavy 92a03ab7d6 added /region flag teleport 2011-02-24 21:35:45 +01:00
Redecouverte 68a0c67769 fixed for latest changes 2011-02-24 21:18:08 +01:00
Redecouverte 17e9105b9c commands now handled by commandhandler, updated /region info and /region flag for extended flag data 2011-02-24 21:15:05 +01:00
Redecouverte 5411a294e7 implemented heal, greeting and farewell flag 2011-02-24 21:14:42 +01:00
Redecouverte f821e277de geter with default values for extended AreFlags data 2011-02-24 21:11:31 +01:00
Valentin Churavy 18c2164049 added basic support of region teleport in ProtectedRegion 2011-02-24 20:29:47 +01:00
DarkLiKally c9688a9c58 Fixed an issue with the mob spawn control flags 2011-02-24 17:56:36 +01:00
Valentin Churavy cd599849b2 55: Improved corner handling (Corners are now always inside a
PolygonalRegion)
2011-02-24 17:32:06 +01:00
DarkLiKally 423f0199d0 Updated mob spawn control flags 2011-02-24 16:36:47 +01:00
DarkLiKally 40299eeea4 Changed Logger back to private (I changed it to public for some test reasons) 2011-02-24 16:20:52 +01:00
DarkLiKally 38077275bc Added mob spawn control Flags and global settings 2011-02-24 16:11:44 +01:00
Redecouverte 23aa6dc743 getAreaFlag now respects region priority 2011-02-24 14:52:22 +01:00
Redecouverte b90fb6a2b0 polygonal regions are now recognized by /region command, added extended AreaFlags data functions to ApplicableRegionSet, fixed isFlagAllowed in ApplicableRegionSet can only be executed once problem, updated region managers to not just forward all regions to ApplicableRegionSet 2011-02-24 14:24:23 +01:00
Redecouverte 17c8ed9ebc fixed typo in getRegionManager 2011-02-24 12:42:20 +01:00
Redecouverte a091a32c26 updated imports and comments 2011-02-24 12:14:26 +01:00
Redecouverte 23970a4e36 extended AreaFlags data storage, fixed typo on renaming old regions.txt 2011-02-24 12:06:27 +01:00
Redecouverte f61a9ab5cc added multiworld support for regions and json region database 2011-02-24 11:19:35 +01:00
Redecouverte 4505bb6f4e now including json-simple via build.xml 2011-02-23 20:51:19 +01:00
sk89q bb836aea57 Updated for 4.0-alpha1. 2011-02-23 11:25:10 -08:00
sk89q d584fba31c Updated block damage event handling to work around issues. 2011-02-23 11:07:39 -08:00
Redecouverte feacf3af7b removed CraftBukkit dependency 2011-02-23 19:13:56 +01:00
Redecouverte 8c428bb399 added JSON.simple 1.1 lib 2011-02-23 19:13:55 +01:00
sk89q 8edb6976fb Changed usage of CraftItemStack to ItemStack. 2011-02-23 10:05:29 -08:00
DarkLiKally edd2f460a0 Updated reflowing of water on sponge removal/deactivation 2011-02-22 20:56:57 +01:00
DarkLiKally 8810647bb8 Added reflowing of water on sponge removal/deactivation and
Updated water clearing on sponge creation/activation
2011-02-22 20:44:16 +01:00
DarkLiKally 2204bd67a7 Fixed the water damage block Bug 2011-02-22 17:27:58 +01:00
DarkLiKally c9c747693d Added ability to change default values of region's flags in config.yml for: FLAG_LIGHTER, FLAG_TNT, FLAG_CREEPER_EXPLOSION, FLAG_MOB_DAMAGE 2011-02-22 15:06:25 +01:00
Redecouverte 135d92303d more fixed for cake protection, protected cake now is semi-proteced, only the first slice is not protected 2011-02-22 15:02:57 +01:00
Redecouverte c707434155 fixed cake protection in regions 2011-02-22 14:26:01 +01:00
Valentin Churavy 4b72805a69 55: ProtectedPolygonalRegion should now handle edges better. 2011-02-22 13:58:05 +01:00
Redecouverte d5a9b0c65f really fixed setUpCourtyardRegion().. 2011-02-22 13:33:30 +01:00
Redecouverte 2015604fe2 fixed ProtectedPolygonalRegion construction in setUpCourtyardRegion 2011-02-22 13:33:01 +01:00
Redecouverte 96a290b153 added ItemAcquireBlacklistEvent for onPlayerPickupItem, not implemented in craftbukkit. yet 2011-02-22 13:22:06 +01:00
Redecouverte 912fcfe88a added tests to netbeans project 2011-02-22 13:18:27 +01:00
Redecouverte 4dcf7489fa added NetBeans project files 2011-02-22 13:03:06 +01:00
Redecouverte 7f1552dff8 updated onPlayerDropItem for latest bukkit, updated WorldEdit API calls for latest WorldEdit 2011-02-22 12:04:44 +01:00
Redecouverte d2ca8bffc4 we are now ignoring canceled events 2011-02-22 02:49:20 +01:00
Redecouverte e15b01bac5 added blacklist on-drop event 2011-02-22 02:48:57 +01:00
Redecouverte dcd3cb80b8 switched to parameterless constructor (i guess this is that the bukkit devs intended with their fancy warning) 2011-02-22 02:15:06 +01:00
Redecouverte d0ddc7c271 - added .gitignore to ignore eclipse/etc build files
- events are now registered in onEnable()
2011-02-22 02:03:20 +01:00
DarkLiKally 2b55f3407c Fixed the skeleton damage bug in protected areas 2011-02-22 01:01:31 +01:00
DarkLiKally e84afb4808 Fixed the Skeleton damage bug in protected regions 2011-02-22 01:01:31 +01:00
Redecouverte 10c47eff7e fixed entity damage events for latest bukkit 2011-02-21 23:30:20 +01:00
sk89q aee81f918e Added polygonal regions. They don't save/load yet, nor can you make them in-game yet. They were tested to work a week ago though. 2011-02-20 12:10:42 -08:00
sk89q 95b2d9419f Fixed redstone listener for newer versions of Bukkit. 2011-02-12 19:14:14 -08:00
sk89q feb9ce6633 Re-added priority tree region manager implementation. Add and removal operations are not yet optimized. 2011-02-12 16:09:21 -08:00
sk89q 43489ca087 Changed how ApplicableRegionSet iterated over the region set, allowing it to be reused. 2011-02-12 15:49:55 -08:00
sk89q ce1a15e6ea Improved tick sync message suppression. 2011-02-05 14:00:06 -08:00
sk89q cc72d370ea Added suppress-tick-sync-warnings option. 2011-02-05 13:45:05 -08:00
sk89q d042185660 Added WorldGuardPlugin.canBuild(player, x, y, z) 2011-02-04 20:51:14 -08:00
sk89q e78b639018 Updated CHANGELOG.txt. 2011-02-02 23:37:40 -08:00
sk89q e8ea562b09 Changed 'release' target to also 'clean'. 2011-02-02 23:28:48 -08:00
sk89q 3b5a729ef3 Updated command handling for Bukkit. 2011-02-02 22:27:44 -08:00
sk89q ef7d487ec5 Updated burn event handling. 2011-02-02 22:21:44 -08:00
sk89q b379b8f022 Fixed suffocation disable option. 2011-02-02 21:03:33 -08:00
sk89q a31378c2c8 Changed disable-water-damage to disable-drowning-damage. 2011-02-02 20:51:52 -08:00
sk89q 0d2c2121bb 3.2.1 CHANGELOG.txt. 2011-01-31 14:36:33 -08:00
sk89q 21040b306a Updated for ItemStack change in Bukkit. 2011-01-31 14:35:46 -08:00
sk89q 541b1dbc44 Updated for 3.2. 2011-01-30 01:38:39 -08:00
sk89q 005ac41820 Added PvP default flag. 2011-01-30 01:36:59 -08:00
sk89q dd93772233 Fixed creeper explosion block with WorldGuard. 2011-01-30 01:16:16 -08:00
sk89q 428fc7e5f6 Fixed commands for the Bukkit commands change. 2011-01-30 01:03:57 -08:00
sk89q 5cf38cc885 Added redstone support to sponges, removed classic water. 2011-01-28 10:23:43 -08:00
sk89q 2f6b51e811 Fixed item durability disable for hoes. 2011-01-28 00:59:19 -08:00
sk89q 2f12da6bc6 Fixed error in a test. 2011-01-28 00:06:58 -08:00
sk89q 3985e157d9 Increased the priority of WorldGuard's event handling. 2011-01-24 09:17:20 -08:00
sk89q 3034eb5c12 Updated CHANGELOG.txt. 2011-01-24 09:12:56 -08:00
sk89q f666f1baa9 Fixed creeper and chest flag conflicting. 2011-01-24 09:12:32 -08:00
sk89q 3bbffa7b55 Updated for 3.1. 2011-01-24 02:40:17 -08:00
sk89q bc774e2596 Added /regionmembership permission. 2011-01-24 02:38:18 -08:00
sk89q 65a0e5c188 Possibly fixed projectile blocking in no-PvP zones. 2011-01-24 02:37:11 -08:00
sk89q 772d2cb580 Added ability to disable chest protection. 2011-01-24 02:35:33 -08:00
sk89q edc6825f83 Added WorldGuardPlugin.getRegionLoader(). 2011-01-22 01:41:18 -08:00
sk89q 7b2f9e0c86 Added Javadoc compilation. 2011-01-22 01:31:57 -08:00
sk89q 0fa4fa1862 Added getRegionManager() to WorldGuardPlugin. 2011-01-22 01:31:48 -08:00
sk89q 5be31ebb5c Fixed /god not working for others. 2011-01-21 19:49:22 -08:00
sk89q 962394b2ba Updated for 3.0b2. 2011-01-21 19:45:41 -08:00
sk89q 7cf7c5f44c Fixed issue where permissions were not loaded. 2011-01-21 19:45:06 -08:00
sk89q 5b494a09ec Fixed permissions for /stack, /locate, and /reloadwg. 2011-01-21 17:53:06 -08:00
sk89q 5cfac5da4a Marked version as beta1. 2011-01-21 15:41:25 -08:00
sk89q 203004951b Updated CHANGELOG.txt. 2011-01-21 15:26:43 -08:00
sk89q 765d7402fa Added parent-child relationships to regions, overhauled region code, added global build flag, improved flag support. 2011-01-21 15:23:11 -08:00
sk89q 151b5fc561 Fixed no-PvP zone messages being sent to the wrong person. 2011-01-21 01:37:40 -08:00
sk89q b489da7fe4 Fixed commands so that they work in a recent version of Bukkit. 2011-01-21 01:32:23 -08:00
sk89q 786a0f6f2b Reduced the number of imports in WorldGuardPlugin. 2011-01-21 01:27:18 -08:00
sk89q e2a940e01b Cleaned up code. 2011-01-21 01:21:36 -08:00
sk89q 518c3be478 Fixed errors in TestPlayer.java. 2011-01-21 01:13:20 -08:00
sk89q 6f3eaac008 Fixed NullPointerException in explode hook. 2011-01-21 00:51:50 -08:00
sk89q 31633e9466 Updated for 2.3.1. 2011-01-20 11:23:56 -08:00
sk89q 02913780ec Fixed the item durability disable setting changing the damage value on an empty hand. 2011-01-20 11:23:13 -08:00
sk89q f03a2263d8 Added checks for unchecked exceptions when resolving permissions. 2011-01-20 11:19:59 -08:00
sk89q a8cd832c28 Fixed various cast exceptions with the blacklist loggers. 2011-01-20 11:16:59 -08:00
sk89q abbced0530 Updated changelog. 2011-01-20 02:09:04 -08:00
sk89q 200e07023f Fixed /locate printing the name of the wrong person. 2011-01-20 02:03:43 -08:00
sk89q 5fdd26b53f Fixed CSVDatabase spitting an error if the owners list was empty. 2011-01-20 02:01:50 -08:00
sk89q 61896ea760 Updated example config.yml. 2011-01-20 01:56:42 -08:00
sk89q b43881c299 Added /locate. 2011-01-20 01:54:47 -08:00
sk89q 6046f4defc Fixed teleport-on-suffocation setting. 2011-01-20 01:07:39 -08:00
sk89q 69ccb9f12b Implemented contact damage and fixed other damage protection. 2011-01-20 00:55:20 -08:00
sk89q 430f2f57e9 Made TNT blocking work. 2011-01-19 23:38:16 -08:00
sk89q c3f0bbb41c Added /heal and /slay. 2011-01-19 23:31:20 -08:00
sk89q 7e481e6a9a Moved commands handling to be Bukkit-compliant. 2011-01-19 23:27:35 -08:00
sk89q 627de1aebd Changed how the player item event was handled. 2011-01-19 22:09:15 -08:00
sk89q 194108336b Updated CHANGELOG.txt. 2011-01-17 19:47:24 -08:00
sk89q eade612981 Fixed WorldGuard not getting group lists for permissions correctly. 2011-01-17 19:45:53 -08:00
sk89q 733163cc4c Updated changelog, readme. 2011-01-17 19:22:04 -08:00
sk89q 86a917ddd1 Added creeper block support. 2011-01-17 18:38:12 -08:00
sk89q e8503aa0b9 Now supports GroupUsers (through WorldEdit). 2011-01-17 17:55:56 -08:00
sk89q 01bf9e8406 Fixed issue where the build process did not make sure that plugin.yml would be updated. 2011-01-17 17:47:07 -08:00
sk89q 0bdadf63b3 Fixed errors in tests. 2011-01-17 17:45:51 -08:00
sk89q 5b1c35bf06 Fixed build file not replacing version macro correctly. 2011-01-17 16:51:04 -08:00
sk89q c467acdfac Updated CHANGELOG.txt for 2.1.1. 2011-01-17 02:55:18 -08:00
sk89q 22167a0a07 Allowed placing WorldEdit.jar as a dependency in WorldGuard/. 2011-01-17 02:53:13 -08:00
sk89q 251647c7a2 Added some priority support. 2011-01-17 02:31:32 -08:00
sk89q 80e9799579 Fixed typo in README.txt. 2011-01-17 00:23:17 -08:00
sk89q 95f49f34d0 Cleaned up code. 2011-01-17 00:19:23 -08:00
sk89q b01b67f64c Cleaned up code. 2011-01-17 00:16:02 -08:00
sk89q 603fb5d2b8 Made /reload WorldGuard work for everyone by default. 2011-01-17 00:13:27 -08:00
sk89q 22f7c347ab Simplified release ZIP. 2011-01-17 00:10:32 -08:00
sk89q 08229ed4f9 Made WorldGuard write default configuration files, more friendly. Removed hMod configuration files. 2011-01-17 00:05:35 -08:00
sk89q a942fd08f5 Fixed NullPointerException related to the player item event. 2011-01-16 23:15:30 -08:00
sk89q c96d534c26 Fixed fire spread disable preventing flint and steel too. 2011-01-16 19:38:29 -08:00
sk89q 789a9a9bb4 Fixed configuration file not being reloaded. 2011-01-16 13:33:23 -08:00
sk89q d2435a8026 Updated supporting documentation. 2011-01-16 13:33:14 -08:00
sk89q 36db436fa3 Implemented temporary permissions. 2011-01-16 12:56:17 -08:00
sk89q 30d9978412 Fixed various issues with regions. 2011-01-16 11:54:03 -08:00
sk89q 5db7f124ac Added region claiming, some fixes. 2011-01-16 10:44:37 -08:00
sk89q c82ee055e7 Updated stack command to use ItemType.usesDamageValue(). 2011-01-16 09:15:16 -08:00
sk89q cb1c1efc35 Moved blacklist message flood logger to Blacklist. 2011-01-16 09:11:42 -08:00
sk89q 0037a4e83f Restored blacklist. 2011-01-16 02:50:41 -08:00
sk89q c369b3c62a Removed item drop blacklist. 2011-01-15 23:50:29 -08:00
sk89q 0934a12205 Updated region protection to support chests. 2011-01-15 23:47:15 -08:00
sk89q d19db5f86f Further progress on the port. 2011-01-15 23:21:27 -08:00
sk89q 5657ee6c90 Progress. 2011-01-15 16:33:21 -08:00
sk89q 41a71d6185 Added Updatr support. 2011-01-12 09:18:09 -08:00
sk89q 11592cd742 2.0beta3 2011-01-12 09:15:44 -08:00
sk89q 43d83d8855 Fixed NullPointerException inside the ignite hook. 2011-01-12 09:15:04 -08:00
sk89q d1cb628473 Updated WorldGuard to catch a missing WorldEdit. 2011-01-10 13:18:28 -08:00
sk89q 44fc802e8b Updated for 2.0beta2. 2011-01-10 13:00:38 -08:00
sk89q bfa1734d23 Fixed the NullPointerException in the damage hook caused by a null attacker. 2011-01-10 13:00:04 -08:00
sk89q 66139dacac Updated for 2.0beta1. 2011-01-08 18:43:19 -08:00
sk89q 714c24445d Updated for 2.0. 2011-01-08 18:41:26 -08:00
sk89q 79f55a02cb Fixed NullPointerExceptions in item use hook. 2011-01-08 18:38:18 -08:00
sk89q 484fe22e9e Finished up regions support. 2011-01-08 18:26:49 -08:00
sk89q 119d8b1a81 Fixed /delarea and allowed it to use its own /delarea permission instead. 2011-01-08 16:42:09 -08:00
sk89q 953d1f0aed Add denial messages to region protection. Changed use-protected-regions to use-regions and turned it on by default. 2011-01-08 16:36:25 -08:00
sk89q 2e225a9452 Removed INVENTORY_CHANGE hook. 2011-01-08 16:35:35 -08:00
sk89q 960dc2cd48 Changed ProtectedCuboidRegion to do its bounds check without Vector. 2011-01-08 16:35:15 -08:00
sk89q 345ac35649 Added area protection code borrowed from WorldEdit. While the framework is currently quite flexible, the implementation still needs work. 2011-01-08 02:04:21 -08:00
sk89q 802114c605 Commented out WorldGuardListener.onInventoryChange(). 2011-01-08 01:33:20 -08:00
sk89q 16bbd30209 Code cleanup. 2010-12-30 00:51:12 -08:00
sk89q 0021e789bc Removed com.sk89q.worldedit.blocks.BlockType. 2010-12-30 00:48:50 -08:00
sk89q 41daebb629 Updated changelog. 2010-12-26 10:32:31 -08:00
sk89q b496e88557 Fixed NullPointerException in WorldGuardListener.onSignChange(). 2010-12-26 10:31:54 -08:00
193 changed files with 20868 additions and 4016 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
*.java diff=java
+6
View File
@@ -0,0 +1,6 @@
.classpath
.project
.settings
target
.DS_Store
+7
View File
@@ -0,0 +1,7 @@
language: java
jdk:
- oraclejdk7
- openjdk7
- openjdk6
notifications:
email: false
+323 -2
View File
@@ -1,4 +1,325 @@
1.8:
5.6:
- Added official support for Minecraft 1.4. Support for 1.3.2 (and below) is still
provided in this release.
- Added support for new and existing explosion types.
- Added support for blocking withers with the following settings:
mobs:
block-wither-explosions: false
block-wither-block-damage: false
block-wither-skull-explosions: false
block-wither-skull-block-damage: true
- Added support for blocking item frames (and their use) in protected regions.
- Added item frame destruction region flags (if you wish to disable item frame
destruction completely).
- (Re-)added support for priority R-tree region indexes. This means quicker region lookup,
and better support for servers with thousands of regions.
- Improved /region info output for -g group flags.
- Allowed removing of -g group flags with /region flag.
- Allowed /region flag to set group and value at once.
- Deleting a region flag now also deletes group flag.
- Fixed detection of attack by projectiles to be more accurate.
- Fixed support for saving non-string flags in the MySQL region support.
- Fixed spurious comma in "Flags:" /region info output.
- Fixed players who are not in god mode not receiving damage in PVP areas from
enderpearls.
- Players will now be told that they are in a no-PvP area if they are in one and
attempting to attack someone, or that the player they are attacking is in a
no-PvP area, if that is the case instead.
- Fixed an issue where region.getId() was lowercase'd each pass of a for loop in
MySQLDatabase.updatePoly2dPoints().
- Fixed mob damage from projectiles not being properly blocked in regions where
applicable.
- Changed default region wand to leather (#334).
Thank you to the following individuals for their contribution:
thvortex, Rutr, Glitchfinder, and DarthAndroid.
5.5.4:
- Minecraft 1.3 support.
- Fixed /stack dupe bugs.
- Added regions.use-creature-spawn-event.
- Update for Async chat issue.
- Add use flag to cakes.
- Report number of plugins loaded in report writer.
- Updated fireblal item blocking.
- Fixed permissions for /region reload.
5.5.3:
- Added game mode flag.
- Added item drop pickup flag to regions.
- Added support for fireball item blocking (385).
- Added configuration option to allow creature spawns from plugins.
- Added host key check.
- Added a new line split feature to region greetings.
- Prevented commands in the allow commands list from being blocked and
vice versa.
5.5.2:
- Added potion-splash flag to block splash potions
- Add entity-painting-destroy which can be used to prevent entities from destroying
paintings (skeletons firing arrows)
- Added send-chat and receive-chat flags
- Fixed having regions in multiple worlds with the same name not working with MySQL
- A cancellable event is now fired if WorldGuard disallows PvP. (for developers!)
- Made /region setparent check worldguard.region.setparent.own/member.<parent> instead
of worldguard.region.setparent.own/member.<child>.
- Allowed passing #<index> in place of a region ID, where <index> is the index as
displayed by /region list.
- Fixed an error that occured when clearing a non-existant region's parent.
- Added a -s flag to /region teleport, which sends you to the spawn point instead of the
teleport point of a region.
- Added region/role-based permissions to /region teleport.
- BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags
use it.
- /region info -s now selects the region being queried.
- Added /region teleport <id>.
- Vector flags can now be set to the current location with the value "here" and to a
specific position with x,y,z.
- Made /region info show the region you're in if you don't specify an id explicitly.
- Prevent block ignition from lightning strikes if lightning is blocked in region. Fixes
#1175
- Correctly check both WEPIF and superperms in WorldGurdPlugin.broadcastNotification()
- Destroy fire blocks when fire-spread is disallowed
- Added a construct flag that can be used to restrict block placing/destroying in zones
to certain roles.
- Added FallingSand to list of intensive entities to be removed with /halt-activiy.
- Replaced all usage of CreatureType by EntityType.
- Updated to support Bukkit 1.2-R0.3 and newer
- Made auto-god-mode disabled by default again.
- Added sign protection check disable.
- Cleaned up javadoc, deprecated duplicate methods, other cleanup
- Added a RegionGroupFlag to evey region flag Using the /region flag command with -g,
the region group that the region flag applies to can be set.
5.5.1:
- Fixed attacking with arrows from non-PVP to PVP areas
- Compatibility with Bukkit 1.1-R5
- Removed broken suppress-tick-sync-warnings config option. See bukkit.yml's setings.warn-on-overload option instead.
- Add region and 'can build' information to CommandBook's /whois
Contributions thanks to: NolanSyKinsley
5.5:
- Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
- Now using Bukkit's tagged logging
- Updated to new event system
- Flush player flag state cache on world change
- Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0
- Added MySQL region storage method.
- Made explosions display their animations even when the event was blocked.
- Added fallback support for those who don't have a version of CommandBook with GodComponent
- Added LIGHTNING flag to DefaultFlag's flagsList Fixes #1026
- Removed /god, /heal, /locate, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded.
- Removed remaining usages of org.bukkit.util.config.Configuration
- Removed some unused configuration options
- Added permission worldguard.region.wand to the region wand
- Fixed ProtectedRegion.compareTo.
- Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
- Added exp-drops flag to disable experience drops per-region.
- Fixed some warnings.
- Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
- Added support for fireballs shot by players being blocked by the PVP flag.
- Now using dynamic command registration
- Split off ender dragon block damage from creeper block damage.
Contributions thanks to: narthollis, DarkArc, Wolvereness, and skeight
5.4:
- Fixed configuration generation on Windows
- Fixed intersection calculation for regions
- Fixed timer and feeding delay for food flags
- Fixed region managers not being created properly (This caused errors related to CREATURE_SPAWN)
- Added support for Minecraft 1.0.1 blocks
- Added support for enchantments and tool damage (worldguard.stack.damaged is the node) with /stack
- Made being in the wg-invincible group respect the configuration's auto-invincible setting
- Added per-group region claim limit maximum
- Added worldguard.region.addowner.unclaimed.* permission for non-economy region 'buying'
- Checking allowed/blocked commands now occurs earlier to override more plugins
- Made PVP flag check whether either player is in a pvp deny region for blocking
Contributions thanks to: epuidokas, wizjany, Turtle9598, and DerFlash
5.3:
- Added new config options and flags to better handle explosions of all types
- Added config options and flags for snow, ice, mushroom spread, grass spread,
and leaf decay
- Added min and max health flags to clamp the values for the existing healing
flags
- Added hunger flags similar to the existing healing flags
- Added an option to disable the use of the move event. This can boost
performance on large servers but will disable the greeting/farewell
and entry/exit flags
- Added flag to prevent pistons (including those that are outside the
region, but would affect blocks inside the region)
- Added a /wg flushstates [player] command to free players stuck in a
region that was exit-deny but no longer exists or the flag was removed
- Added a config option to disable xp orb dropping
- Added config option to disable redstone wire obsidian generators
- Added a vehicle-destroy flag
- Added enderman protection config and flag
- Allowed and blocked command flags will now fall back to the global region
- The worldguard.region.flag.own/member permissions are now
worldguard.region.flag.regions.own/member! Please change your permissions
accordingly.
- Made //stack respect max stack sizes unless the player has the
worldguard.stack.illegitimate permission
- Setting invincibility flag to deny will override god mode unless the player
has worldguard.god.override-regions
- The sleep flag will now prevent beds in the nether from
exploding if set to deny
- Existing regions can no longer be accidentally overwritten.
Use /region redefine to move an existing region.
- The info command will now sort players alphabetically
- Priming TNT by punching it with flint and steal should throw a blacklist
event (consistent with old Minecraft versions)
- The /stoplag command will now remove xp orbs
- Permissions system will use per-world permissions if the provider supports it
- Players in vehicles are now subject to entry/exit and greeting/farewell flags
- Fixed interact blacklist event not logging correctly
- Fixed heal flag taking effect half a block northeast of the region
- Fixed a infinite sign dropping bug
- Fixed players being able to douse fire by punching it in regions they
couldn't build it
- Fixed players being able to eat protected cake
- Fence gate usage can be blocked with the use flag
- Fixed chests being unprotected when they should be in 1.8
- Fixed weather config settings not applying when a world was loaded
- Fixed explosion handling in certain cases
- Fixed arrows working in non-pvp zones
- Fixed buckets working on the border of protected regions in certain cases
Contributions thanks to:
wizjany, zml2008, imjake9, Droolio, epuidokas,
EduardBaer, TomyLobo, and halvors
5.2.2:
- Changed configuration saving so empty lists will be added to
the configuration files.
5.2.1:
- Add region bounds to /region info
- Added the ability to add owners/members to the global region for
handling guest groups. Now if there's owners or members on the global
region, then those that are not on the list cannot build.
- Fixed some flag algorithm issues.
- API: Fixed DefaultDomain.size() not counting players.
- API: Undeprecated ApplicableRegionSet.allows(StateFlag).
5.2:
- Gave the ability to use color colors and macros in greeting
and farewell messages.
- Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread,
disable-snow-melting, disable-ice-formation.
- Added paintings to blacklist support.
- Added default.disable-health-regain.
- Added auto-invincible-permission setting, which lets you use the permission
'worldguard.auto-invincible' to become invincible on join automatically.
- Flames won't appear if you are /god'ed now.
- Added blocked-cmds region flag to block commands.
- Added allowed-cmds region flag to whitelist commands.
- Added entry region flag to block entry. Use entry-group to determine who
this affects.
- Added exit region flag to block exit. Use exit-group to determine who
this affects.
- Made negative healing possible via the healing flag.
- Changed the configuration header messages to be more helpful to new users.
- Added a warning about modifying region files by hand.
- Improved the API for plugin developers.
5.1:
- A lot of changes.
4.0-alpha1:
- This release is only to fix WorldGuard for Bukkit. Ignore the 4.0
label. Just move along. Nothing to see.
3.2.2:
- Changed disable-water-damage to disable-drowning-damage.
- Fixed suffocation disable option.
- Fixed fire spread blocking.
- stopfire and allowfire now work in server console, just like in hMod.
3.2.1:
- Updated for recent Bukkit ItemStack change.
3.2:
- Added regions.default.pvp to control default PvP setting.
- Updated WorldGuard for the newer builds of Bukkit.
- Fixed creeper explosion blocking.
- Added redstone support to sponges, removed classic water.
- Fixed item durability disable for hoes.
3.1.2:
- Increased the priority of WorldGuard's event handling.
3.1.1:
- Fixed creeper and chest flag conflicting.
3.1:
- Added ability to disable chest protection. New configuration setting
(regions.build.chest-access) and new chest flag.
- Possibly fixed projectile blocking in no-PvP zones.
- Added /regionmembership permission that lets people only change
the owners and members of regions they own.
3.0b2:
- Fixed issue where built-in permissions were not (re)loaded.
- Fixed /god not working for others.
3.0b1:
- Added parent-child relationships to regions.
- Added global build flag.
- Improved flag support.
- Fixed no-PvP zone messages being sent to the wrong person.
- Fixed commands so that they work in a recent version of Bukkit.
- Fixed NullPointerException in explode hook.
2.3.1:
- Fixed various cast exceptions with the blacklist loggers.
- Added checks for unchecked exceptions when resolving permissions.
- Fixed the item durability disable setting changing the damage value on
an empty hand.
2.3:
- /god now works very well.
- Item (TNT, flint and steel, etc.) blocking should now work.
- The TNT blocking configuration variable should now work.
- Re-added /heal (not sure where that went), added /slay.
- Implemented contact damage disable toggle.
- Made all player damage disabling configuration parameters work.
- Fixed teleport-on-suffocation setting.
- Added /locate <name>, /locate <x> <y> <z>, and /locate that lets you
program/change your compass bearing to point to a player's position
(not yet live), a position, or back to spawn.
- Fixed CSVDatabase spitting an error if the owners list was empty.
2.2:
- Now supports GroupUsers.
- Added support for blocking creeper explosions.
- Fixed a bug where a player's groups were not being loaded correctly,
causing the blacklist group ignore option to not work.
2.1.1:
- Fixed fire spread disable preventing flint and steel too.
- Fixed NullPointerException related to the player item event.
- Made setup simpler.
2.1:
- Improved Bukkit support.
2.0beta3:
- Fixed NullPointerException inside the ignite hook.
2.0beta2:
- Fixed a NullPointerException in the damage hook.
2.0beta1:
- Added area protection. Use /region or /rg to define regions.
1.8.1
- Fixed NullPointerException.
1.8
- Updated for Minecraft beta.
- Blacklist hooks have CHANGED. The new hooks are work better. on-create has
been replaced with on-place (for block placement) and on-use
@@ -7,7 +328,7 @@
- Added coordinates to blacklist file logger.
- Added suffocation damage prevention.
1.7.1:
1.7.1
- Updated for v0.2.8.
1.7
+69
View File
@@ -0,0 +1,69 @@
Contributing
============
Thank you for your interest in contributing to WorldGuard! We appreciate your
effort, but to make sure that the inclusion of your patch is a smooth process, we
ask that you make note of the following guidelines.
* **Follow the [Oracle coding conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html).**
We can't stress this enough; if your code has notable issues, it may delay
the process significantly.
* **Target Java 6 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
and other such tasks easier. Ignore this guideline if it makes the code
too unreadable.
* **Write complete Javadocs.** Do so only for public methods, and make sure
that your `@param` and `@return` fields are not just blank.
* **Don't tag classes with @author.** Some legacy classes may have this tag,
but we are phasing it out.
* **Make sure the code is efficient.** One way you can achieve this is to spend
around ten minutes to think about what the code is doing and whether it
seems awfully roundabout. If you had to copy the same large piece of
code in several places, that's bad.
* **Keep commit summaries under 70 characters.** For more details, place two
new lines after the summary line and write away!
* **Test your code.** We're not interested in broken code, for the obvious reasons.
* **Write unit tests.** While this is strictly optional, we recommend it for
complicated algorithms.
Checklist
---------
Ready to submit? Perform the checklist below:
1. Have all tabs been replaced into four spaces? Are indentations 4-space wide?
2. Have I written proper Javadocs for my public methods? Are the @param and
@return fields actually filled out?
3. Have I `git rebase`d my pull request to the latest commit of the target
branch?
4. Have I combined my commits into a reasonably small number (if not one)
commit using `git rebase`?
5. Have I made my pull request too large? Pull requests should introduce
small sets of changes at a time. Major changes should be discussed with
the team prior to starting work.
6. Are my commit messages descriptive?
You should be aware of [`git rebase`](http://learn.github.com/p/rebasing.html).
It allows you to modify existing commit messages, and combine, break apart, or
adjust past changes.
Example
-------
This is **GOOD:**
if (var.func(param1, param2)) {
// do things
}
This is **EXTREMELY BAD:**
if(var.func( param1, param2 ))
{
// do things
}
-15
View File
@@ -1,15 +0,0 @@
Installation
------------
This plugin requires Hey0's server modification.
1. Create a "plugins" folder inside your "bin" folder.
2. Copy WorldGuard.jar into "plugins".
3. Add "WorldGuard" to the "plugins" line of your server.properties file.
If it's not already there, add the line. The line should look like this:
plugins=WorldGuard
If you have multiple plugins, separate plugin names with commas.
+39 -1
View File
@@ -1,3 +1,7 @@
----------------------------------------------------------------------------
WorldGuard License
----------------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
@@ -162,4 +166,38 @@ General Public License ever published by the Free Software Foundation.
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
Library.
----------------------------------------------------------------------------
PRTree License
----------------------------------------------------------------------------
Copyright (c) 2008-2010 Robert Olofsson.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
+232
View File
@@ -0,0 +1,232 @@
<!DOCTYPE html>
<html>
<head>
<title>${project.name} ${version}</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Ropa+Sans" rel="stylesheet" type="text/css">
<style>
body {
margin: 0;
padding: 3em 1em;
background: #efefef;
color: #333;
line-height: 1.5;
}
#wrapper {
width: 600px;
margin: auto;
}
body, th, td, input {
font: 14px 'Source Sans Pro', Arial, sans-serifsans-serif;
}
.section {
background: #fff;
position: relative;
padding: 2em 2.4em;
margin: 3em auto 4em auto;
width: 80%;
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.section:before, .section:after {
content: "";
position: absolute;
z-index: -2;
}
.section {
-moz-border-radius: 4px;
border-radius: 4px;
}
.section:before, .section:after {
bottom: 15px;
left: 10px;
width: 50%;
height: 20%;
max-width: 300px;
max-height: 100px;
-webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-webkit-transform: rotate(-1deg);
-moz-transform: rotate(-1deg);
-ms-transform: rotate(-1deg);
-o-transform: rotate(-1deg);
transform: rotate(-1deg);
}
.section:after {
right: 10px;
left: auto;
-webkit-transform: rotate(1deg);
-moz-transform: rotate(1deg);
-ms-transform: rotate(1deg);
-o-transform: rotate(1deg);
transform: rotate(1deg);
}
a:link, a:visited {
color: #0004b2;
text-decoration: none;
}
a:hover {
color: #ac0000;
text-decoration: none;
border-bottom: 1px solid #999;
}
h1 {
font: 2.7em 'Ropa Sans', 'Trebuchet MS', Helvetica, Arial, sans-serif;
color: #000;
margin: 0 0;
padding: 0 0 0.2em 0;
font-weight: normal;
text-align: center;
text-shadow: 2px 2px #FFF;
}
h2 {
font-size: 1.3em;
color: #FFF;
margin: -2.5em 0 0.8em 0;
float: left;
background: #0049FF;
padding: 0.4em 0.8em;
border-radius: 0.2em;
font-weight: normal;
text-align: center;
}
h3 {
text-transform: uppercase;
font-weight: bold;
}
h2 + * {
clear: both;
}
@media (max-width: 650px) {
#wrapper {
width: 100%;
}
}
</style>
</head>
<body>
<div id="wrapper">
<h1>${project.name} ${version}</h1>
<div class="section">
<h2>Getting Started</h2>
<p>
Thanks for choosing ${project.name}! When you first install ${project.name},
nothing will be enabled, so you will need to switch on the features
that you need to use, whenever it is convenient for you.
</p>
<ul>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Installation">How do I install ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Upgrading">How do I update ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}#Usage">How do I use ${project.name}?</a></li>
</ul>
<p>
Need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Common Issues</h2>
<h3>What are the other files that come with the download?</h3>
<p>
Inside the folder "contrib" of the download are the following files:
</p>
<ul>
<li>blacklist_table.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Blacklist">blacklist feature</a>.</li>
<li>region_storage.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Regions">region protection feature</a>.</li>
<li>region_storage_update_20110325.sql is for updating your region protection
database (if you're using it) if your database was made before March 25, 2011.</li>
</ul>
<h3>${project.name} doesn't seem to work.</h3>
<p>
Two common mistakes include forgetting to install WorldEdit
(${project.name} needs it), or making
a syntax error in one of ${project.name}'s configuration files (this is very
fatal unfortunately, and can be caused by a single character typed in the wrong place). Try
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">asking in IRC</a>
to see whether anyone can help you.
</p>
<h3>How do I protect my spawn, or another area?</h3>
<p>
Read the <a href="http://wiki.sk89q.com/wiki/${project.name}/Regions/Tutorial">area protection tutorial</a>
on our wiki. For more detailed information, be sure to read about
<a href="http://wiki.sk89q.com/wiki/WorldGuard/Regions">region protection on the wiki</a>. Note
that if you can't build in spawn, don't forget that Minecraft comes with its own
limited spawn protection that you have to disable (see below).
</p>
<h3>I or others don't have permission to build.</h3>
<p>
Unless you copied configuration files from an older installation of
${project.name}, your problem is either caused by another plugin, or by not
disabling the built-in spawn protection of the Minecraft server.
</p>
<h3>No one can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'deny' means that
no one can modify the things inside the region.</li>
<li>That you added the player as an owner or member of the region. If you are using
a group (g:groupName), you may have to give the group the permission of
group.groupName for ${project.name} to recognize it.</li>
<li>That you disabled spawn protection. The Minecraft server has an automatic
spawn protection feature where only 'ops' can build in a definable
radius around spawn (by default, it is 16 blocks). If you are on Minecraft
1.4 or newer, edit "spawn-protection" in server.properties; otherwise, modify bukkit.yml
and change the spawn-radius setting.</li>
<li>That it's not another plugin causing you trouble. The error messages of ${project.name} are of
a dark red shade. If the color of the "no permission" message is not
that color, it is not ${project.name}.</li>
</ul>
<h3>Everyone can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'allow' means that
anyone can modify the things inside the region.</li>
<li>That it's not caused by another plugin. If players are getting a dark red
permission denied message, but they can still build, another plugin
is likely causing the conflict.</li>
</ul>
<h3>Where do I report bugs or suggest ideas?</h3>
<p>
Make sure you are using the latest version of ${project.name}, try asking in
IRC first (see "Need help?" above) if it's a problem, and if you think you've
found a bug or have a great suggestion to provide, please
report it to <a href="http://youtrack.sk89q.com/issues/WORLDGUARD">our issue tracker</a>.
</p>
<p>
Still need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Contributing</h2>
<p>
Did you know that ${project.name} is open source? That means that you can
read the code and learn from it, as well as modify it and submit back
changes to help the community!
</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">View the source code</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Development">More information</a></li>
</ul>
</div>
</div>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
![WorldGuard](http://static.sk89q.com/readme/worldguard.png)
==========
WorldGuard is a toolbox of various functions, useful for multiplayer servers, that lets you:
* Protect your server from a number of problems.
* Block fire spread, lava spread, endermen, and more.
* Flag areas as "no PVP" or "no TNT."
* Assign ownership to areas so only selected individuals can build.
* Use a number of useful commands.
WorldGuard is open source and is available under the GNU General Public License v3.
Compiling
---------
The project is written for Java 6 and our build process makes use of [Maven](http://maven.apache.org). Detailed compilation information [can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
Dependencies are automatically handled by Maven.
Contributing
------------
We happily accept contributions, especially through pull requests on GitHub. Submissions
must be licensed under the GNU General Public License v3.
Please read CONTRIBUTING.md for important guidelines to follow.
Links
-----
* [IRC channel](http://skq.me/irc/irc.esper.net/sk89q/) (#sk89q on irc.esper.net)
* [Issue tracker](http://youtrack.sk89q.com/issues/WORLDGUARD)
* [Continuous integration](http://build.sk89q.com) [![Build Status](https://secure.travis-ci.org/sk89q/worldguard.png)](http://travis-ci.org/sk89q/worldguard)
* [End-user documentation](http://wiki.sk89q.com/wiki/WorldGuard)
-251
View File
@@ -1,251 +0,0 @@
WorldGuard
Copyright (c) 2010 sk89q <http://www.sk89q.com>
Licensed under the GNU Lesser General Public License v3
Introduction
------------
WorldGuard has a number of features, any of which you can choose to
use or not:
- Enforce only one session for a player on a server (can't login twice).
- Block creeper explosions.
- Block TNT explosions.
- Block lighters from setting fires.
- Block all fires.
- Disable fall damage, lava damage, fire damage, and/or water damage.
- 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).
- Prevent water from destroying blocks like Redstone wire and flowers.
- Simulate the function of the sponge from Minecraft Classic.
- Notify admins, block, log, kick or ban for the use of certain block types
or items.
- Temporarily stop fire globally with some commands.
- Destroy tools on drop to alleviate the durability cheat.
- Prevent gravel and sand from falling.
- Allow portal blocks to be placed anywhere.
hMod is required as WorldGuard is a plugin for hMod.
Configuration
-------------
A "worldguard.properties" will be created the first the time that you load
WorldGuard on your server. You can either restart your server or use
/reloadplugin WorldGuard to reload the configuraton file after editing it.
NOTE: Some features may require a custom version of hMod. When the server
is loaded with the plugin, WorldGuard will tell you the features
unsupported by your version of hMod.
- summary-on-start (def. true)
Print a summary of WorldGuard's protection settings at-a-glance when
the plugin is loaded.
- item-durability (def. false)
**Requires special version of hMod
Enables item durability.
- classic-water (def. false)
Toggle use of classic water. Be foreward that your world may be
flooded if you are not careful. If you have WorldEdit, you can use
//drain in such an event, although that will drain the entire pool
as well. This classic-esque water will only spread infinitely over
ground, but if there are air blocks underneath, the water will not
spread (preventing waterfalls from becoming tsunamis).
- simulate-sponge (def. true)
Toggle simulation of the sponge from Classic. It blocks water from
flowing near the sponge.
- sponge-radius (def. 3)
The radius of the sponge's effect. The default is that of Classic,
creating a 5x5x5 cuboid free of water. Increasing the number will
increase server load exponentially, although 3-5 has fairly low impact.
- no-physics-gravel (def. false)
**Requires special version of hMod
Prevents gravel from falling due to gravity.
- no-physics-sand (def. false)
**Requires special version of hMod
Prevents sand from falling due to gravity.
- allow-portal-anywhere (def. false)
**Requires special version of hMod
Allows you to place portal blocks anywhere.
- enforce-single-session (def. true)
Enforce single sessions. If the player is already found to be on
the server when s/he logs in, the other player will be kicked with
an informative message. The inventory will have been saved before
the new session starts.
- block-tnt (def. false)
Block TNT explosions. TNT will still explode client-side but the blocks
will be "restored" in a few seconds afterwards.
- block-lighter (def. false)
Block flint and steel fires. Those with access to the commands
/uselighter or /lighter can bypass this. /uselighter is not a real
command; it is only used for permissions.
- block-creepers (def. false)
Block creeper explosions from destroying terrain (and possibly from
causing damage).
- disable-lava-fire (def. true)
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.
- disable-water-damage-blocks (no default)
List of blocks that should not be destroyed by water (Redstone wire,
minecart tracks, flowers, etc.).
- item-drop-blacklist (no default)
List of block names/IDs to destroy on drop. This can alleviate the
durability cheat that allows you to drop your tools to fix their
durability. You can also enforce this with the blacklist but
this is an easier way to do it (this way also prints a more
friendly message than if you used the 'tell' action of the blacklist).
- login-protection (def. 3)
Number of seconds to keep a player invincible when the player joins.
- spawn-protection (def. 0)
Number of seconds to keep a player invincible when the player spawns.
This does not apply to players joining the server.
- kick-on-death (def. false)
Kick players when they die (and respawn). This is to work around the
issues of invisible players when players die.
- disable-fall-damage (def. false)
- disable-lava-damage (def. false)
- disable-fire-damage (def. false)
- disable-water-damage (def. false)
Disable various types of damage.
- log-console (def. true)
For blacklist log actions, print to console.
- log-file (def. false)
For blacklist log actions, log to file.
- log-file-path (def. "worldguard/logs/%Y-%m-%d.log")
Log blacklist events to file. You can use these patterns in the path:
%Y the year (YYYY)
%m the month (MM)
%d the day (DD)
%W the week of the year (00-52)
%H 24-hour time (HH)
%h 12-hour time (HH)
%i the minute (mm)
%s the second (ss)
%u the user's name
%% translates to a single percent sign "%"
The files are not automatically rotated if they get large so you should
perhaps put a week in the filename at least.
Escape backslashes with another backslash, like so:
C:\path\to\log.txt -> C:\\path\\to\\log.txt
- log-file-open-files (def. 10)
The number of log files to keep open at once. Unless you use dynamic
patterns in the path, the value of this variable won't matter. However,
if, for example, you use a player's username in the filename and you
have many users who cause logged events to occur, files would have
to be opened for each user and this parameter would matter.
- log-database (def. false)
Log blacklist events to database.
- log-database-dsn (def. "jdbc:mysql://localhost:3306/minecraft")
Connection string. A string to use for MySQL would be:
jdbc:mysql://localhost:3306/minecraft
The "minecraft" part at the end is the database name.
Escape colons with a backslash, like so:
jdbc:mysql://localhost:3306/minecraft
->
jdbc\:mysql\://localhost\:3306/minecraft
- log-database-user (def. "root")
Database username.
- log-database-pass (def. "")
Database password.
- log-database-table (def. "blacklist_events")
Database table to use.
Commands
--------
- /stopfire and /allowfire
Disables and enables fire spread globally. Both commands require the
permission to use only "/stopfire. Re-enabling fire spread with this
command will not override other fire spread control features of
WorldGuard. Note that disabling fire does not disable fire damage
but fire at least won't spread.
- /god
Toggles your invincibility. Players must have permission to use "/god"
to be able to use this command. You can also use this command to
toggle the invincibility of others although you must have the
"/godother" permission.
Server Commands
---------------
- fire-stop and fire-allow
Disables and enables fire spread globally. Re-enabling fire spread
with this command will not override other fire spread control features
of WorldGuard. Note that disabling fire does not disable fire damage
but fire at least won't spread.
Blacklists
----------
Blacklists let you control the use of blocks and items. You can have
certain rules apply to only some groups.
Edit the included worldguard-blacklist.txt file and follow the
instructions inside. The file comes with the download for WorldGuard.
Other Features
--------------
To give someone invincibility every time s/he joins the server, create
a wg-invincible group and add the group to the user or have the user's
group inherit this group.
To give someone the ability to breathe under water, create
a wg-amphibious group and add the group to the user or have the user's
group inherit this group.
Thanks
------
While I would like to thank everyone for their support, I would like to
say thanks to the following individuals for their direct
contributions to WorldGuard:
- Sturmeh, for contributing the original durability workaround
- Meaglin, for changing the on flow hook at my request
- Dinnerbone, for implementing the on item pick up hook at my request,
and also for figuring out the durability bug in the process
-86
View File
@@ -1,86 +0,0 @@
<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"/>
<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 dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
</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="WorldGuard.jar"/>
</manifest>
<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">
<input message="Enter version:" addproperty="version"/>
<antcall target="jar"/>
<delete dir="${release.dir}"/>
<mkdir dir="${release.dir}"/>
<copy todir="${release.dir}">
<fileset dir="."/>
<globmapper from="*.txt" to="*.txt"/>
</copy>
<copy file="worldguard.properties" todir="${release.dir}"/>
<copy tofile="${release.dir}/WorldGuard.jar" file="${dist.dir}/WorldGuard.jar"/>
<zip destfile="${release.dir}/worldguard-${version}.zip" basedir="${release.dir}" excludes="*.zip"/>
<mkdir dir="${release.dir}/src"/>
<copy todir="${release.dir}/src">
<fileset dir="${src.dir}"/>
</copy>
<zip destfile="${release.dir}/worldguard-${version}-source.zip" basedir="${release.dir}" excludes="*.zip"/>
</target>
<!-- Clean the output -->
<target name="clean">
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
<delete dir="${release.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>
@@ -1,21 +1,24 @@
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`world` varchar(32) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
ALTER TABLE `blacklist_events` ADD `world` VARCHAR( 32 ) NOT NULL
+274
View File
@@ -0,0 +1,274 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.7-SNAPSHOT</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
<license>
<name>GNU General Public License 2.0</name>
<url>LICENSE.txt</url>
<distribution>repo</distribution>
<comments>License on all contributions</comments>
</license>
</licenses>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>rebar</artifactId>
<version>4.1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.2-R0.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.7.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
</distributionManagement>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>blacklist.txt</include>
<include>builtin_rules.yml</include>
<include>rulelist.yml</include>
</includes>
</resource>
<resource>
<targetPath></targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>models/</include>
<include>sql/</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
<include>com.sk89q:rebar</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</project>
-748
View File
@@ -1,748 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
/**
*
* @author sk89q
*/
public class BlacklistEntry {
/**
* Used to prevent spamming.
*/
private static Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
/**
* Parent blacklist entry.
*/
private Blacklist blacklist;
/**
* List of groups to not affect.
*/
private Set<String> ignoreGroups;
/**
* List of actions to perform on destruction.
*/
private String[] destroyActions;
/**
* List of actions to perform on break.
*/
private String[] breakActions;
/**
* List of actions to perform on left click.
*/
private String[] destroyWithActions;
/**
* List of actions to perform on block placement.
*/
private String[] placeActions;
/**
* List of actions to perform on item use.
*/
private String[] useActions;
/**
* List of actions to perform on right click upon.
*/
private String[] rightClickActions;
/**
* List of actions to perform on drop.
*/
private String[] dropActions;
/**
* List of actions to perform on drop.
*/
private String[] acquireActions;
/**
* Message for users.
*/
private String message;
/**
* Comment for administrators.
*/
private String comment;
/**
* Used to ignore messages.
*/
private static ActionHandler silentHandler = new ActionHandler() {
public void log(String itemName) {}
public void kick(String itemName) {}
public void ban(String itemName) {}
public void notifyAdmins(String itemName) {}
public void tell(String itemName) {}
};
/**
* Construct the object.
*
* @param blacklist
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
}
/**
* @return the ignoreGroups
*/
public String[] getIgnoreGroups() {
return ignoreGroups.toArray(new String[ignoreGroups.size()]);
}
/**
* @param ignoreGroups the ignoreGroups to set
*/
public void setIgnoreGroups(String[] ignoreGroups) {
Set<String> ignoreGroupsSet = new HashSet<String>();
for (String group : ignoreGroups) {
ignoreGroupsSet.add(group.toLowerCase());
}
this.ignoreGroups = ignoreGroupsSet;
}
/**
* @return
*/
public String[] getDestroyActions() {
return destroyActions;
}
/**
* @param actions
*/
public void setDestroyActions(String[] actions) {
this.destroyActions = actions;
}
/**
* @return
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param action
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return
*/
public String[] getRightClickActions() {
return rightClickActions;
}
/**
* @param actions
*/
public void setRightClickActions(String[] actions) {
this.rightClickActions = actions;
}
/**
* @return
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the comment
*/
public String getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
* Returns true if this player should be ignored.
*
* @param player
* @return
*/
public boolean shouldIgnore(Player player) {
if (ignoreGroups == null) {
return false;
}
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
return true;
}
}
return false;
}
/**
* Announces a message to all administrators.
*
* @param str
*/
public void notifyAdmins(String str) {
for (Player player : etc.getServer().getPlayerList()) {
if (player.canUseCommand("/wprotectalerts")
|| player.canUseCommand("/worldguardnotify")) {
player.sendMessage(Colors.LightGray + "WG: " + str);
}
}
}
/**
* Ban a player.
*
* @param player
* @param msg
*/
public void banPlayer(Player player, String msg) {
etc.getServer().ban(player.getName());
etc.getLoader().callHook(PluginLoader.Hook.BAN, new Object[]{
player.getUser(), player.getUser(), msg
});
player.kick(msg);
}
/**
* Called on block destruction. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onDestroy(final Block block, final Player player) {
if (destroyActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDestroyAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You are not allowed to destroy " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You are not allowed to destroy " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (destroy) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You are not allowed to destroy " + itemName + ".");
}
};
return process(block.getType(), player, destroyActions, handler, false, false);
}
/**
* Called on block break. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onBreak(final Block block, final Player player) {
if (breakActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logBreakAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You are not allowed to break " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You are not allowed to break " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (break) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You are not allowed to break " + itemName + ".");
}
};
return process(block.getType(), player, breakActions, handler, true, false);
}
/**
* Called on left click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDestroyWith(final int item, final Player player) {
if (destroyWithActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDestroyWithAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't destroy with " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't destroy with " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (destroy w/) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You can't destroy with " + itemName + ".");
}
};
return process(item, player, destroyWithActions, handler, false, false);
}
/**
* Called on block placement. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onPlace(final int item, final Player player) {
if (placeActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logPlaceAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't place " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't place " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (place) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You can't place " + itemName + ".");
}
};
return process(item, player, placeActions, handler, true, false);
}
/**
* Called on use. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onUse(final int item, final Player player) {
if (useActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logUseAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't use " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't use " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (use) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to use " + itemName + ".");
}
};
return process(item, player, useActions, handler, false, false);
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onRightClick(final Block block, final Player player) {
if (useActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logRightClickAttempt(player, block, comment);
}
public void kick(String itemName) {
player.kick("You can't use " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't use " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (use) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to use " + itemName + ".");
}
};
return process(block.getType(), player, useActions, handler, false, false);
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentUse(final Block block, final Player player) {
if (useActions == null) {
return true;
}
return process(block.getType(), player, useActions, silentHandler, false, true);
}
/**
* Called on item drop. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDrop(final int item, final Player player) {
if (dropActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logDropAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't drop " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't drop " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (drop) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to drop " + itemName + ".");
}
};
return process(item, player, dropActions, handler, true, false);
}
/**
* Called on item acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onAcquire(final int item, final Player player) {
if (acquireActions == null) {
return true;
}
final BlacklistEntry entry = this;
ActionHandler handler = new ActionHandler() {
public void log(String itemName) {
blacklist.getLogger().logAcquireAttempt(player, item, comment);
}
public void kick(String itemName) {
player.kick("You can't acquire " + itemName);
}
public void ban(String itemName) {
entry.banPlayer(player, "Banned: You can't acquire " + itemName);
}
public void notifyAdmins(String itemName) {
entry.notifyAdmins(player.getName() + " (acquire) " + itemName
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
public void tell(String itemName) {
player.sendMessage(Colors.Yellow + "You're not allowed to acquire " + itemName + ".");
}
};
return process(item, player, acquireActions, handler, true, false);
}
/**
* Called on item acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentAcquire(final int item, final Player player) {
if (acquireActions == null) {
return true;
}
return process(item, player, acquireActions, silentHandler, false, true);
}
/**
* Internal method to handle the actions.
*
* @param id
* @param player
* @param actions
* @param handler
* @param allowRepeat
* @param silent
* @return
*/
private boolean process(int id, Player player, String[] actions,
ActionHandler handler, boolean allowRepeat, boolean silent) {
if (shouldIgnore(player)) {
return true;
}
String name = player.getName();
long now = System.currentTimeMillis();
boolean repeating = false;
// Check to see whether this event is being repeated
BlacklistTrackedEvent tracked = lastAffected.get(name);
if (tracked != null) {
if (tracked.getId() == id && tracked.getTime() > now - 3000) {
repeating = true;
} else {
tracked.setTime(now);
tracked.setId(id);
}
} else {
lastAffected.put(name, new BlacklistTrackedEvent(id, now));
}
boolean ret = true;
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (this.message != null) {
player.kick(String.format(this.message,
etc.getDataSource().getItem(id)));
} else {
handler.kick(etc.getDataSource().getItem(id));
}
// Ban
} else if (action.equalsIgnoreCase("ban")) {
handler.ban(etc.getDataSource().getItem(id));
if (this.message != null) {
banPlayer(player, "Banned: " + String.format(this.message,
etc.getDataSource().getItem(id)));
} else {
handler.ban(etc.getDataSource().getItem(id));
}
} else if (!repeating || allowRepeat) {
// Notify
if (action.equalsIgnoreCase("notify")) {
handler.notifyAdmins(etc.getDataSource().getItem(id));
// Log
} else if (action.equalsIgnoreCase("log")) {
handler.log(etc.getDataSource().getItem(id));
// Tell
} else if (action.equalsIgnoreCase("tell")) {
if (this.message != null) {
player.sendMessage(Colors.Yellow +
String.format(message, etc.getDataSource().getItem(id))
+ ".");
} else {
handler.tell(etc.getDataSource().getItem(id));
}
}
}
}
return ret;
}
/**
* Forget a player.
*
* @param player
*/
public static void forgetPlayer(Player player) {
lastAffected.remove(player.getName());
}
/**
* Forget all players.
*
* @param player
*/
public static void forgetAllPlayers() {
lastAffected.clear();
}
/**
* Gets called for actions.
*/
private static interface ActionHandler {
public void log(String itemName);
public void kick(String itemName);
public void ban(String itemName);
public void notifyAdmins(String itemName);
public void tell(String itemName);
}
}
-165
View File
@@ -1,165 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Set;
import java.util.HashSet;
/**
*
* @author sk89q
*/
public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* List of logger handlers.
*/
private Set<BlacklistLoggerHandler> handlers
= new HashSet<BlacklistLoggerHandler>();
/**
* Add a handler.
*
* @param handler
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Add a handler.
*
* @param handler
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
}
/**
* Add a handler.
*
* @param handler
*/
public void clearHandlers() {
handlers.clear();
}
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDestroyAttempt(player, block, comment);
}
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logBreakAttempt(player, block, comment);
}
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logUseAttempt(player, item, comment);
}
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logRightClickAttempt(Player player, Block block, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logRightClickAttempt(player, block, comment);
}
}
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDestroyWithAttempt(player, item, comment);
}
}
/**
* Log a place attempt.
*
* @param player
* @param item
*/
public void logPlaceAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logPlaceAttempt(player, item, comment);
}
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logDropAttempt(player, item, comment);
}
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logAcquireAttempt(player, item, comment);
}
}
/**
* Close the connection.
*/
public void close() {
for (BlacklistLoggerHandler handler : handlers) {
handler.close();
}
}
}
-86
View File
@@ -1,86 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Interface for loggers for the blacklist.
*
* @author sk89q
*/
public interface BlacklistLoggerHandler {
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment);
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment);
/**
* Log a use attempt.
*
* @param player
* @param block
*/
public void logUseAttempt(Player player, int item, String comment);
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment);
/**
* Log a place attempt.
*
* @param player
* @param item
*/
public void logPlaceAttempt(Player player, int item, String comment);
/**
* Log a right click on attempt.
*
* @param player
* @param item
*/
public void logRightClickAttempt(Player player, Block block, String comment);
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment);
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment);
/**
* Close the logger.
*/
public void close();
}
-143
View File
@@ -1,143 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to destroy " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to break " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logRightClickAttempt(Player player, Block block, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to right click " + getFriendlyItemName(block.getType())
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log an attempt to destroy with an item.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to destroy with " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a block creation attempt.
*
* @param player
* @param item
*/
public void logPlaceAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to place " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a use attempt.
*
* @param player
* @param item
*/
public void logUseAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to use " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to drop " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
logger.log(Level.INFO, "WorldGuard: " + player.getName()
+ " tried to acquire " + getFriendlyItemName(item)
+ (comment != null ? " (" + comment + ")" : ""));
}
/**
* Get an item's friendly name with its ID.
*
* @param id
*/
private static String getFriendlyItemName(int id) {
return etc.getDataSource().getItem(id) + " (#" + id + ")";
}
/**
* Close the connection.
*/
public void close() {
}
}
-227
View File
@@ -1,227 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
/**
*
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* DSN.
*/
private String dsn;
/**
* Username.
*/
private String user;
/**
* Password.
*/
private String pass;
/**
* Table.
*/
private String table;
/**
* Database connection.
*/
private Connection conn;
/**
* Construct the object.
*
* @param dsn
* @param user
* @param pass
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
}
/**
* Gets the database connection.
*
* @return
* @throws SQLException
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(dsn, user, pass);
}
return conn;
}
/**
* Log an event to the database.
*
* @param event
* @param name
* @param x
* @param y
* @param z
* @param item
* @param comment
*/
private void logEvent(String event, String name, int x, int y, int z, int item,
String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
stmt.setString(2, name);
stmt.setInt(3, x);
stmt.setInt(4, y);
stmt.setInt(5, z);
stmt.setInt(6, item);
stmt.setInt(7, (int)(System.currentTimeMillis() / 1000));
stmt.setString(8, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
+ e.getMessage());
}
}
/**
* Log a block destroy attempt.
*
* @param player
* @param block
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
logEvent("DESTROY", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
logEvent("BREAK", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logRightClickAttempt(Player player, Block block, String comment) {
logEvent("RIGHT_CLICK", player.getName(),
block.getX(), block.getY(), block.getZ(), block.getType(),
comment);
}
/**
* Right a left click attempt.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
logEvent("DESTROY_WITH", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log a place attempt.
*
* @param player
* @param item
*/
public void logPlaceAttempt(Player player, int item, String comment) {
logEvent("PLACE", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log a use attempt.
*
* @param player
* @param item
*/
public void logUseAttempt(Player player, int item, String comment) {
logEvent("USE", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
logEvent("DROP", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Log an aquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
logEvent("AQUIRE", player.getName(),
(int)Math.floor(player.getX()), (int)Math.floor(player.getY()),
(int)Math.floor(player.getZ()), item, comment);
}
/**
* Close the connection.
*/
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
}
}
}
-190
View File
@@ -1,190 +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.util.List;
import java.util.ArrayList;
import java.net.URL;
import java.io.*;
import java.lang.reflect.*;
/**
* 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();
List<String> missingFeatures = new ArrayList<String>();
registerHook("COMMAND", PluginListener.Priority.MEDIUM);
registerHook("SERVERCOMMAND", PluginListener.Priority.MEDIUM);
registerHook("EXPLODE", PluginListener.Priority.HIGH);
registerHook("IGNITE", PluginListener.Priority.HIGH);
registerHook("FLOW", PluginListener.Priority.HIGH);
registerHook("LOGINCHECK", PluginListener.Priority.HIGH);
registerHook("LOGIN", PluginListener.Priority.MEDIUM);
registerHook("BLOCK_CREATED", PluginListener.Priority.HIGH);
registerHook("BLOCK_DESTROYED", PluginListener.Priority.CRITICAL);
registerHook("BLOCK_BROKEN", PluginListener.Priority.HIGH);
registerHook("BLOCK_PLACE", PluginListener.Priority.HIGH);
registerHook("DISCONNECT", PluginListener.Priority.HIGH);
registerHook("ITEM_DROP", PluginListener.Priority.HIGH);
registerHook("ITEM_USE", PluginListener.Priority.HIGH);
registerHook("ITEM_PICK_UP", PluginListener.Priority.HIGH);
registerHook("SIGN_CHANGE", PluginListener.Priority.HIGH);
registerHook("OPEN_INVENTORY", PluginListener.Priority.HIGH);
registerHook("INVENTORY_CHANGE", PluginListener.Priority.HIGH);
registerHook("BLOCK_PHYSICS", PluginListener.Priority.MEDIUM);
registerHook("HEALTH_CHANGE", PluginListener.Priority.MEDIUM);
registerHook("DAMAGE", PluginListener.Priority.MEDIUM);
registerHook("LIQUID_DESTROY", PluginListener.Priority.MEDIUM);
if (missingFeatures.size() > 0) {
logger.log(Level.WARNING, "WorldGuard: Your version of hMod does not support "
+ concatMissingFeatures(missingFeatures) + ".");
} else {
logger.log(Level.INFO, "WorldGuard: Your version of hMod appears to"
+ " support all features.");
}
}
/**
* Conditionally registers a hook.
*
* @param name
* @param priority
* @return where the hook was registered correctly
*/
public boolean registerHook(String name, PluginListener.Priority priority) {
try {
PluginLoader.Hook hook = PluginLoader.Hook.valueOf(name);
etc.getLoader().addListener(hook, listener, this, priority);
return true;
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING, "WorldGuard: Missing hook " + name + "!");
return false;
}
}
/**
* Enables the plugin.
*/
@Override
public void enable() {
logger.log(Level.INFO, "WorldGuard version " + getVersion() + " loaded");
listener.loadConfiguration();
etc.getInstance().addCommand("/stopfire", "Globally stop fire spread");
etc.getInstance().addCommand("/allowfire", "Globally re-enable fire spread");
}
/**
* Disables the plugin.
*/
@Override
public void disable() {
try {
listener.disable();
BlacklistEntry.forgetAllPlayers();
} catch (Throwable t) {
}
etc.getInstance().removeCommand("/stopfire");
etc.getInstance().removeCommand("/allowfire");
}
/**
* Get the WorldGuard version.
*
* @return
*/
private String getVersion() {
try {
String classContainer = WorldGuard.class.getProtectionDomain()
.getCodeSource().getLocation().toString();
URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(manifestUrl.openStream());
Attributes attrib = manifest.getMainAttributes();
String ver = (String)attrib.getValue("WorldGuard-Version");
return ver != null ? ver : "(unavailable)";
} catch (IOException e) {
return "(unknown)";
}
}
/**
* Joins a string from an array of strings.
*
* @param str
* @param delimiter
* @return
*/
private static String concatMissingFeatures(List<String> str) {
if (str.isEmpty()) {
return "";
}
int size = str.size();
StringBuilder buffer = new StringBuilder();
buffer.append("(1) ");
buffer.append(str.get(0));
for (int i = 1; i < size; i++) {
if (i == size - 1) {
buffer.append(" or ");
buffer.append("(");
buffer.append(i + 1);
buffer.append(") ");
buffer.append(str.get(i));
} else {
buffer.append(", ");
buffer.append("(");
buffer.append(i + 1);
buffer.append(") ");
buffer.append(str.get(i));
}
}
return buffer.toString();
}
}
File diff suppressed because it is too large. Load diff
@@ -1,271 +0,0 @@
// $Id$
/*
* WorldEdit
* 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.worldedit.blocks;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumSet;
/**
* Block types.
*
* @author sk89q
*/
public enum BlockType {
AIR(0, "Air", "air"),
STONE(1, "Stone", new String[]{"stone", "rock"}),
GRASS(2, "Grass", "grass"),
DIRT(3, "Dirt", "dirt"),
COBBLESTONE(4, "Cobblestone", "cobblestone"),
WOOD(5, "Wood", "wood"),
SAPLING(6, "Sapling", "sapling"),
BEDROCK(7, "Bedrock", "bedrock"),
WATER(8, "Water", "watermoving"),
STATIONARY_WATER(9, "Water (stationary)", "water"),
LAVA(10, "Lava", "lavamoving"),
STATIONARY_LAVA(11, "Lava (stationary)", "lava"),
SAND(12, "Sand", "sand"),
GRAVEL(13, "Gravel", "gravel"),
GOLD_ORE(14, "Gold ore", "goldore"),
IRON_ORE(15, "Iron ore", "ironore"),
COAL_ORE(16, "Coal ore", "coalore"),
LOG(17, "Log", "log"),
LEAVES(18, "Leaves", "leaves"),
SPONGE(19, "Sponge", "sponge"),
GLASS(20, "Glass", "glass"),
CLOTH(35, "Cloth", "cloth"),
YELLOW_FLOWER(37, "Yellow flower", "yellowflower"),
RED_FLOWER(38, "Red rose", new String[]{"redflower", "redrose"}),
BROWN_MUSHROOM(39, "Brown mushroom", "brownmushroom"),
RED_MUSHROOM(40, "Red mushroom", "redmushroom"),
GOLD_BLOCK(41, "Gold block", new String[]{"gold", "goldblock"}),
IRON_BLOCK(42, "Iron block", new String[]{"iron", "ironblock"}),
DOUBLE_STEP(43, "Double step", "doublestep"),
STEP(44, "Step", "step"),
BRICK(45, "Brick", "brick"),
TNT(46, "TNT", "tnt"),
BOOKCASE(47, "Bookcase", new String[]{"bookshelf", "bookshelf"}),
MOSSY_COBBLESTONE(48, "Cobblestone (mossy)", "mossycobblestone"),
OBSIDIAN(49, "Obsidian", "obsidian"),
TORCH(50, "Torch", "torch"),
FIRE(51, "Fire", "fire"),
MOB_SPAWNER(52, "Mob spawner", "mobspawner"),
WOODEN_STAIRS(53, "Wooden stairs", "woodstairs"),
CHEST(54, "Chest", "chest"),
REDSTONE_WIRE(55, "Redstone wire", "redstone"),
DIAMOND_ORE(56, "Diamond ore", "diamondore"),
DIAMOND_BLOCK(57, "Diamond block", new String[]{"diamond", "diamondblock"}),
WORKBENCH(58, "Workbench", "workbench"),
CROPS(59, "Crops", "crops"),
SOIL(60, "Soil", "soil"),
FURNACE(61, "Furnace", "furnace"),
BURNING_FURNACE(62, "Furnace (burning)", "burningfurnace"),
SIGN_POST(63, "Sign post", new String[]{"sign", "signpost"}),
WOODEN_DOOR(64, "Wooden door", "wooddoor"),
LADDER(65, "Ladder", "ladder"),
MINECART_TRACKS(66, "Minecart tracks", new String[]{"track", "tracks"}),
COBBLESTONE_STAIRS(67, "Cobblestone stairs", "cobblestonestairs"),
WALL_SIGN(68, "Wall sign", "wallsign"),
LEVER(69, "Lever", "level"),
STONE_PRESSURE_PLATE(70, "Stone pressure plate", "stonepressureplate"),
IRON_DOOR(71, "Iron Door", "irondoor"),
WOODEN_PRESSURE_PLATE(72, "Wooden pressure plate", "woodpressureplate"),
REDSTONE_ORE(73, "Redstone ore", "redstoneore"),
GLOWING_REDSTONE_ORE(74, "Glowing redstone ore", "glowingredstoneore"),
REDSTONE_TORCH_OFF(75, "Redstone torch (off)",
new String[]{"redstonetorch"," redstonetorchon"}),
REDSTONE_TORCH_ON(76, "Redstone torch (on)", "redstonetorchon"),
STONE_BUTTON(77, "Stone Button", "stonebutton"),
SNOW(78, "Snow", "snow"),
ICE(79, "Ice", "ice"),
SNOW_BLOCK(80, "Snow block", "snowblock"),
CACTUS(81, "Cactus", "cactus"),
CLAY(82, "Clay", "clay"),
REED(83, "Reed", "reed"),
JUKEBOX(84, "Jukebox", "jukebox"),
FENCE(85, "Fence", "fence"),
PUMPKIN(86, "Pumpkin", "pumpkin"),
RED_BLOCK(87, "Cobblestone (red mossy)", new String[]{"redmossycobblestone", "redcobblestone"}),
HELL_DIRT(88, "Mud", "mud"),
HELL_GOLD(89, "Brittle gold", "brittlegold"),
PORTAL(90, "Portal", "portal"),
LIGHTED_PUMPKIN(91, "Pumpkin (on)", new String[]{"pumpkinlighted", "pumpkinon", "litpumpkin"});
/**
* Stores a map of the IDs for fast access.
*/
private static final Map<Integer,BlockType> ids = new HashMap<Integer,BlockType>();
/**
* Stores a map of the names for fast access.
*/
private static final Map<String,BlockType> lookup = new HashMap<String,BlockType>();
private final int id;
private final String name;
private final String[] lookupKeys;
static {
for(BlockType type : EnumSet.allOf(BlockType.class)) {
ids.put(type.id, type);
for (String key : type.lookupKeys) {
lookup.put(key, type);
}
}
}
/**
* Construct the type.
*
* @param id
* @param name
*/
BlockType(int id, String name, String lookupKey) {
this.id = id;
this.name = name;
this.lookupKeys = new String[]{lookupKey};
}
/**
* Construct the type.
*
* @param id
* @param name
*/
BlockType(int id, String name, String[] lookupKeys) {
this.id = id;
this.name = name;
this.lookupKeys = lookupKeys;
}
/**
* Return type from ID. May return null.
*
* @param id
* @return
*/
public static BlockType fromID(int id) {
return ids.get(id);
}
/**
* Return type from name. May return null.
*
* @param name
* @return
*/
public static BlockType lookup(String name) {
return lookup.get(name.toLowerCase());
}
/**
* Get block numeric ID.
*
* @return
*/
public int getID() {
return id;
}
/**
* Get user-friendly block name.
*
* @return
*/
public String getName() {
return name;
}
/**
* Checks to see whether a block should be placed last.
*
* @param id
* @return
*/
public boolean shouldPlaceLast() {
return shouldPlaceLast(id);
}
/**
* Checks to see whether a block should be placed last.
*
* @param id
* @return
*/
public static boolean shouldPlaceLast(int id) {
return id == 6 // Saplings
|| id == 37 // Yellow flower
|| id == 38 // Red flower
|| id == 39 // Brown mushroom
|| id == 40 // Red mush room
|| id == 50 // Torch
|| id == 51 // Fire
|| id == 55 // Redstone wire
|| id == 59 // Crops
|| id == 63 // Sign post
|| id == 64 // Wooden door
|| id == 65 // Ladder
|| id == 66 // Minecart tracks
|| id == 68 // Wall sign
|| id == 69 // Lever
|| id == 70 // Stone pressure plate
|| id == 71 // Iron door
|| id == 72 // Wooden pressure plate
|| id == 75 // Redstone torch (off)
|| id == 76 // Redstone torch (on)
|| id == 77 // Stone button
|| id == 78 // Snow
|| id == 81 // Cactus
|| id == 83 // Reed
|| id == 90; // Portal
}
/**
* Checks whether a block can be passed through.
*
* @param id
* @return
*/
public static boolean canPassThrough(int id) {
return id == 0 // Air
|| id == 6 // Saplings
|| id == 37 // Yellow flower
|| id == 38 // Red flower
|| id == 39 // Brown mushroom
|| id == 40 // Red mush room
|| id == 50 // Torch
|| id == 51 // Fire
|| id == 55 // Redstone wire
|| id == 59 // Crops
|| id == 63 // Sign post
|| id == 65 // Ladder
|| id == 66 // Minecart tracks
|| id == 68 // Wall sign
|| id == 69 // Lever
|| id == 70 // Stone pressure plate
|| id == 72 // Wooden pressure plate
|| id == 75 // Redstone torch (off)
|| id == 76 // Redstone torch (on)
|| id == 77 // Stone button
|| id == 78 // Snow
|| id == 83 // Reed
|| id == 90; // Portal
}
}
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>default</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}-${project.version}.jar</source>
<destName>WorldGuard.jar</destName>
<outputDirectory>/</outputDirectory>
<filtered>false</filtered>
</file>
<file>
<source>README.html</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
</files>
<fileSets>
<fileSet>
<includes>
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_storage.sql</include>
<include>contrib/region_storage_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
</assembly>
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* An action that will be performed if the conditions are matched of the rule.
*
* @param <T> implementation-specific context object
*/
public interface Action<T extends Context> {
/**
* Apply the action.
*
* @param context implementation-specific context object
*/
void apply(T context);
}
@@ -0,0 +1,75 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* An attachment is analogous to an event.
*/
public final class Attachment {
private static int NEXT_ID = 0;
private final int id;
private final String alias;
/**
* Create a new attachment with the given alias. The alias is used in rule list
* files.
*
* @param alias alias name
*/
public Attachment(String alias) {
this.alias = alias;
// No internal ID
id = -1;
}
/**
* Create a new attachment with the given alias. The alias is used in rule list
* files.
*
* @param alias alias name
* @param isInternal true to assign this attachment a standard internal ID
*/
Attachment(String alias, boolean isInternal) {
this.alias = alias;
id = isInternal ? NEXT_ID++ : -1;
}
/**
* Get the internal ID.
*
* @return ID number, possibly -1 for no internal ID
*/
int getId() {
return id;
}
/**
* Get the alias used inside rule list files.
*
* @return alias
*/
public String getAlias() {
return alias;
}
}
@@ -0,0 +1,77 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sk89q.rebar.config.Loader;
import com.sk89q.rebar.config.LoaderBuilderException;
/**
* A database of valid attachments.
*/
public final class AttachmentManager implements Loader<Attachment> {
private Set<Attachment> attachments = new HashSet<Attachment>();
private Map<String, Attachment> aliasMap = new HashMap<String, Attachment>();
public AttachmentManager() {
}
/**
* Register an attachment.
*
* @param attachment the attachment
*/
public synchronized void register(Attachment attachment) {
if (attachments.contains(attachment)
|| aliasMap.containsKey(attachment.getAlias().toLowerCase())) {
throw new IllegalArgumentException("Attachment '" + attachment + "' already registered.");
}
attachments.add(attachment);
aliasMap.put(attachment.getAlias().toLowerCase(), attachment);
}
/**
* Get an attachment by its alias.
*
* @param alias alias, case in-sensitive
* @return an attachment or null
*/
public synchronized Attachment lookup(String alias) {
return aliasMap.get(alias.toLowerCase());
}
@Override
public Attachment read(Object value) throws LoaderBuilderException {
String id = String.valueOf(value);
Attachment attachment = lookup(id);
if (attachment == null) {
throw new LoaderBuilderException("Unknown RuleList attachment: " + id);
}
return attachment;
}
}
@@ -0,0 +1,88 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* A context has some shared variables that may be used by a number of different
* events. Because the context contains common information, criteria and
* actions do not have to be custom tailored to specific implementation-specific
* events, and can refer to the the properties set on the context. The place
* where the information is known as to what is considered the proper valid
* value of a common property is during the initial handling of
* the event in the implementation.
* </p>
* Implementations need to have custom contexts that can carry more
* information than offered in this abstract implementation. Criteria and
* actions can be implement-specific by tailoring themselves to one of these
* implementation-specific contexts.
*
* @author sk89q
*/
public abstract class Context {
private boolean matches = false;
private boolean cancelled = false;
/**
* Gets whether the event associated with this context has been set to
* be cancelled.
*
* @return true if the event is set to be cancelled
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Set the event associated with this context to be cancelled, if possible.
*/
public void cancel() {
setCancelled(true);
}
/**
* Set the event associated with this context to be cancelled, if possible.
*
* @param cancelled true to cancel
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Set as to whether all the conditions associated with this context have
* evaluated to being true.
*
* @param matches match state
*/
void setMatches(boolean matches) {
this.matches = matches;
}
/**
* Returns whether all the conditions associated with this context
* have been evaluated to true.
*
* @return true if all the conditions have been true
*/
public boolean matches() {
return matches;
}
}
@@ -0,0 +1,37 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* A criteria that is evaluated to decide whether the rule should undergo
* further processing.
*
* @param <T> an implementation-specific context
*/
public interface Criteria<T extends Context> {
/**
* Returns whether the current event / context matches this criteria.
*
* @param context context to verify
* @return true if it matches
*/
boolean matches(T context);
}
@@ -0,0 +1,80 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY), without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* Contains names of standard attachments.
*/
public final class DefaultAttachments {
public final static Attachment BLOCK_BREAK = new Attachment("block-break", true);
public final static Attachment BLOCK_PLACE = new Attachment("block-place", true);
public final static Attachment BLOCK_SPREAD = new Attachment("block-spread", true);
public final static Attachment BLOCK_PHYSICS = new Attachment("block-physics", true);
public final static Attachment BLOCK_INTERACT = new Attachment("block-interact", true);
public final static Attachment BLOCK_FADE = new Attachment("block-fade", true);
public final static Attachment BLOCK_FORM = new Attachment("block-form", true);
public final static Attachment PLAYER_JOIN = new Attachment("player-join", true);
public final static Attachment PLAYER_RESPAWN = new Attachment("player-respawn", true);
public final static Attachment PLAYER_QUIT = new Attachment("player-quit", true);
public final static Attachment ENTITY_EXPLODE = new Attachment("entity-explode", true);
public final static Attachment ENTITY_DAMAGE = new Attachment("entity-damage", true);
public final static Attachment ENTITY_DEATH = new Attachment("entity-death", true);
public final static Attachment ENTITY_IGNITE = new Attachment("entity-ignite", true);
public final static Attachment ENTITY_SPAWN = new Attachment("entity-spawn", true);
public final static Attachment ENTITY_STRIKE = new Attachment("entity-strike", true);
public final static Attachment ENTITY_INTERACT = new Attachment("entity-interact", true);
public final static Attachment CHAT = new Attachment("chat", true);
public final static Attachment ITEM_DROP = new Attachment("item-drop", true);
public final static Attachment ITEM_PICKUP = new Attachment("item-pickup", true);
public final static Attachment ITEM_USE = new Attachment("item-use", true);
public final static Attachment WEATHER_PHENOMENON = new Attachment("weather-phenomenon", true);
public final static Attachment WEATHER_TRANSITION = new Attachment("weather-transition", true);
public final static Attachment WORLD_LOAD = new Attachment("world-load", true);
public final static Attachment WORLD_UNLOAD = new Attachment("world-unload", true);
public final static Attachment WORLD_SAVE = new Attachment("world-save", true);
private DefaultAttachments() {
}
/**
* Register the attachments in this class with the given manager.
*
* @param manager the manager
*/
public static void registerWith(AttachmentManager manager) {
for (Field field : DefaultAttachments.class.getFields()) {
if (Modifier.isStatic(field.getModifiers())
&& Attachment.class.isAssignableFrom(field.getType())) {
try {
manager.register((Attachment) field.get(null));
} catch (IllegalArgumentException e) {
throw new RuntimeException("Failed to register default attachment", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to register default attachment", e);
}
}
}
}
}
@@ -0,0 +1,99 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@link Rule} implementation with a list of {@link Criteria} and
* {@link Action}s.
*
* @param <T> underlying implementation-specific context
*/
public class DefinedRule<T extends Context> implements Rule<T> {
private static Logger logger = Logger.getLogger(Rule.class.getCanonicalName());
private final List<Criteria<T>> criterion = new LinkedList<Criteria<T>>();
private final List<Action<T>> actions = new LinkedList<Action<T>>();
/**
* Add a criteria to this rule.
*
* @param criteria the criteria
*/
public void add(Criteria<T> criteria) {
criterion.add(criteria);
}
/**
* Add an action to this rule.
*
* @param action the action
*/
public void add(Action<T> action) {
actions.add(action);
}
/**
* Returns whether criteria are defined.
*
* @return true if there are criteria
*/
public boolean hasCriterion() {
return criterion.size() > 0;
}
/**
* Returns whether actions are defined.
*
* @return true if there are actions
*/
public boolean hasActions() {
return actions.size() > 0;
}
@Override
public boolean matches(T context) {
for (Criteria<T> criteria : criterion) {
if (!criteria.matches(context)) {
context.setMatches(false);
return false;
}
}
context.setMatches(true);
return true;
}
@Override
public void apply(T context) {
for (Action<T> action : actions) {
try {
action.apply(context);
} catch (Throwable t) {
logger.log(Level.WARNING, "Failed to apply action of rule", t);
}
}
}
}
@@ -0,0 +1,42 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import com.sk89q.rebar.config.LoaderBuilderException;
public class DefinitionException extends LoaderBuilderException {
private static final long serialVersionUID = -5429457695711163632L;
public DefinitionException() {
}
public DefinitionException(String message) {
super(message);
}
public DefinitionException(Throwable cause) {
super(cause);
}
public DefinitionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,47 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class DefinitionInitializeEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final RuleListsManager ruleListsManager;
public DefinitionInitializeEvent(RuleListsManager ruleListsManager) {
this.ruleListsManager = ruleListsManager;
}
public RuleListsManager getManager() {
return ruleListsManager;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -0,0 +1,76 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.HashMap;
import java.util.Map;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.ConfigurationValue;
import com.sk89q.rebar.config.Loader;
/**
* Manages loaders for definitions of the given generic type.
*
* @author sk89q
* @param <V> type to create
*/
public class DefinitionManager<V> {
/**
* Map of factories.
*/
private Map<String, Loader<? extends V>> factories = new HashMap<String, Loader<? extends V>>();
/**
* Register a loader.
*
* @param id ID, case does not matter
* @param factory factory
*/
public void register(String id, Loader<? extends V> factory) {
factories.put(id.toLowerCase(), factory);
}
/**
* Create a new instance.
*
* @param id type
* @param node configuration node
* @param value short-hand value, possibly null
* @return an object
* @throws DefinitionException thrown on error when parsing or instantiating
*/
V newInstance(String id, ConfigurationNode node, ConfigurationValue value) throws DefinitionException {
Loader<? extends V> factory;
if (value != null) {
node = node.clone();
node.set("_", value.get());
}
if ((factory = factories.get(id)) != null) {
return factory.read(node);
}
throw new DefinitionException("Don't know what '" + id
+ "' is (typo? criteria/action doesn't exist?)");
}
}
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExpressionParser {
private static final char COLOR_CHAR = '\u00A7';
private static final Pattern classicColors = Pattern.compile("&[A-Fa-z0-9klmnor]");
public String format(Context context, String string) {
Matcher m = classicColors.matcher(string);
string = m.replaceAll(COLOR_CHAR + "$1");
return string;
}
}
@@ -0,0 +1,40 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* A criteria wrapper that inverts the condition.
*
* @author sk89q
* @param <T> underlying criteria
*/
public class InvertedCriteria<T extends Context> implements Criteria<T> {
private final Criteria<T> criteria;
public InvertedCriteria(Criteria<T> criteria) {
this.criteria = criteria;
}
@Override
public boolean matches(T context) {
return !criteria.matches(context);
}
}
@@ -0,0 +1,30 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* Attempts to resolve the requested object from other objects. For
* example, a block place event can have multiple 'relevant' blocks, such as
* the target block or the source block. A resolver is used to figure out
* which block is requested, and then the resolver would return the object
* requested by accessing it through a given context.
*/
public interface Resolver {
}
@@ -0,0 +1,63 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.HashMap;
import java.util.Map;
public class ResolverManager {
private final Map<Class<? extends Resolver>, Map<String, Resolver>> resolvers
= new HashMap<Class<? extends Resolver>, Map<String, Resolver>>();
private final Map<Resolver, String> reverse = new HashMap<Resolver, String>();
public <T extends Resolver> void register(Class<T> clazz, String id, T resolver) {
Map<String, Resolver> map = resolvers.get(clazz);
if (map == null) {
map = new HashMap<String, Resolver>();
resolvers.put(clazz, map);
}
reverse.put(resolver, id);
map.put(id.toLowerCase(), resolver);
}
public String getId(Object object) {
return reverse.get(object);
}
@SuppressWarnings("unchecked")
public <T extends Resolver> T get(Class<T> clazz, String id) throws DefinitionException {
Map<String, Resolver> map = resolvers.get(clazz);
if (map == null) {
throw new DefinitionException("Don't know how to resolve "
+ clazz.getCanonicalName());
}
Resolver resolver = map.get(id);
if (resolver == null) {
throw new DefinitionException("Don't know how to resolve "
+ clazz.getCanonicalName());
}
return (T) resolver;
}
}
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* A rule that may match a number of events and can be applied in
* a situation. See {@link DefinedRule} for a rule implementation that
* consists of constituent {@link Criteria}s and {@link Action}s.
*
* @author sk89q
* @param <T> implementation-specific context
*/
public interface Rule<T extends Context> {
boolean matches(T context);
void apply(T context);
}
@@ -0,0 +1,60 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.List;
/**
* A pair of attachments and a rule.
*/
public class RuleEntry {
private final List<Attachment> attachments;
private final Rule<?> rule;
/**
* Construct the rule entry with the list of attachments and rules.
*
* @param attachments attachment names
* @param rule rules
*/
public RuleEntry(List<Attachment> attachments, Rule<?> rule) {
this.attachments = attachments;
this.rule = rule;
}
/**
* Get the list of attachments.
*
* @return attachment
*/
public List<Attachment> getAttachments() {
return attachments;
}
/**
* Get the rule.
*
* @return rule
*/
public Rule<?> getRule() {
return rule;
}
}
@@ -0,0 +1,175 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.List;
import java.util.logging.Logger;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.ConfigurationValue;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.util.LoggerUtils;
/**
* A loader that will load rule definitions for the RuleLists.
*/
public class RuleEntryLoader extends AbstractNodeLoader<RuleEntry> {
public static final String INLINE = "_";
private static final Logger logger = LoggerUtils.getLogger(RuleEntryLoader.class);
private final AttachmentManager attachmentManager;
private final DefinitionLoader<Criteria<?>> criteriaLoader;
private final DefinitionLoader<Action<?>> actionLoader;
/**
* Construct the loader.
*
* @param ruleListsManager the action lists manager
*/
public RuleEntryLoader(RuleListsManager ruleListsManager) {
attachmentManager = ruleListsManager.getAttachments();
criteriaLoader = new DefinitionLoader<Criteria<?>>(ruleListsManager.getCriterion(), true);
actionLoader = new DefinitionLoader<Action<?>>(ruleListsManager.getActions(), false);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public RuleEntry read(ConfigurationNode node) {
if (node.size() == 0) {
return null;
}
List<Attachment> when = node.listOf("when", attachmentManager);
// Check to see if the rule has any events defined
if (when.size() == 0) {
logger.warning("A rule has missing 'when' clause:\n" + node.toString());
return null;
}
try {
DefinedRule rule = new DefinedRule();
// Get criterion from the 'if' subnode
for (Criteria criteria : node.listOf("if", criteriaLoader)) {
rule.add(criteria);
}
// Get actions from the 'then' subnode
for (Action action : node.listOf("then", actionLoader)) {
rule.add(action);
}
// A rule needs actions!
if (rule.hasActions()) {
return new RuleEntry(when, rule);
} else {
logger.warning("The following rule has no actions in:\n" + node.toString());
return null;
}
} catch (LoaderBuilderException e) {
logger.warning("A rule had the error '" + e.getMessage() + ", and the rule is:\n" + node.toString());
return null;
}
}
/**
* Inverts an criteria, wrapping it in a {@link InvertedCriteria}.
*
* @param criteria to invert
* @param inverted true to invert (false to not)
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <V> V invertCriteria(V object, boolean inverted) {
if (object instanceof Criteria && inverted) {
return (V) new InvertedCriteria((Criteria<?>) object);
}
return object;
}
/**
* Loads specific definitions (criterion or actions) defined.
*
* @param <T> type of definition ({@link Action} or {@link Criteria})
*/
private class DefinitionLoader<T> extends AbstractNodeLoader<T> {
private final DefinitionManager<T> manager;
private final boolean strict;
/**
* Construct the object.
*
* @param manager the definition manager
* @param strict true to throw exceptions on error
*/
public DefinitionLoader(DefinitionManager<T> manager, boolean strict) {
this.manager = manager;
this.strict = strict;
}
@Override
public T read(ConfigurationNode node) {
String id = node.getString("?");
boolean inverted = node.getBoolean("negate", false);
try {
// Check for long hand notation (?: class)
if (id != null) {
return invertCriteria(manager.newInstance(id, node, null), inverted);
}
// Check for short-hand notation (?class: value)
for (String key : node.getKeys(ConfigurationNode.ROOT)) {
if (key.startsWith("?")) {
id = key;
Object value = node.get(key);
return invertCriteria(
manager.newInstance(key.substring(1), node, new ConfigurationValue(value)), inverted);
}
}
// No class defined!
logger.warning("RuleList: Missing '?' parameter in definition " +
"(to define what kind of criteria/action it is)");
return null;
} catch (DefinitionException e) {
logger.warning("RuleList: Invalid definition " +
"identified by type '" + id + "': " + e.getMessage());
// Throw an exception in strict mode
if (strict) {
throw new LoaderBuilderException("RuleList: Invalid definition " +
"identified by type '" + id + "': " + e.getMessage());
}
return null;
}
}
}
}
@@ -0,0 +1,83 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.HashMap;
import java.util.Map;
/**
* Holds all the rules.
*/
public class RuleList {
private Map<Attachment, RuleSet> collections = new HashMap<Attachment, RuleSet>();
/**
* Build a new instance.
*/
public RuleList() {
}
/**
* Get a rule set for a given attachment. A rule set is guaranteed to be
* returned for all given attachments.
*
* @param attachment the attachment
* @return the rule set
*/
public synchronized RuleSet get(Attachment attachment) {
RuleSet collection = collections.get(attachment);
if (collection == null) {
collection = new RuleSet();
collections.put(attachment, collection);
}
return collection;
}
/**
* Register a rule with this rule list.
*
* @param entry entry
*/
public void learn(RuleEntry entry) {
Rule<?> rule = entry.getRule();
for (Attachment attachment : entry.getAttachments()) {
learn(attachment, rule);
}
}
/**
* Register a rule with this rule list.
*
* @param attachment the attachment for the rule
* @param rule the rule itself
*/
public void learn(Attachment attachment, Rule<?> rule) {
get(attachment).learn(rule);
}
/**
* Forget all rules.
*/
public void clear() {
collections.clear();
}
}
@@ -0,0 +1,65 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.List;
import java.util.logging.Logger;
import com.sk89q.rebar.config.ConfigurationNode;
/**
* RuleList-related utility methods.
*/
public class RuleListUtils {
private RuleListUtils() {
}
/**
* Warn of unknown directives in a rule list block.
*
* @param node node
* @param logger the logger to send to
* @param expected expected keys
*/
public static void warnUnknown(ConfigurationNode node, Logger logger, String ... expected) {
List<String> keys = node.getKeys(ConfigurationNode.ROOT);
for (String key : keys) {
boolean found = false;
if (key.equals("?")) continue;
if (key.equals("negate")) continue;
if (key.equals("_")) continue;
if (key.length() > 0 && key.charAt(0) == '?') continue;
for (String expect : expected) {
if (expect.equals(key)) {
found = true;
break;
}
}
if (!found) {
logger.warning("[WorldGuard] RuleList: Unexpected parameter of '" + key + "' in " + node);
}
}
}
}
@@ -0,0 +1,77 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
/**
* Manages action lists and details relevant to them.
*/
public class RuleListsManager {
private final AttachmentManager attachments = new AttachmentManager();
private final DefinitionManager<Criteria<?>> criterion = new DefinitionManager<Criteria<?>>();
private final DefinitionManager<Action<?>> actions = new DefinitionManager<Action<?>>();
private final ResolverManager subjectResolvers = new ResolverManager();
private final ExpressionParser exprParser = new ExpressionParser();
/**
* Get the attachment manager.
*
* @return the attachment manager
*/
public AttachmentManager getAttachments() {
return attachments;
}
/**
* Get the criterion manager.
*
* @return criterion manager
*/
public DefinitionManager<Criteria<?>> getCriterion() {
return criterion;
}
/**
* Get the actions manager.
*
* @return actions manager
*/
public DefinitionManager<Action<?>> getActions() {
return actions;
}
/**
* Get the subject resolvers manager.
*
* @return the subject resolvers manager
*/
public ResolverManager getResolvers() {
return subjectResolvers;
}
/**
* Get the expression parser.
*
* @return the expression parser
*/
public ExpressionParser getParser() {
return exprParser;
}
}
@@ -0,0 +1,93 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Holds a collection of rules that can be applied to a context.
*
* @see RuleList
*/
public class RuleSet {
private List<Rule<?>> rules = new LinkedList<Rule<?>>();
RuleSet() {
}
/**
* Add the given rule to this set.
*
* @param rule the rule
*/
public synchronized void learn(Rule<?> rule) {
rules.add(rule);
}
/**
* Forget all rules.
*/
public synchronized void clear() {
rules.clear();
}
/**
* Return whether this set has rules.
*
* @return true if there are rules
*/
public synchronized boolean hasRules() {
return rules.size() > 0;
}
/**
* Get the list of rules. The returned list cannot be modified.
*
* @return rule list
*/
public synchronized List<Rule<?>> getRules() {
return Collections.unmodifiableList(rules);
}
/**
* Apply this rule set onto the given context. Only one thread should call
* this method at a given time.
*
* @param context the context
* @return true if the event has been cancelled
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean process(Context context) {
if (context.isCancelled()) {
return true; // Ignore cancelled events for now
}
for (Rule rule : rules) {
if (rule.matches(context)) {
rule.apply(context);
}
}
return context.isCancelled();
}
}
@@ -0,0 +1,131 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.rulelists;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.StringLoaderBuilder;
/**
* A loader that will load the built-in rules used. It handles a slightly different
* format that also stores parameter information and other goodies.
*/
public class RuleTemplateEntryLoader extends AbstractNodeLoader<List<RuleEntry>> {
private static final StringLoaderBuilder stringLoader = new StringLoaderBuilder();
private final ConfigurationNode config;
private final RuleEntryLoader entryLoader;
/**
* Construct the loader with the given rule lists manager.
*
* @param manager the manager
* @param config the configuration node to read settings from
*/
public RuleTemplateEntryLoader(RuleListsManager manager, ConfigurationNode config) {
entryLoader = new RuleEntryLoader(manager);
this.config = config;
}
@Override
public List<RuleEntry> read(ConfigurationNode node) throws LoaderBuilderException {
List<RuleEntry> rules = new ArrayList<RuleEntry>();
List<String> settings = node.listOf("setting", stringLoader);
if (settings.size() == 0) {
throw new LoaderBuilderException("No 'setting' value in:\n" + node.toString());
}
String selectedSetting = settings.get(0);
String type = node.getString("type", "boolean");
if (settings.size() > 1) {
boolean migrate = false;
boolean found = false;
Object value = null;
for (String setting : settings) {
if (config.contains(setting)) {
value = config.get(setting);
found = true;
break;
} else {
migrate = true;
}
}
if (found && migrate) {
config.set(settings.get(0), value);
int i = 0;
for (String setting : settings) {
if (i++ != 0) {
config.remove(setting);
}
}
}
}
boolean active = false;
// See if the setting is active
if (type.equals("boolean")) {
boolean negate = node.getBoolean("negate", false);
boolean enabled = config.getBoolean(selectedSetting, negate);
if (negate) {
enabled = !enabled;
}
if (enabled) {
active = true;
}
} else if (type.equals("list")) {
Object val = config.get(selectedSetting);
if (val == null) {
config.set(selectedSetting, new ArrayList<Object>());
} else if (val instanceof List<?> && ((List<?>) val).size() > 0) {
active = true;
}
}
// Load the setting
if (active) {
List<String> paramPaths = node.getStringList("parameters.target", new ArrayList<String>());
if (paramPaths.size() > 0) {
Object val = config.get(selectedSetting);
for (String path : paramPaths) {
node.set(path, val);
}
}
for (RuleEntry rule : node.listOf("rules", entryLoader)) {
rules.add(rule);
}
}
return rules;
}
}
@@ -0,0 +1,26 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY), without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard;
/**
* A user, group, or other object that describes a set of users.
*/
public interface Classifier {
}
@@ -0,0 +1,94 @@
// $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 The player's name
*/
public abstract String getName();
/**
* Returns true if the player is inside a group.
*
* @param group The group to check
* @return Whether this player is in {@code group}
*/
public abstract boolean hasGroup(String group);
/**
* Get the player's position.
*
* @return The player's position
*/
public abstract Vector getPosition();
/**
* Kick the player.
*
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban the player.
*
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
/**
* Send the player a message;
*
* @param msg The message to send to the player
*/
public abstract void printRaw(String msg);
/**
* Get the player's list of groups.
*
* @return The groups this player is in
*/
public abstract String[] getGroups();
/**
* Returns whether a player has permission.
*
* @param perm The permission to check
* @return Whether this player has {@code perm}
*/
public abstract boolean hasPermission(String perm);
@Override
public boolean equals(Object obj) {
return obj instanceof LocalPlayer && ((LocalPlayer) obj).getName().equals(getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
}
@@ -17,24 +17,31 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Map;
package com.sk89q.worldguard.blacklist;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.Map;
import java.util.logging.Level;
import java.io.*;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class Blacklist {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
public abstract class Blacklist {
/**
* List of entries by block ID.
*/
@@ -44,16 +51,29 @@ public class Blacklist {
* Logger.
*/
private BlacklistLogger blacklistLogger = new BlacklistLogger();
/**
* Blacklist contains on-acquire events.
* Last event.
*/
private boolean hasOnAcquire;
private BlacklistEvent lastEvent;
/**
* Used to prevent flooding.
*/
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
private boolean useAsWhitelist;
private final Logger logger;
public Blacklist(Boolean useAsWhitelist, Logger logger) {
this.useAsWhitelist = useAsWhitelist;
this.logger = logger;
}
/**
* Returns whether the list is empty.
*
* @return
*
* @return whether the blacklist is empty
*/
public boolean isEmpty() {
return blacklist.isEmpty();
@@ -61,226 +81,57 @@ public class Blacklist {
/**
* Get the entries for an item or list.
*
* @param id The item id to get blacklist information for
* @return The blacklist entries for {@code id}
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
}
/**
* Get the number of individual items that have blacklist entries.
*
* @return The number of items in the blacklist
*/
public int getItemCount() {
return blacklist.size();
}
/**
* Returns whether the blacklist is used as a whitelist.
*
* @return whether the blacklist is be used as a whitelist
*/
public boolean isWhitelist() {
return useAsWhitelist;
}
/**
* Get the logger.
*
* @return
*
* @return The logger used in this blacklist
*/
public BlacklistLogger getLogger() {
return blacklistLogger;
}
/**
* Called on block destruction. Returns true to let the action pass
* through.
* Method to handle the event.
*
* @param block
* @param player
* @return
* @param event The event to check
* @param forceRepeat Whether to force quickly repeating notifications
* @param silent Whether to force-deny notifications
* @return Whether the event is allowed
*/
public boolean onDestroy(final Block block, final Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
List<BlacklistEntry> entries = getEntries(event.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDestroy(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on block break. Returns true to let the action pass
* through.
*
* @param block
* @param player
* @return
*/
public boolean onBreak(final Block block, final Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onBreak(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on left click. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDestroyWith(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDestroyWith(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on place. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onPlace(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onPlace(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param block
* @param player
* @return
*/
public boolean onRightClick(Block block, Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onRightClick(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on item use. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onUse(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onUse(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on right click upon. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentUse(Block block, Player player) {
List<BlacklistEntry> entries = getEntries(block.getType());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onSilentUse(block, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on drop. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onDrop(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onDrop(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onAcquire(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onAcquire(item, player)) {
ret = false;
}
}
return ret;
}
/**
* Called on acquire. Returns true to let the action pass through.
*
* @param item
* @param player
* @return
*/
public boolean onSilentAcquire(int item, Player player) {
List<BlacklistEntry> entries = getEntries(item);
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.onSilentAcquire(item, player)) {
if (!entry.check(useAsWhitelist, event, forceRepeat, silent)) {
ret = false;
}
}
@@ -290,9 +141,8 @@ public class Blacklist {
/**
* Load the blacklist.
*
* @param file
* @return
* @throws IOException
* @param file The file to load from
* @throws IOException if an error occurred reading from the file
*/
public void load(File file) throws IOException {
FileReader input = null;
@@ -303,8 +153,6 @@ public class Blacklist {
input = new FileReader(file);
BufferedReader buff = new BufferedReader(input);
hasOnAcquire = false;
String line;
List<BlacklistEntry> currentEntries = null;
while ((line = buff.readLine()) != null) {
@@ -322,14 +170,14 @@ public class Blacklist {
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
int id;
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = etc.getDataSource().getItem(item.trim());
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "WorldGuard: Unknown block name: "
logger.log(Level.WARNING, "Unknown block name: "
+ item);
break;
}
@@ -359,23 +207,21 @@ public class Blacklist {
for (BlacklistEntry entry : currentEntries) {
if (parts[0].equalsIgnoreCase("ignore-groups")) {
entry.setIgnoreGroups(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-destroy")) {
entry.setDestroyActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("ignore-perms")) {
entry.setIgnorePermissions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-break")) {
entry.setBreakActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-left")
|| parts[0].equalsIgnoreCase("on-destroy-with")) {
} else if (parts[0].equalsIgnoreCase("on-destroy-with")) {
entry.setDestroyWithActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-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-right-click")) {
entry.setRightClickActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-drop")) {
entry.setDropActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-acquire")) {
hasOnAcquire = true;
entry.setAcquireActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("message")) {
entry.setMessage(parts[1].trim());
@@ -402,17 +248,87 @@ public class Blacklist {
if (input != null) {
input.close();
}
} catch (IOException e2) {
} catch (IOException ignore) {
}
}
}
/**
* Blacklist contains on-acquire events.
*
* @return
* Get the last event.
*
* @return The last event
*/
public boolean hasOnAcquire() {
return hasOnAcquire;
public BlacklistEvent getLastEvent() {
return lastEvent;
}
/**
* Notify administrators.
*
* @param event The event to notify about
* @param comment The comment to notify with
*/
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
broadcastNotification(ChatColor.GRAY + "WG: "
+ 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 The message to broadcast
*/
public abstract void broadcastNotification(String msg);
/**
* Forget a player.
*
* @param player The player to forget
*/
public void forgetPlayer(LocalPlayer player) {
lastAffected.remove(player.getName());
}
/**
* Forget all players.
*/
public void forgetAllPlayers() {
lastAffected.clear();
}
/**
* Get an item's ID from its name.
*
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
if (type != null) {
return type.getID();
} else {
return -1;
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id The id to look up
* @return The item's friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -0,0 +1,424 @@
// $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.Collections;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class BlacklistEntry {
/**
* Parent blacklist entry.
*/
private Blacklist blacklist;
/**
* List of groups to not affect.
*/
private Set<String> ignoreGroups;
/**
* List of permissions to not affect.
*/
private Set<String> ignorePermissions;
private String[] breakActions;
private String[] destroyWithActions;
private String[] placeActions;
private String[] interactActions;
private String[] useActions;
private String[] dropActions;
private String[] acquireActions;
private String message;
private String comment;
/**
* Construct the object.
*
* @param blacklist The blacklist that contains this entry
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
}
/**
* @return the ignoreGroups
*/
public String[] getIgnoreGroups() {
return ignoreGroups.toArray(new String[ignoreGroups.size()]);
}
/**
* @return the ignoreGroups
*/
public String[] getIgnorePermissions() {
return ignorePermissions.toArray(new String[ignorePermissions.size()]);
}
/**
* @param ignoreGroups the ignoreGroups to set
*/
public void setIgnoreGroups(String[] ignoreGroups) {
Set<String> ignoreGroupsSet = new HashSet<String>();
for (String group : ignoreGroups) {
ignoreGroupsSet.add(group.toLowerCase());
}
this.ignoreGroups = ignoreGroupsSet;
}
/**
* @param ignorePermissions the ignorePermissions to set
*/
public void setIgnorePermissions(String[] ignorePermissions) {
Set<String> ignorePermissionsSet = new HashSet<String>();
Collections.addAll(ignorePermissionsSet, ignorePermissions);
this.ignorePermissions = ignorePermissionsSet;
}
/**
* @return The actions that occur when breaking
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions The actions to occur when breaking
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return The actions that occur when destroying with a specific item
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param actions The actions to occur when destroying with an item
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return The actions that will occur when placing
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions The actions to occur when placing
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return The actions that will occur when interacting
*/
public String[] getInteractActions() {
return interactActions;
}
/**
* @param actions The actions to occur when interacting
*/
public void setInteractActions(String[] actions) {
this.interactActions = actions;
}
/**
* @return The actions that will occur when using
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions The actions to occur when using
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return The actions that will occur when dropping
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions The actions to occur when dropping
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return The actions that will occur when acquiring
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions The actions to occur when acquiring
*/
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 The player to check
* @return whether this player should be ignored for blacklist blocking
*/
public boolean shouldIgnore(LocalPlayer player) {
if (ignoreGroups != null) {
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
return true;
}
}
}
if (ignorePermissions != null) {
for (String perm : ignorePermissions) {
if (player.hasPermission(perm)) {
return true;
}
}
}
return false;
}
/**
* Get the associated actions with an event.
*
* @param event The event to check
* @return The actions for the given event
*/
private String[] getActions(BlacklistEvent event) {
if (event instanceof BlockBreakBlacklistEvent) {
return breakActions;
} else if (event instanceof BlockPlaceBlacklistEvent) {
return placeActions;
} else if (event instanceof BlockInteractBlacklistEvent) {
return interactActions;
} else if (event instanceof DestroyWithBlacklistEvent) {
return destroyWithActions;
} else if (event instanceof ItemAcquireBlacklistEvent) {
return acquireActions;
} else if (event instanceof ItemDropBlacklistEvent) {
return dropActions;
} else if (event instanceof ItemUseBlacklistEvent) {
return useActions;
} else {
return null;
}
}
/**
* Method to handle the event.
*
* @param useAsWhitelist Whether this entry is buing used in a whitelist
* @param event The event to check
* @param forceRepeat Whether to force repeating notifications even within the delay limit
* @param silent Whether to prevent notifications from happening
* @return Whether the action was allowed
*/
public boolean check(boolean useAsWhitelist, BlacklistEvent event, boolean forceRepeat, boolean silent) {
LocalPlayer player = event.getPlayer();
if (shouldIgnore(player)) {
return true;
}
String name = player.getName();
long now = System.currentTimeMillis();
boolean repeating = false;
// Check to see whether this event is being repeated
BlacklistTrackedEvent tracked = blacklist.lastAffected.get(name);
if (tracked != null) {
if (tracked.matches(event, now)) {
repeating = true;
}
} else {
blacklist.lastAffected.put(name, new BlacklistTrackedEvent(event, now));
}
String actions[] = getActions(event);
boolean ret = !useAsWhitelist;
// Nothing to do
if (actions == null) {
return ret;
}
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Allow
} else if (action.equalsIgnoreCase("allow")) {
if (silent) {
return true;
}
ret = true;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (silent) {
continue;
}
if (this.message != null) {
player.kick(String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.kick("You can't " + event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
// Ban
} else if (action.equalsIgnoreCase("ban")) {
if (silent) {
continue;
}
if (this.message != null) {
player.ban("Banned: " + String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.ban("Banned: You can't "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
} else if (!silent && (!repeating || forceRepeat)) {
// Notify
if (action.equalsIgnoreCase("notify")) {
blacklist.notify(event, comment);
// Log
} else if (action.equalsIgnoreCase("log")) {
blacklist.getLogger().logEvent(event, comment);
// Tell
} else if (action.equalsIgnoreCase("tell")) {
if (this.message != null) {
player.printRaw(ChatColor.YELLOW +
String.format(message, getFriendlyItemName(event.getType()))
+ ".");
} else {
player.printRaw(ChatColor.YELLOW + "You're not allowed to "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()) + ".");
}
}
}
}
return ret;
}
/**
* Get an item's friendly name with its ID.
*
* @param id The id to get a name for
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -0,0 +1,83 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist;
import java.util.HashSet;
import java.util.Set;
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 The handler to add
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Remove a handler.
*
* @param handler The handler to remove
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
}
/**
* Add a handler.
*/
public void clearHandlers() {
handlers.clear();
}
/**
* Log an event.
*
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
handler.logEvent(event, comment);
}
}
/**
* Close the connection.
*/
public void close() {
for (BlacklistLoggerHandler handler : handlers) {
handler.close();
}
}
}
@@ -17,50 +17,32 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class BlacklistTrackedEvent {
private int id;
private BlacklistEvent event;
private long time;
/**
* Construct the object.
*
* @param id
* @param time
*
* @param event The event tracked
* @param time The time at which the event occurred
*/
public BlacklistTrackedEvent(int id, long time) {
this.id = id;
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
this.time = time;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the time
*/
public long getTime() {
return time;
}
/**
* @param time the time to set
*/
public void setTime(long time) {
this.time = time;
public boolean matches(BlacklistEvent other, long now) {
return other.getType() == event.getType()
&& time > now - 3000
&& other.getClass() == event.getClass();
}
}
@@ -0,0 +1,85 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* Represents a blacklist event.
*
* @author sk89q
*/
public abstract class BlacklistEvent {
private Vector pos;
private int type;
/**
* Holds the player that triggered the event.
*/
private LocalPlayer player;
/**
* Construct the object.
*
* @param player The player associated with this event
* @param pos The position the event occurred at
* @param type The type of item used
*/
public BlacklistEvent(LocalPlayer player, Vector pos, int type) {
this.player = player;
this.pos = pos;
this.type = type;
}
/**
* Get the player.
*
* @return The player associated with this event
*/
public LocalPlayer getPlayer() {
return player;
}
/**
* Get the position.
*
* @return The position of this event
*/
public Vector getPosition() {
return pos;
}
/**
* Get the item type.
*
* @return The type associated with this event
*/
public int getType() {
return type;
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return The event description
*/
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,34 @@
// $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);
}
@Override
public String getDescription() {
return "break";
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "interact with";
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "place";
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "destroy with";
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "acquire";
}
}
@@ -0,0 +1,29 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public abstract class ItemBlacklistEvent extends BlacklistEvent {
public ItemBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "drop";
}
}
@@ -0,0 +1,34 @@
// $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);
}
@Override
public String getDescription() {
return "use";
}
}
@@ -1,43 +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/>.
*/
/**
* Inventory related functions.
*
* @author sk89q
*/
public class ItemArrayUtil {
/**
* Set the contents of an ItemArray.
*
* @param itemArray
* @param contents
*/
public static void setContents(ItemArray<?> itemArray, Item[] contents) {
int size = itemArray.getContentsSize();
for (int i = 0; i < size; i++) {
if (contents[i] == null) {
itemArray.removeItem(i);
} else {
itemArray.setSlot(contents[i], i);
}
}
}
}
// $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,128 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.loggers;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
private String worldName;
private final Logger logger;
public ConsoleLoggerHandler(String worldName, Logger logger) {
this.worldName = worldName;
this.logger = logger;
}
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id;
}
}
/**
* Close the connection.
*/
public void close() {
}
}
@@ -0,0 +1,205 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.blacklist.loggers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* DSN.
*/
private final String dsn;
/**
* Username.
*/
private final String user;
/**
* Password.
*/
private final String pass;
/**
* Table.
*/
private final String table;
/**
* World name.
*/
private final String worldName;
/**
* Database connection.
*/
private Connection conn;
private final Logger logger;
/**
* Construct the object.
*
* @param dsn The DSN for the connection
* @param user The username to connect with
* @param pass The password to connect with
* @param table The table to log to
* @param worldName The name of the world to log
* @param logger The logger to log errors to
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
this.logger = logger;
}
/**
* Gets the database connection.
*
* @return The database connection
* @throws SQLException when the connection cannot be created
*/
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 The event to log
* @param player The player associated with the event
* @param pos The location of the event
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(String event, LocalPlayer player, Vector pos, int item,
String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, world, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
stmt.setString(2, worldName);
stmt.setString(3, player.getName());
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setInt(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
+ e.getMessage());
}
}
/**
* Log an event.
*
* @param event The event to log
*/
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 BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent("INTERACT", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent("DESTROY_WITH", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent("ACQUIRE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent("DROP", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent("USE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Unknown
} else {
logEvent("UNKNOWN", event.getPlayer(), event.getPlayer().getPosition(),
-1, comment);
}
}
/**
* Close the connection.
*/
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ignore) {
}
}
}
@@ -17,27 +17,34 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
import java.io.*;
import java.util.regex.*;
import java.util.Map;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TreeMap;
import java.util.Iterator;
package com.sk89q.worldguard.blacklist.loggers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard");
/**
* Regex for patterns in the path.
*/
@@ -56,45 +63,59 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* Path pattern.
*/
private String pathPattern;
/**
* World name.
*/
private String worldName;
/**
* Cache of writers.
*/
private TreeMap<String,FileLoggerWriter> writers =
new TreeMap<String,FileLoggerWriter>();
private final Logger logger;
/**
* Construct the object.
*
* @param pathPattern
* @param pathPattern The pattern for the logflie path
* @param worldName The name of the world
* @param logger The logger used to log errors
*/
public FileLoggerHandler(String pathPattern) {
public FileLoggerHandler(String pathPattern, String worldName, Logger logger) {
this.pathPattern = pathPattern;
this.worldName = worldName;
this.logger = logger;
}
/**
* Construct the object.
*
* @param pathPattern
* @param cacheSize
* @param pathPattern The pattern for logfile paths
* @param cacheSize The size of the file cache
* @param worldName The name of the associated world
* @param logger The logger to log errors with
*/
public FileLoggerHandler(String pathPattern, int cacheSize) {
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
this.pathPattern = pathPattern;
this.cacheSize = cacheSize;
this.worldName = worldName;
this.logger = logger;
}
/**
* Build the path.
*
* @return
*
* @param playerName The name of the playername
* @return The path for the logfile
*/
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
Pattern p = Pattern.compile("%.");
Matcher m = p.matcher(pathPattern);
Matcher m = pattern.matcher(pathPattern);
StringBuffer buffer = new StringBuffer();
// Pattern replacements
@@ -110,6 +131,12 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
rep = rep.substring(0, 32);
}
}else if (group.matches("%w")) {
rep = worldName.toLowerCase().replaceAll("[^A-Za-z0-9_]", "_");
if (rep.length() > 32) { // Actual max length is 16
rep = rep.substring(0, 32);
}
// Date and time
} else if (group.matches("%Y")) {
rep = String.valueOf(calendar.get(Calendar.YEAR));
@@ -128,28 +155,29 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
} else if (group.matches("%s")) {
rep = String.format("%02d", calendar.get(Calendar.SECOND));
}
m.appendReplacement(buffer, rep);
}
m.appendTail(buffer);
return buffer.toString();
}
/**
* Log a message.
*
* @param player
* @param message
*
* @param player The player to log
* @param message The message to log
* @param comment The comment associated with the logged event
*/
private void log(Player player, String message, String comment) {
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
try {
String date = dateFormat.format(new Date());
String line = "[" + date + "] " + player.getName() + ": " + message
+ (comment != null ? " (" + comment + ")" : "") + "\r\n";
FileLoggerWriter writer = writers.get(path);
// Writer already exists!
@@ -171,7 +199,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
FileWriter stream = new FileWriter(path, true);
BufferedWriter out = new BufferedWriter(stream);
out.write(line);
@@ -189,7 +217,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
Map.Entry<String,FileLoggerWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
it.remove();
@@ -207,108 +235,42 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
}
/**
* Gets the coordinates of a block in text form for the log.
*
* @param block
* @return
* Gets the coordinates in text form for the log.
*
* @param pos The position to get coordinates for
* @return The position's coordinates in human-readable form
*/
private String getCoordinates(Block block) {
return "@" + block.getX() + "," + block.getY() + "," + block.getZ();
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 a block destroy attempt.
* Log an event.
*
* @param player
* @param block
* @param event The event to log
*/
public void logDestroyAttempt(Player player, Block block, String comment) {
log(player, "Tried to destroy " + getFriendlyItemName(block.getType())
+ " " + getCoordinates(block),
comment);
}
/**
* Log a block break attempt.
*
* @param player
* @param block
*/
public void logBreakAttempt(Player player, Block block, String comment) {
log(player, "Tried to break " + getFriendlyItemName(block.getType())
+ " " + getCoordinates(block),
comment);
}
/**
* Log a right click on attempt.
*
* @param player
* @param block
*/
public void logRightClickAttempt(Player player, Block block, String comment) {
log(player, "Tried to right click " + getFriendlyItemName(block.getType())
+ " " + getCoordinates(block),
comment);
}
/**
* Log an attempt to destroy with an item.
*
* @param player
* @param item
*/
public void logDestroyWithAttempt(Player player, int item, String comment) {
log(player, "Tried to destroy with " + getFriendlyItemName(item), comment);
}
/**
* Log a block creation attempt.
*
* @param player
* @param item
*/
public void logPlaceAttempt(Player player, int item, String comment) {
log(player, "Tried to place " + getFriendlyItemName(item), comment);
}
/**
* Log a block use attempt.
*
* @param player
* @param item
*/
public void logUseAttempt(Player player, int item, String comment) {
log(player, "Tried to use " + getFriendlyItemName(item), comment);
}
/**
* Log a drop attempt.
*
* @param player
* @param item
*/
public void logDropAttempt(Player player, int item, String comment) {
log(player, "Tried to drop " + getFriendlyItemName(item), comment);
}
/**
* Log an acquire attempt.
*
* @param player
* @param item
*/
public void logAcquireAttempt(Player player, int item, String comment) {
log(player, "Tried to acquire " + getFriendlyItemName(item), comment);
public void logEvent(BlacklistEvent event, String comment) {
logEvent(event, event.getDescription(), event.getType(), event.getPosition(), comment);
}
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The id to get a friendly name for
* @return The friendly name
*/
private static String getFriendlyItemName(int id) {
return etc.getDataSource().getItem(id) + " (#" + id + ")";
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
/**
@@ -318,7 +280,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
for (Map.Entry<String,FileLoggerWriter> entry : writers.entrySet()) {
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
@@ -17,7 +17,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.*;
package com.sk89q.worldguard.blacklist.loggers;
import java.io.BufferedWriter;
/**
*
@@ -39,8 +41,9 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Construct the object.
*
* @param writer
*
* @param path The path to write to
* @param writer The writer for the file
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
this.path = path;
@@ -50,15 +53,15 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* File path.
*
* @return
*
* @return The path the logger is logging to
*/
public String getPath() {
return path;
}
/**
* @return the writer
* @return the writer being logged to
*/
public BufferedWriter getWriter() {
return writer;
@@ -70,22 +73,14 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
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;
@@ -0,0 +1,36 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldguard.blacklist.Blacklist;
public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist, plugin.getLogger());
this.plugin = plugin;
}
@Override
public void broadcastNotification(String msg) {
plugin.broadcastNotification(msg);
}
}
@@ -0,0 +1,238 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.inventory.ItemStack;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.region.ApplicableRegionSet;
/**
* An implementation of a {@link Context} for Bukkit. This object is thread-safe, but
* the underlying objects returned by this class may not be.
*
* @see Context
*/
public class BukkitContext extends Context {
private final RegionQueryCache regionCache;
private final Event event;
private RegionQuery regionQuery;
private String message;
private Entity sourceEntity;
private Entity targetEntity;
private ItemStack item;
private BlockState sourceBlock;
private BlockState targetBlock;
private BlockState replacedTargetBlock;
private ApplicableRegionSet lastApplRegionSet;
/**
* Construct a context linked to the given event.
*
* @param plugin the WorldGuard plugin
* @param event the event
*/
BukkitContext(WorldGuardPlugin plugin, Event event) {
this.regionCache = plugin.getRegionCache();
this.event = event;
}
/**
* Get the message attribute of this context.
*
* @return message or null
*/
public String getMessage() {
return message;
}
/**
* Set the message attribute of this context.
*
* @param message or null
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Get the source entity for this context. The source entity is the 'cause' of
* this context, if it is available.
*
* @return entity or null
*/
public Entity getSourceEntity() {
return sourceEntity;
}
/**
* Set the source entity for this context. The source entity is the 'cause' of
* this context, if it is available.
*
* @param sourceEntity entity or null
*/
public void setSourceEntity(Entity sourceEntity) {
this.sourceEntity = sourceEntity;
}
/**
* Get the target entity for this context. The target entity is the 'subject'
* of this context, if it is available.
*
* @return entity or null
*/
public Entity getTargetEntity() {
return targetEntity;
}
/**
* Set the target entity for this context. The target entity is the 'subject'
* of this context, if it is available.
*
* @param targetEntity entity or null
*/
public void setTargetEntity(Entity targetEntity) {
this.targetEntity = targetEntity;
}
/**
* Get the primary item related to this context. Only events that are oriented
* around an item have this property set.
*
* @return item or null
*/
public ItemStack getItem() {
return item;
}
/**
* Set the primary item related to this context. Only events that are oriented
* around an item have this property set.
*
* @param item item or null
*/
public void setItem(ItemStack item) {
this.item = item;
}
/**
* Get the source block for this context. The source block is the 'cause'
* of this context, if it is available.
*
* @return block or null
*/
public BlockState getSourceBlock() {
return sourceBlock;
}
/**
* Set the source block for this context. The source block is the 'cause'
* of this context, if it is available.
*
* @param block block or null
*/
public void setSourceBlock(BlockState block) {
this.sourceBlock = block;
}
/**
* Get a target block for this context. The target block is the 'subject' of
* this context, if it is available.
*
* @return block or null
*/
public BlockState getTargetBlock() {
return targetBlock;
}
/**
* Set a target block for this context. The target block is the 'subject' of
* this context, if it is available.
*
* @param targetBlock block or null
*/
public void setTargetBlock(BlockState targetBlock) {
this.targetBlock = targetBlock;
}
/**
* Get the placed block for this context. The placed block is the 'new' block
* that will replace the existing block in this context, if it is available.
*
* @return block or null
*/
public BlockState getPlacedBlock() {
return replacedTargetBlock;
}
/**
* Set the placed block for this context. The placed block is the 'new' block
* that will replace the existing block in this context, if it is available.
*
* @param replacedTargetBlock block or null
*/
public void setPlacedBlock(BlockState replacedTargetBlock) {
this.replacedTargetBlock = replacedTargetBlock;
}
/**
* Get the last {@link ApplicableRegionSet}. This can be set by a rule and used
* within one, but it cannot be guaranteed to exist across rules.
*
* @return an {@link ApplicableRegionSet} or null
*/
public ApplicableRegionSet getApplicableRegionSet() {
return lastApplRegionSet;
}
/**
* Set the last {@link ApplicableRegionSet}.
*
* @param set an {@link ApplicableRegionSet} or null
*/
public void setApplicableRegionSet(ApplicableRegionSet set) {
this.lastApplRegionSet = set;
}
/**
* Get the underlying event object.
*
* @return event object
*/
public Event getEvent() {
return event;
}
/**
* Get the region query object.
*
* @return region query object
*/
public synchronized RegionQuery getRegionQuery() {
if (regionQuery == null) {
regionQuery = regionCache.against(event);
}
return regionQuery;
}
}
@@ -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.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.setBanned(true);
player.kickPlayer(msg);
}
@Override
public String[] getGroups() {
return plugin.getGroups(player);
}
@Override
public void printRaw(String msg) {
player.sendMessage(msg);
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
}
@@ -0,0 +1,275 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class BukkitUtil {
private BukkitUtil() {
}
/**
* Converts the location of a Bukkit block to a WorldEdit vector.
*
* @param block The block to convert
* @return The block's location as a BlockVector
*/
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
/**
* Converts a Bukkit location to a WorldEdit vector.
*
* @param loc A Bukkit Location
* @return A Vector with the location's x, y, and z values
*/
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
/**
* Converts a Bukkit vector to a WorldEdit vector.
*
* @param vector The Bukkit vector
* @return A WorldEdit vector with the same values as the Bukkit vector.
*/
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
}
/**
* Converts a WorldEdit vector to a Bukkit location.
*
* @param world The World to create the new Location with
* @param vec The vector to use for coordinates
* @return The Vector as a location with a World of world
*/
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Matches one player based on name.
*
* @param server The server to check
* @param name The name to attempt to match
* @deprecated see {@link WorldGuardPlugin#matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @return The matched player if any, otherwise null
*/
@Deprecated
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
return null;
}
return players.get(0);
}
/**
* Drops a sign item and removes a sign.
*
* @param block The block
* @deprecated see {@link org.bukkit.block.Block#breakNaturally()}
*/
@Deprecated
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(ItemID.SIGN, 1));
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
* @param world
* @param ox
* @param oy
* @param oz
*/
public static void setBlockToWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 0) {
block.setTypeId(8);
}
}
/**
* Checks if the given block is water
*
* @param world the world
* @param ox x
* @param oy y
* @param oz z
* @return true if it's water
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
return id == 8 || id == 9;
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
* a series of two free blocks. The player will be teleported to
* that free position.
*
* @param player
*/
public static void findFreePosition(Player player) {
Location loc = player.getLocation();
int x = loc.getBlockX();
int y = Math.max(0, loc.getBlockY());
int origY = y;
int z = loc.getBlockZ();
World world = player.getWorld();
byte free = 0;
while (y <= world.getMaxHeight() + 1) {
if (BlockType.canPassThrough(world.getBlockTypeIdAt(x, y, z))) {
free++;
} else {
free = 0;
}
if (free == 2) {
if (y - 1 != origY || y == 1) {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
if (y <= 2 && world.getBlockAt(x,0,z).getTypeId() == BlockID.AIR) {
world.getBlockAt(x,0,z).setTypeId(20);
loc.setY(2);
}
player.setFallDistance(0F);
player.teleport(loc);
}
return;
}
y++;
}
}
/**
* Replace color macros in a string. The macros are in the form of `[char]
* where char represents the color. R is for red, Y is for yellow,
* G is for green, C is for cyan, B is for blue, and P is for purple.
* The uppercase versions of those are the darker shades, while the
* lowercase versions are the lighter shades. For white, it's 'w', and
* 0-2 are black, dark grey, and grey, respectively.
*
* @param str
* @return color-coded string
*/
public static String replaceColorMacros(String str) {
str = str.replace("&r", ChatColor.RED.toString());
str = str.replace("&R", ChatColor.DARK_RED.toString());
str = str.replace("&y", ChatColor.YELLOW.toString());
str = str.replace("&Y", ChatColor.GOLD.toString());
str = str.replace("&g", ChatColor.GREEN.toString());
str = str.replace("&G", ChatColor.DARK_GREEN.toString());
str = str.replace("&c", ChatColor.AQUA.toString());
str = str.replace("&C", ChatColor.DARK_AQUA.toString());
str = str.replace("&b", ChatColor.BLUE.toString());
str = str.replace("&B", ChatColor.DARK_BLUE.toString());
str = str.replace("&p", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("&P", ChatColor.DARK_PURPLE.toString());
str = str.replace("&0", ChatColor.BLACK.toString());
str = str.replace("&1", ChatColor.DARK_GRAY.toString());
str = str.replace("&2", ChatColor.GRAY.toString());
str = str.replace("&w", ChatColor.WHITE.toString());
return str;
}
/**
* Returns whether our running CraftBukkit already supports
* the HangingEvent instead of the PaintingEvent
*
* @return true if the hanging event is supported
*/
public static boolean hasHangingEvent() {
Class<?> tmp = null;
try {
tmp = Class.forName("org.bukkit.event.hanging.HangingEvent");
} catch (ClassNotFoundException ignored) { }
return (tmp != null);
}
/**
* Search an enum for a value, and return the first one found. Return null if the
* enum entry is not found.
*
* @param enumType enum class
* @param values values to test
* @return a value in the enum or null
*/
public static <T extends Enum<T>> T tryEnum(Class<T> enumType, String ... values) {
for (String val : values) {
try {
return Enum.valueOf(enumType, val);
} catch (IllegalArgumentException e) {
}
}
return null;
}
static void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
}
}
static void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
}
@@ -0,0 +1,413 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.PairedKeyValueLoaderBuilder;
import com.sk89q.rebar.config.YamlConfigurationFile;
import com.sk89q.rebar.config.YamlStyle;
import com.sk89q.rebar.config.types.LowercaseStringLoaderBuilder;
import com.sk89q.rebar.config.types.StringLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.RuleEntryLoader;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*/
public class ConfigurationManager {
private static Logger logger = LoggerUtils.getLogger(RuleEntryLoader.class, "[WorldGuard] ");
private static final String DEFAULT_RULELIST_PATH = "rulelist.yml";
private static final String DEFAULT_BLACKLIST_PATH = "worlds/%world%/blacklist.txt";
private static final String DEFAULT_WORLD_CONFIG_PATH = "worlds/%world%/config.yml";
static final YamlStyle YAML_STYLE = new YamlStyle(FlowStyle.BLOCK);
private WorldGuardPlugin plugin;
private ConcurrentMap<String, WorldConfiguration> worlds;
private YamlConfigurationFile config;
private Map<String, String> ruleLists = new HashMap<String, String>();
private Map<String, String> blacklists = new HashMap<String, String>();
private Map<String, String> worldConfigs = new HashMap<String, String>();
@Deprecated
private Set<String> hasGodMode = new HashSet<String>();
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
/* Configuration data start */
public boolean useRegionsScheduler;
public boolean useRegionsCreatureSpawnEvent;
public boolean usePlayerMove;
public Map<String, String> hostKeys = new HashMap<String, String>();
public boolean useSqlDatabase = false;
public String sqlDsn;
public String sqlUsername;
public String sqlPassword;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin the plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.worlds = new ConcurrentHashMap<String, WorldConfiguration>();
}
/**
* Load the configuration.
*/
public void load() {
loadConfig();
// Regions settings
useRegionsScheduler = config.getBoolean("regions.use-scheduler", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
// Regions SQL settings
useSqlDatabase = config.getBoolean("regions.sql.use", false);
sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
sqlUsername = config.getString("regions.sql.username", "worldguard");
sqlPassword = config.getString("regions.sql.password", "worldguard");
// Other settings
usePlayerMove = config.getBoolean("use-player-move-event", true);
// Load host keys
hostKeys = config.mapOf("host-keys",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
// Load rule list filenames
if (config.contains("rulelists")) {
ruleLists = config.mapOf("rulelists",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("rulelists").set("__default__", DEFAULT_RULELIST_PATH);
ruleLists = new HashMap<String, String>();
ruleLists.put("__default__", DEFAULT_RULELIST_PATH);
}
// Load blacklist filenames
if (config.contains("blacklists")) {
blacklists = config.mapOf("blacklists",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("blacklists").set("__default__", DEFAULT_BLACKLIST_PATH);
blacklists = new HashMap<String, String>();
blacklists.put("__default__", DEFAULT_BLACKLIST_PATH);
}
// Load world config filenames
if (config.contains("world-configs")) {
worldConfigs = config.mapOf("world-configs",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("world-configs").set("__default__", DEFAULT_WORLD_CONFIG_PATH);
worldConfigs = new HashMap<String, String>();
worldConfigs.put("__default__", DEFAULT_WORLD_CONFIG_PATH);
}
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
saveConfig();
}
/**
* Unload the configuration.
*/
public void unload() {
worlds.clear();
}
/**
* Load the configuration from file.
*/
private void loadConfig() {
config = new YamlConfigurationFile(new File(plugin.getDataFolder(), "config.yml"), YAML_STYLE);
try {
config.load();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading config.yml for global config", e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Error reading config.yml for global config", e);
}
}
/**
* Save the configuration to file.
*/
private void saveConfig() {
config.setHeader(
"# GLOBAL CONFIGURATION FILE\r\n" +
"#\r\n" +
"# Everything in here applies to all worlds. For world-specific settings, edit \r\n" +
"# the files in plugins/WorldGuard/worlds/WORLD_NAME_HERE/config.yml\r\n" +
"#\r\n" +
"# The official format of this file is called YAML. If you've never had to\r\n" +
"# edit one before, you should REALLY read http://wiki.sk89q.com/wiki/Editing_YAML\r\n");
try {
config.save();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to save configuration", e);
}
}
/**
* Get the configuration for a world.
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
public WorldConfiguration get(World world) {
String worldName = world.getName();
WorldConfiguration config = worlds.get(worldName);
WorldConfiguration newConfig = null;
while (config == null) {
if (newConfig == null) {
newConfig = new WorldConfiguration(plugin, worldName, this, this.config);
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
}
/**
* Get the RuleList file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getRuleListFile(String worldName) {
String path = ruleLists.get(worldName.toLowerCase());
if (path == null) {
path = ruleLists.get("__default__");
}
if (path == null) {
path = DEFAULT_RULELIST_PATH;
}
path = path.replace("%world%", worldName);
File file = new File(plugin.getDataFolder(), path);
if (!file.exists()) {
plugin.createDefaultConfiguration(file, "rulelist.yml");
}
return file;
}
/**
* Get the blacklist file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getBlacklistFile(String worldName) {
String path = blacklists.get(worldName.toLowerCase());
File file;
if (path == null) {
path = blacklists.get("__default__");
}
if (path == null) {
path = DEFAULT_BLACKLIST_PATH;
}
path = path.replace("%world%", worldName);
file = new File(plugin.getDataFolder(), path);
if (!file.exists()) {
plugin.createDefaultConfiguration(file, "blacklist.txt");
}
return file;
}
/**
* Get the world configuration file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getWorldConfigFile(String worldName) {
String path = worldConfigs.get(worldName.toLowerCase());
File file;
if (path == null) {
path = worldConfigs.get("__default__");
}
if (path == null) {
path = DEFAULT_WORLD_CONFIG_PATH;
}
path = path.replace("%world%", worldName);
file = new File(plugin.getDataFolder(), path);
return file;
}
/**
* Forget a player.
*
* @param player The player to forget about
*/
void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
// The blacklist needs to forget players
Blacklist bl = entry.getValue().getBlacklist();
if (bl != null) {
bl.forgetPlayer(player);
}
}
hasGodMode.remove(player.getName());
hasAmphibious.remove(player.getName());
}
/**
* Enable god mode for a player.
*
* @param player The player to enable god mode for.
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
/**
* Disable god mode for a player.
*
* @param player The player to disable godmode for
*/
@Deprecated
public void disableGodMode(Player player) {
hasGodMode.remove(player.getName());
}
/**
* Check to see if god mode is enabled for a player.
*
* @param player The player to check
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(Player player) {
if (hasCommandBookGodMode) {
GodComponent god = CommandBook.inst().getComponentManager().getComponent(GodComponent.class);
if (god != null) {
return god.hasGodMode(player);
}
}
return hasGodMode.contains(player.getName());
}
/**
* Enable amphibious mode for a player.
*
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(Player player) {
hasAmphibious.add(player.getName());
}
/**
* Disable amphibious mode for a player.
*
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(Player player) {
hasAmphibious.remove(player.getName());
}
/**
* Check to see if amphibious mode is enabled for a player.
*
* @param player The player to check
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
}
/**
* Check and store whether CommandBook is installed.
*/
void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
hasCommandBookGodMode = true;
return;
}
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
/**
* Return whether CommandBook is available for God mode usage.
*
* @return true if it available
*/
boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -0,0 +1,82 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
/**
* This event is fired when PVP is disallowed between players due to a "pvp deny" flag.
* Cancelling this event allows the PVP in spite of this.
*
* @author Score_Under
*/
public class DisallowedPVPEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private final Player attacker;
private final Player defender;
private final EntityDamageByEntityEvent event;
public DisallowedPVPEvent(final Player attacker, final Player defender, EntityDamageByEntityEvent event) {
this.attacker = attacker;
this.defender = defender;
this.event = event;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* @return the attacking player.
*/
public Player getAttacker() {
return attacker;
}
/**
* @return the defending player.
*/
public Player getDefender() {
return defender;
}
public EntityDamageByEntityEvent getCause() {
return event;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -0,0 +1,305 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.PluginManager;
import com.sk89q.rebar.util.LoggerUtils;
/**
* Handles the "stop lag" mode.
*/
public class LagStopMode implements Listener {
private static final Logger logger = LoggerUtils.getLogger(LagStopMode.class,
"[WorldGuard] Lag Stop Mode: ");
private final WorldGuardPlugin plugin;
private boolean enabled = false;
private boolean removeAnimals = true;
LagStopMode(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register this class's events.
*/
void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
/**
* Get whether the lag stop mode is enabled.
*
* @return true if it's enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enable the lag stop mode. This will start the process and emit messages.
*
* @param unloadChunks true to unload chunks
*/
public void enable(boolean unloadChunks) {
if (!enabled) {
Server server = plugin.getServer();
server.broadcastMessage(ChatColor.GRAY
+ "(WorldGuard's 'lag stop' mode has been enabled. Some parts of the game may be 'frozen'. Keep calm and carry on.)");
// Remove entities
server.broadcastMessage(ChatColor.GRAY + "(Please wait... removing entities...)");
for (World world : server.getWorlds()) {
freeUp(world);
}
// Unloading chunks
if (unloadChunks) {
server.broadcastMessage(ChatColor.GRAY + "(Please wait... garbage collecting chunks...)");
for (World world : server.getWorlds()) {
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
chunk.unload(true, true);
}
}
}
server.broadcastMessage(ChatColor.GRAY + "(Completed. Lag stop mode is still enabled.)");
}
this.enabled = true;
}
/**
* Disable the lag stop mode.
*/
public void disable() {
if (enabled) {
Server server = plugin.getServer();
server.broadcastMessage(ChatColor.GRAY
+ "(WorldGuard's 'lag stop' mode is now off. Everything should proceed to start working again.)");
}
this.enabled = false;
}
/**
* Returns whether animals are being removed.
*
* @return true if animals are being removed
*/
public boolean isRemovingAnimals() {
return removeAnimals;
}
/**
* Set whether animals should be removed.
*
* @param removeAnimals true to remove animals
*/
public void setRemoveAnimals(boolean removeAnimals) {
this.removeAnimals = removeAnimals;
}
/**
* Remove items and other things within the chunk.
*
* @param plugin the plugin
* @param chunk the chunk to halt
*/
private void freeUp(Chunk chunk) {
int removed = 0;
for (Entity entity : chunk.getEntities()) {
if (shouldRemove(entity)) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info(removed + " entities (>50) auto-removed from " + chunk.toString());
}
}
/**
* Remove items and other things within the world.
*
* @param plugin the plugin
* @param world the world to halt
*/
private void freeUp(World world) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (shouldRemove(entity)) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info(removed + " entities (>50) auto-removed from " + world.toString());
}
}
/**
* Returns whether an entity should be removed.
*
* @param entity the entity to check
* @return true if it should be removed
*/
private boolean shouldRemove(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingBlock
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player)
&& (removeAnimals || !(entity instanceof Animals)));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
if (enabled) {
player.sendMessage(ChatColor.GRAY
+ "WorldGuard's 'lag stop' mode has been enabled. Some parts of the game may be 'frozen'.");
freeUp(world);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockFromTo(BlockFromToEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockIgnite(BlockIgniteEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBurn(BlockBurnEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockForm(BlockFormEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onLeavesDecay(LeavesDecayEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockSpread(BlockSpreadEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityExplode(EntityExplodeEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
if (enabled) {
freeUp(event.getChunk());
}
}
}
@@ -17,48 +17,58 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.logging.Logger;
import java.util.logging.Level;
package com.sk89q.worldguard.bukkit;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
/**
* Sends all logger messages to a player.
*
* @author sk89q
*/
public class LoggerToChatHandler extends Handler {
/**
* Player.
*/
private Player player;
private CommandSender player;
/**
* Construct the object.
*
*
* @param player
*/
public LoggerToChatHandler(Player player) {
public LoggerToChatHandler(CommandSender player) {
this.player = player;
}
/**
* Close the handler.
*/
@Override
public void close() {
}
/**
* Flush the output.
*/
@Override
public void flush() {
}
/**
* Publish a log record.
*/
@Override
public void publish(LogRecord record) {
player.sendMessage(Colors.LightGray + record.getLevel().getName() + ": "
+ Colors.White + record.getMessage());
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
player.sendMessage(ChatColor.RED + record.getLevel().getName() + ": "
+ ChatColor.YELLOW + record.getMessage());
} else {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.WHITE + record.getMessage());
}
}
}
@@ -0,0 +1,96 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.region.ApplicableRegionSet;
import com.sk89q.worldguard.region.RegionManager;
import com.sk89q.worldguard.region.RegionQueryCacheEntry;
/**
* A class that will cache all region queries. Instances of this class are created
* via an instance of {@link RegionQueryCache} and represent a point in time.
*/
public final class RegionQuery {
private final WorldGuardPlugin plugin;
private final RegionQueryCacheEntry entry;
/**
* Construct the instance with the underlying cache entry.
*
* @param entry
*/
RegionQuery(WorldGuardPlugin plugin, RegionQueryCacheEntry entry) {
this.plugin = plugin;
this.entry = entry;
}
/**
* Get an {@link ApplicableRegionSet} for a given location. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given location.
*
* @param location the location to check
* @return the set, or null if region protection is disabled for the given location
*/
public ApplicableRegionSet lookup(Location location) {
World world = location.getWorld();
Vector vector = BukkitUtil.toVector(location);
ConfigurationManager config = plugin.getGlobalStateManager();
WorldConfiguration worldConfig = config.get(world);
RegionManager regionManager = plugin.getGlobalRegionManager();
if (!worldConfig.useRegions) {
return null;
}
return entry.lookup(regionManager.get(world), vector);
}
/**
* Get an {@link ApplicableRegionSet} for a given block. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given block.
*
* @param block the block to check
* @return the set, or null if region protection is disabled for the given block
*/
public ApplicableRegionSet lookup(Block block) {
return lookup(block.getLocation());
}
/**
* Get an {@link ApplicableRegionSet} for a given entity. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given entity.
*
* @param entity the entity to check
* @return the set, or null if region protection is disabled for the given entity
*/
public ApplicableRegionSet lookup(Entity entity) {
return lookup(entity.getLocation());
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.event.Event;
import com.sk89q.worldguard.region.AbstractRegionQueryCache;
/**
* An implementation of {@link AbstractRegionQueryCache} for Bukkit. This implementation
* is thread-safe.
*/
public final class RegionQueryCache extends AbstractRegionQueryCache {
private final WorldGuardPlugin plugin;
/**
* Construct the cache with the given plugin instance.
*
* @param plugin plugin instance
*/
public RegionQueryCache(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Get a {@link RegionQuery} object that can cache region queries. The object
* returned by this method does not need to be cached. It is merely a proxy class.
*
* @param event the event to cache against
* @return an object to perform lookups against
*/
public RegionQuery against(Event event) {
return new RegionQuery(plugin, get(event));
}
}
@@ -0,0 +1,332 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.region.RegionManager;
import com.sk89q.worldguard.util.LogListBlock;
public class ReportWriter {
private static final SimpleDateFormat dateFmt =
new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
private Date date = new Date();
private StringBuilder output = new StringBuilder();
public ReportWriter(WorldGuardPlugin plugin) {
appendReportHeader(plugin);
appendServerInformation(plugin.getServer());
appendPluginInformation(plugin.getServer().getPluginManager().getPlugins());
appendWorldInformation(plugin.getServer().getWorlds());
appendGlobalConfiguration(plugin.getGlobalStateManager());
appendWorldConfigurations(plugin, plugin.getServer().getWorlds(),
plugin.getGlobalRegionManager(), plugin.getGlobalStateManager());
appendln("-------------");
appendln("END OF REPORT");
appendln();
}
protected static String repeat(String str, int n) {
if(str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
protected void appendln(String text) {
output.append(text);
output.append("\r\n");
}
protected void appendln(String text, Object ... args) {
output.append(String.format(text, args));
output.append("\r\n");
}
protected void append(LogListBlock log) {
output.append(log.toString());
}
protected void appendln() {
output.append("\r\n");
}
protected void appendHeader(String text) {
String rule = repeat("-", text.length());
output.append(rule);
output.append("\r\n");
appendln(text);
output.append(rule);
output.append("\r\n");
appendln();
}
private void appendReportHeader(WorldGuardPlugin plugin) {
appendln("WorldGuard Configuration Report");
appendln("Generated " + dateFmt.format(date));
appendln();
appendln("Version: " + plugin.getDescription().getVersion());
appendln();
}
private void appendGlobalConfiguration(ConfigurationManager config) {
appendHeader("Global Configuration");
LogListBlock log = new LogListBlock();
LogListBlock configLog = log.putChild("Configuration");
Class<? extends ConfigurationManager> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
if (field.getName().equalsIgnoreCase("CONFIG_HEADER")) continue;
Object val = field.get(config);
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException ignore) {
}
}
append(log);
appendln();
}
private void appendServerInformation(Server server) {
appendHeader("Server Information");
LogListBlock log = new LogListBlock();
Runtime runtime = Runtime.getRuntime();
log.put("Java", "%s %s (%s)",
System.getProperty("java.vendor"),
System.getProperty("java.version"),
System.getProperty("java.vendor.url"));
log.put("Operating system", "%s %s (%s)",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
log.put("Available processors", runtime.availableProcessors());
log.put("Free memory", runtime.freeMemory() / 1024 / 1024 + " MB");
log.put("Max memory", runtime.maxMemory() / 1024 / 1024 + " MB");
log.put("Total memory", runtime.totalMemory() / 1024 / 1024 + " MB");
log.put("Server ID", server.getServerId());
log.put("Server name", server.getServerName());
log.put("Implementation", server.getVersion());
//log.put("Address", server.getIp(), server.getPort());
log.put("Player count", "%d/%d",
server.getOnlinePlayers().length, server.getMaxPlayers());
append(log);
appendln();
}
private void appendPluginInformation(Plugin[] plugins) {
appendHeader("Plugins (" + plugins.length + ")");
LogListBlock log = new LogListBlock();
for (Plugin plugin : plugins) {
log.put(plugin.getDescription().getName(), plugin.getDescription().getVersion());
}
append(log);
appendln();
/*appendHeader("Plugin Information");
log = new LogListBlock();
for (Plugin plugin : plugins) {
log.putChild(plugin.getDescription().getName())
.put("Data folder", plugin.getDataFolder())
.put("Website", plugin.getDescription().getWebsite())
.put("Entry point", plugin.getDescription().getMain());
}
append(log);
appendln();*/
}
private void appendWorldInformation(List<World> worlds) {
appendHeader("Worlds");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
int loadedChunkCount = world.getLoadedChunks().length;
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock entitiesLog = worldLog.putChild("Entities");
infoLog.put("Seed", world.getSeed());
infoLog.put("Environment", world.getEnvironment().toString());
infoLog.put("Player count", world.getPlayers().size());
infoLog.put("Entity count", world.getEntities().size());
infoLog.put("Loaded chunk count", loadedChunkCount);
infoLog.put("Spawn location", world.getSpawnLocation());
infoLog.put("Raw time", world.getFullTime());
Map<Class<? extends Entity>, Integer> entityCounts =
new HashMap<Class<? extends Entity>, Integer>();
// Collect entities
for (Entity entity : world.getEntities()) {
Class<? extends Entity> cls = entity.getClass();
if (entityCounts.containsKey(cls)) {
entityCounts.put(cls, entityCounts.get(cls) + 1);
} else {
entityCounts.put(cls, 1);
}
}
// Print entities
for (Map.Entry<Class<? extends Entity>, Integer> entry
: entityCounts.entrySet()) {
entitiesLog.put(entry.getKey().getSimpleName(),
"%d [%f]",
entry.getValue(),
(float) (entry.getValue() / (double) loadedChunkCount));
}
i++;
}
append(log);
appendln();
}
private void appendWorldConfigurations(WorldGuardPlugin plugin, List<World> worlds,
RegionManager regionMgr, ConfigurationManager mgr) {
appendHeader("World Configurations");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock configLog = worldLog.putChild("Configuration");
LogListBlock blacklistLog = worldLog.putChild("Blacklist");
LogListBlock regionsLog = worldLog.putChild("Region manager");
infoLog.put("Configuration file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/config.yml")).getAbsoluteFile());
infoLog.put("Blacklist file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/blacklist.txt")).getAbsoluteFile());
infoLog.put("Regions file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/regions.yml")).getAbsoluteFile());
WorldConfiguration config = mgr.get(world);
Class<? extends WorldConfiguration> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException ignore) {
}
}
if (config.getBlacklist() == null) {
blacklistLog.put("State", "DISABLED");
} else {
blacklistLog.put("State", "Enabled");
blacklistLog.put("Number of items",
config.getBlacklist().getItemCount());
blacklistLog.put("Is whitelist",
config.getBlacklist().isWhitelist());
}
/*RegionIndex worldRegions = regionMgr.get(world);
regionsLog.put("Type", worldRegions.getClass().getCanonicalName());
regionsLog.put("Number of regions", worldRegions.getRegions().size());
LogListBlock globalRegionLog = regionsLog.putChild("Global region");
Region globalRegion = worldRegions.getRegion("__global__");
if (globalRegion == null) {
globalRegionLog.put("Status", "UNDEFINED");
} else {
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (flag instanceof StateFlag) {
globalRegionLog.put(flag.getName(),
globalRegion.getFlag(flag));
}
}
}*/
}
append(log);
appendln();
}
public void write(File file) throws IOException {
FileWriter writer = null;
BufferedWriter out;
try {
writer = new FileWriter(file);
out = new BufferedWriter(writer);
out.write(output.toString());
out.close();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
@Override
public String toString() {
return output.toString();
}
}
@@ -0,0 +1,196 @@
// $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.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.sk89q.worldedit.blocks.BlockID;
/**
* An applicator of the sponge feature.
*/
class SpongeApplicator {
private final int spongeRadius;
private final boolean useRedstone;
private final boolean refillArea;
/**
* Construct a new applicator.
*
* @param spongeRadius the radius of the sponge's effect
* @param useRedstone use Redstone
* @param refillArea refill the area if a sponge is removed
*/
public SpongeApplicator(int spongeRadius, boolean useRedstone, boolean refillArea) {
this.spongeRadius = spongeRadius;
this.useRedstone = useRedstone;
this.refillArea = refillArea;
}
/**
* Returns whether the block at the given position is water.
*
* @param world world
* @param x x
* @param y y
* @param z z
* @return true if it's water
*/
private static boolean isWater(World world, int x, int y, int z) {
int type = world.getBlockTypeIdAt(x, y, z);
return type == BlockID.WATER || type == BlockID.STATIONARY_WATER;
}
/**
* Returns whether the given sponge is an active sponge.
*
* @param block block to check
* @return true if it's active
*/
public boolean isActiveSponge(Block block) {
return block.getType() == Material.SPONGE
&& (!useRedstone || !block.isBlockIndirectlyPowered());
}
/**
* Return true if a given block near an active sponge.
*
* @param blockTo location of the block
* @return true if it's near a sponge (and water should be cancelled)
*/
public boolean isNearSponge(Block blockTo) {
World world = blockTo.getWorld();
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (isActiveSponge(sponge)) {
return true;
}
}
}
}
return false;
}
/**
* Remove water due to a sponge from the given position.
*
* @param block the block
*/
public void clearWater(Block block) {
World world = block.getWorld();
int ox = block.getX();
int oy = block.getY();
int oz = block.getZ();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
if (isWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water due to a sponge from the given position.
*
* @param block the block
*/
public void placeWater(Block block) {
if (!refillArea) return;
World world = block.getWorld();
int ox = block.getX();
int oy = block.getY();
int oz = block.getZ();
// The negative x edge
int cx = ox - spongeRadius - 1;
for (int cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx + 1, cy, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The positive x edge
cx = ox + spongeRadius + 1;
for (int cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx - 1, cy, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The negative y edge
int cy = oy - spongeRadius - 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy + 1, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The positive y edge
cy = oy + spongeRadius + 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy - 1, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The negative z edge
int cz = oz - spongeRadius - 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy, cz + 1).setType(Material.STATIONARY_WATER);
}
}
}
// The positive z edge
cz = oz + spongeRadius + 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy, cz - 1).setType(Material.STATIONARY_WATER);
}
}
}
}
}
@@ -0,0 +1,434 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.YamlConfiguration;
import com.sk89q.rebar.config.YamlConfigurationFile;
import com.sk89q.rebar.config.YamlConfigurationResource;
import com.sk89q.rebar.config.YamlStyle;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.RuleList;
import com.sk89q.rulelists.RuleEntry;
import com.sk89q.rulelists.RuleEntryLoader;
import com.sk89q.rulelists.RuleTemplateEntryLoader;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
import com.sk89q.worldguard.blacklist.loggers.ConsoleLoggerHandler;
import com.sk89q.worldguard.blacklist.loggers.DatabaseLoggerHandler;
import com.sk89q.worldguard.blacklist.loggers.FileLoggerHandler;
/**
* Holds the configuration for individual worlds.
*/
public class WorldConfiguration {
private static Logger logger = LoggerUtils.getLogger(WorldConfiguration.class, "[WorldGuard] ");
private final WorldGuardPlugin plugin;
private final ConfigurationManager configMan;
private final YamlConfigurationFile config;
private final String worldName;
private Blacklist blacklist;
private RuleList ruleList = new RuleList();
private SpongeApplicator spongeApplicator = null;
/* Configuration data start */
public boolean opPermissions;
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand;
public boolean regionInvinciblityRemovesMobs;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
public int maxClaimVolume;
public boolean claimOnlyInsideExistingRegions;
public int maxRegionCountPerPlayer;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
private Map<String, Integer> maxRegionCounts;
public boolean fireSpreadDisableToggle;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin the plugin instance
* @param worldName name of the world that this object is for
* @param configMan configuration manager
* @param parentConfig parent configuration
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName,
ConfigurationManager configMan, ConfigurationNode parentConfig) {
this.plugin = plugin;
this.worldName = worldName;
this.configMan = configMan;
File file = configMan.getWorldConfigFile(worldName);
config = new YamlConfigurationFile(file, ConfigurationManager.YAML_STYLE);
config.setParent(parentConfig);
load();
}
/**
* Load the configuration.
*/
private void load() {
logger.info("Loading configuration for '" + worldName + "'...");
loadConfig();
// Load rule lists
ruleList.clear();
loadBuiltInRules();
loadUserRules();
loadBlacklist();
loadSettings();
saveConfig();
}
/**
* Load the configuration from file.
*/
private void loadConfig() {
try {
config.load();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading configuration for world " + worldName, e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Error reading configuration for world " + worldName, e);
}
}
/**
* Save the configuration to file.
*/
private void saveConfig() {
config.setHeader(
"# CONFIGURATION FILE FOR ONLY THIS WORLD\r\n" +
"#\r\n" +
"# Everything in here applies to ONLY this world. For global settings, edit \r\n" +
"# the file in plugins/WorldGuard/config.yml\r\n" +
"#\r\n" +
"# How do you use this file? Copy potions of the global configuration file into this file.\r\n" +
"#\r\n" +
"# EXAMPLE (remove the # in front):\r\n" +
"#physics:\r\n" +
"# block-tnt-damage: false");
try {
config.save();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to save configuration", e);
}
}
/**
* Load the built-in rules.
*/
private void loadBuiltInRules() {
try {
RuleTemplateEntryLoader loader = new RuleTemplateEntryLoader(
plugin.getRulesListManager(), config);
for (List<RuleEntry> entries : plugin.getBuiltInRules().listOf("", loader)) {
for (RuleEntry entry : entries) {
ruleList.learn(entry);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load the built-in rules", e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to load the built-in rules", e);
}
}
/**
* Load the user rules.
*/
private void loadUserRules() {
File rulesFile = configMan.getRuleListFile(worldName);
RuleEntryLoader entryLoader = new RuleEntryLoader(plugin.getRulesListManager());
YamlConfigurationFile rulesConfig = new YamlConfigurationFile(rulesFile,
ConfigurationManager.YAML_STYLE, false);
try {
rulesConfig.load();
for (RuleEntry entry : rulesConfig.listOf(ConfigurationNode.ROOT, entryLoader)) {
ruleList.learn(entry);
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load " + rulesFile.getAbsolutePath(), e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to load " + rulesFile.getAbsolutePath(), e);
}
}
/**
* Load the blacklist.
*/
private void loadBlacklist() {
try {
if (blacklist != null) {
blacklist.getLogger().close();
}
File blacklistFile = configMan.getBlacklistFile(worldName);
// Load blacklist settings
boolean useBlacklistAsWhitelist = config.getBoolean("blacklist.use-as-whitelist", false);
boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true);
boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false);
String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = config.getString("blacklist.logging.database.user", "root");
String pass = config.getString("blacklist.logging.database.pass", "");
String table = config.getString("blacklist.logging.database.table", "blacklist_events");
boolean logFile = config.getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10));
Blacklist newBlacklist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
newBlacklist.load(blacklistFile);
// If the blacklist is empty, then set the field to null and save some resources
if (newBlacklist.isEmpty()) {
this.blacklist = null;
} else {
this.blacklist = newBlacklist;
logger.log(Level.INFO, "Blacklist loaded.");
BlacklistLogger blacklistLogger = newBlacklist.getLogger();
if (logDatabase)
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user,
pass, table, worldName, logger));
if (logConsole)
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName,
logger));
if (logFile) {
FileLoggerHandler handler = new FileLoggerHandler(logFilePattern,
logFileCacheSize, worldName, logger);
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "WorldGuard blacklist does not exist", e);
} catch (IOException e) {
logger.log(Level.WARNING, "Could not load blacklist", e);
}
}
/**
* Load the settings.
*/
private void loadSettings() {
opPermissions = config.getBoolean("op-permissions", true);
boolean simulateSponge = config.getBoolean("simulation.sponge.enable", true);
int spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1;
boolean redstoneSponges = config.getBoolean("simulation.sponge.redstone", false);
boolean refillArea = config.getBoolean("simulation.sponge.refill-area", false);
if (simulateSponge) {
spongeApplicator = new SpongeApplicator(spongeRadius, redstoneSponges, refillArea);
}
signChestProtection = config.getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = config.getBoolean("chest-protection.disable-off-check", false);
useRegions = config.getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = config.getBoolean("regions.invincibility-removes-mobs", false);
highFreqFlags = config.getBoolean("regions.high-frequency-flags", false);
regionWand = config.getInt("regions.wand", 287);
maxClaimVolume = config.getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = config.getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = config.getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : config.getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = config.get("regions.max-region-count-per-player." + key);
if (val != null && val instanceof Number) {
maxRegionCounts.put(key, ((Number) val).intValue());
}
}
}
// Very important part for protection!
if (useRegions) {
loadRegionModels();
}
// useiConomy = getBoolean("iconomy.enable", false);
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
}
/**
* Load region protection model.
*/
private void loadRegionModels() {
List<String> filenames;
RuleEntryLoader entryLoader = new RuleEntryLoader(plugin.getRulesListManager());
// Make a default protection model list
List<String> defaultProtectionModels = new ArrayList<String>();
defaultProtectionModels.add("minimal");
// Load protection model
filenames = config.getStringList("regions.protection-models", defaultProtectionModels);
for (YamlConfiguration config : readFiles(filenames, "/models/protection/",
new File(plugin.getDataFolder(), "models/protection"))) {
for (RuleEntry entry : config.listOf(ConfigurationNode.ROOT, entryLoader)) {
ruleList.learn(entry);
}
}
}
/**
* Get the blacklist.
*
* @return the blacklist
*/
Blacklist getBlacklist() {
return blacklist;
}
/**
* Get the RuleList.
*
* @return the rule list
*/
RuleList getRuleList() {
return ruleList;
}
/**
* Get the sponge applicator.
*
* @return sponge applicator
*/
SpongeApplicator getSpongeApplicator() {
return spongeApplicator;
}
/**
* Get the world name of this configuration.
*
* @return the world name
*/
public String getWorldName() {
return this.worldName;
}
/**
* Get the maximum region count for a given player.
*
* @param player player
* @return number of regions
*/
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
if (maxRegionCounts.containsKey(group)) {
int groupMax = maxRegionCounts.get(group);
if (max < groupMax) max = groupMax;
}
}
if (max <= -1) {
max = maxRegionCountPerPlayer;
}
return max;
}
/**
* Read a list of files, either from the .jar (preferred) or from disk.
*
* @param filenames list of filenames
* @param internalDir the base path for the JAR files
* @param externalDir the base dir for the disk files
* @return a list of {@link YamlConfiguration}s
*/
private static List<YamlConfiguration> readFiles(Collection<String> filenames,
String internalDir, File externalDir) {
List<YamlConfiguration> configs = new ArrayList<YamlConfiguration>();
for (String filename : filenames) {
YamlConfiguration config;
// External file path
File file = new File(externalDir, filename);
file.getParentFile().mkdirs();
// Try loading from the .jar first
String path = internalDir + filename + ".yml";
config = new YamlConfigurationResource(WorldGuardPlugin.class, path);
try {
config.load();
configs.add(config);
continue; // Found!
} catch (FileNotFoundException e) {
// Do nothing
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to internal path " + path, e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to internal path " + path, e);
}
// Try loading from disk
config = new YamlConfigurationFile(file, new YamlStyle(), false);
try {
config.load();
configs.add(config);
continue; // Found!
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, "Failed to load " + file.getAbsolutePath());
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load " + file.getAbsolutePath(), e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to load " + file.getAbsolutePath(), e);
}
}
return configs;
}
}
@@ -0,0 +1,463 @@
// $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.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.blocks.BlockID;
/**
* The listener for block events.
*/
class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Cake are damaged and not broken when they are eaten, so we must
// handle them a bit separately
if (blockDamaged.getTypeId() == BlockID.CAKE_BLOCK) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_BREAK);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
/* --- No short-circuit returns below this line --- */
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && isWater) {
if (spongeAppl.isNearSponge(blockTo)) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_SPREAD);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceBlock(event.getBlock().getState());
context.setTargetBlock(event.getToBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
boolean isFireSpread = cause == IgniteCause.SPREAD;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules;
BukkitContext context;
BlockState placedState;
switch (event.getCause()) {
case FLINT_AND_STEEL:
// Consider flint and steel as an item use
rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_USE);
context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setTargetBlock(event.getBlock().getState());
context.setItem(event.getPlayer().getItemInHand()); // Should be flint and steel
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
case LAVA:
case SPREAD:
// Consider everything else as a block spread
rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_SPREAD);
context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
// Make a virtual source state
BlockState sourceState = event.getBlock().getState();
sourceState.setType(event.getCause() == IgniteCause.LAVA ? Material.LAVA : Material.FIRE);
context.setSourceBlock(sourceState);
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
case FIREBALL:
case LIGHTNING:
// Consider everything else as a block spread
rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_PLACE);
context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
BukkitUtil.checkAndDestroyAround(block.getWorld(), block.getX(),
block.getY(), block.getZ(), BlockID.FIRE);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_BREAK);
BukkitContext context = new BukkitContext(plugin, event);
BlockState virtualFireState = event.getBlock().getState();
virtualFireState.setType(Material.FIRE);
context.setSourceBlock(virtualFireState);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_PHYSICS);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
/* --- No short-circuit returns below this line --- */
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
} else {
spongeAppl.clearWater(block);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlock();
World world = blockPlaced.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && spongeAppl.isActiveSponge(blockPlaced)) {
spongeAppl.clearWater(blockPlaced);
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_PLACE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getBlockReplacedState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
// Chest protection
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
if (!event.getLine(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (below == BlockID.TNT || below == BlockID.SAND
|| below == BlockID.GRAVEL || below == BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
event.setLine(0, "[Lock]");
player.sendMessage(ChatColor.YELLOW
+ "A chest or double chest above is now protected.");
}
} else if (!wcfg.disableSignChestProtectionCheck) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_FADE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_FORM);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_SPREAD);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceBlock(event.getSource().getState());
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_FADE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_DROP);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceBlock(event.getBlock().getState());
context.setItem(event.getItem());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,314 @@
// $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 org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldguard.region.RegionManager;
import com.sk89q.worldguard.region.flags.DefaultFlag;
/**
* The listener for entity events.
*/
class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getEntity());
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DEATH);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
// Set a message if it's a death from a player
if (event instanceof PlayerDeathEvent) {
context.setMessage(((PlayerDeathEvent) event).getDeathMessage());
}
rules.process(context);
// Set the message back
if (event instanceof PlayerDeathEvent) {
((PlayerDeathEvent) event).setDeathMessage(context.getMessage());
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// Redirect damage done by an entity
if (event instanceof EntityDamageByEntityEvent) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(((EntityDamageByEntityEvent) event).getDamager());
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
// Redirect damage done by blocks
} else if (event instanceof EntityDamageByBlockEvent) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
Block damager = ((EntityDamageByBlockEvent) event).getDamager();
if (damager != null) { // Should NOT be null!
context.setSourceBlock(damager.getState());
}
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
// Other damage
} else {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_IGNITE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(entity);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_EXPLODE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
/* --- No short-circuit returns below this line --- */
// Now apply RuleLists for each block
Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
Block block = iter.next();
rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_BREAK);
context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getEntity());
context.setTargetBlock(block.getState());
rules.process(context);
if (context.isCancelled()) {
iter.remove();
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_EXPLODE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_SPAWN);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_STRIKE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_STRIKE);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(event.getTo() == Material.AIR ?
DefaultAttachments.BLOCK_BREAK : DefaultAttachments.BLOCK_PLACE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(entity);
BlockState newState = event.getBlock().getState(); // This event is lame
newState.setType(event.getTo()); // Need to construct our own BlockState
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(newState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
RegionManager global = plugin.getGlobalRegionManager();
/* --- No short-circuit returns below this line --- */
int blockedEntities = 0;
for (LivingEntity e : event.getAffectedEntities()) {
if (!global.allows(DefaultFlag.POTION_SPLASH, e.getLocation(),
e instanceof Player ? plugin.wrapPlayer((Player) e) : null)) {
event.setIntensity(e, 0);
++blockedEntities;
}
}
if (blockedEntities == event.getAffectedEntities().size()) {
event.setCancelled(true);
}
}
}
@@ -0,0 +1,96 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Hanging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for hanging entity events.
*/
class WorldGuardHangingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardHangingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
if (event instanceof HangingBreakByEntityEvent) {
context.setSourceEntity(((HangingBreakByEntityEvent) event).getRemover());
}
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingPlace(HangingPlaceEvent event) {
Block placedOn = event.getBlock();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_SPAWN);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,98 @@
// $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.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Painting;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for painting related events. This event is deprecated and it is provided for
* compatibility with older versions of Bukkit.
*/
@Deprecated
public class WorldGuardPaintingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardPaintingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent event) {
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
if (event instanceof PaintingBreakByEntityEvent) {
context.setSourceEntity(((PaintingBreakByEntityEvent) event).getRemover());
}
context.setTargetEntity(event.getPainting());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_SPAWN);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setTargetEntity(event.getPainting());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,330 @@
// $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.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for player events.
*/
class WorldGuardPlayerListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardPlayerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
void registerEvents() {
final PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
if (plugin.getGlobalStateManager().usePlayerMove) {
pm.registerEvents(new PlayerMoveHandler(), plugin);
}
}
/**
* Listener just for {@link PlayerMoveEvent}. This handler may not always be
* registered for performance reasons.
*/
class PlayerMoveHandler implements Listener {
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
/* --- No short-circuit returns below this line --- */
if (wcfg.fireSpreadDisableToggle) {
player.sendMessage(ChatColor.YELLOW
+ "Fire spread is currently globally disabled for this world.");
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.PLAYER_JOIN);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(player);
rules.process(context);
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.CHAT);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setMessage(event.getMessage());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
// Put back the chat
event.setMessage(context.getMessage());
}
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
/* --- No short-circuit returns below this line --- */
// Host keys
String hostKey = cfg.hostKeys.get(player.getName().toLowerCase());
if (hostKey != null) {
String hostname = event.getHostname();
int colonIndex = hostname.indexOf(':');
if (colonIndex != -1) {
hostname = hostname.substring(0, colonIndex);
}
if (!hostname.equals(hostKey)) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"You did not join with the valid host key!");
plugin.getLogger().warning("WorldGuard host key check: " +
player.getName() + " joined with '" + hostname +
"' but '" + hostKey + "' was expected. Kicked!");
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.PLAYER_QUIT);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
rules.process(context);
// Cleanup
cfg.forgetPlayer(plugin.wrapPlayer(player));
plugin.forgetPlayer(player);
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules;
BukkitContext context;
// Send one for the block
Block block = event.getClickedBlock();
if (block != null) {
rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_INTERACT);
context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
context.setTargetBlock(event.getClickedBlock().getState());
if (rules.process(context)) {
event.setUseInteractedBlock(Result.DENY);
}
}
// Send one for the item in the end
ItemStack heldItem = event.getPlayer().getItemInHand();
if (heldItem != null) {
rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_USE);
context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setItem(heldItem);
if (rules.process(context)) {
event.setUseItemInHand(Result.DENY);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
Player player = event.getPlayer();
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_DROP);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
context.setItem(event.getItemDrop().getItemStack());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_PICKUP);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setItem(event.getItem().getItemStack());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DEATH);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(player);
rules.process(context);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_USE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setItem(event.getItemStack());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ITEM_USE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
context.setItem(event.getItemStack());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.PLAYER_RESPAWN);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(event.getPlayer());
rules.process(context);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(player);
context.setTargetBlock(event.getBed().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,933 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.hasHangingEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.SimpleInjector;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.rebar.bukkit.VirtualRebarPlugin;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.YamlConfiguration;
import com.sk89q.rebar.config.YamlConfigurationResource;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.Criteria;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.DefinitionManager;
import com.sk89q.rulelists.ResolverManager;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.commands.GeneralCommands;
import com.sk89q.worldguard.bukkit.commands.ProtectionCommands;
import com.sk89q.worldguard.bukkit.commands.ToggleCommands;
import com.sk89q.worldguard.bukkit.definitions.BlockCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.CancelActionLoader;
import com.sk89q.worldguard.bukkit.definitions.DamageCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.EntityCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.FlagCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.ItemCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.PermissionCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.PhenomenonCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.RegionCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.SetBlockActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SetDropActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SpawnCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.TellActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateEntityActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateItemActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SetMessageActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateWorldActionLoader;
import com.sk89q.worldguard.bukkit.definitions.WeatherCriteriaLoader;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlacedBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlayerItemStackSlotResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlayerItemStackSlotResolver.Slot;
import com.sk89q.worldguard.bukkit.resolvers.SourceBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.SourceEntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.TargetBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.TargetEntityResolver;
import com.sk89q.worldguard.region.RegionManager;
import com.sk89q.worldguard.region.indices.RegionIndex;
/**
* The main class for WorldGuard as a Bukkit plugin.
*/
public class WorldGuardPlugin extends JavaPlugin {
private final CommandsManager<CommandSender> commands;
private final RegionManager globalRegionManager;
private final ConfigurationManager configuration;
private RuleListsManager ruleListsManager;
private RegionQueryCache regionCache;
private final LagStopMode lagStopper;
private WorldGuardWorldListener worldListener;
/**
* Do initial loading of WorldGuard. Only called once. {@link #onEnable()} will be
* called when WorldGuard is enabled.
*/
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new RegionManager(this);
lagStopper = new LagStopMode(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@Override
public boolean hasPermission(CommandSender player, String perm) {
return plugin.hasPermission(player, perm);
}
};
}
@SuppressWarnings("deprecation")
@Override
public void onEnable() {
// We don't require Rebar yet
VirtualRebarPlugin.setup(this);
// Set up RuleLists
ruleListsManager = new RuleListsManager();
registerRuleList();
// Setup the cache
regionCache = new RegionQueryCache(this);
// Set the proper command injector
commands.setInjector(new SimpleInjector(this));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
if (!getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
}
}, 0L);
// Need to create the plugins/WorldGuard folder
getDataFolder().mkdirs();
PermissionsResolverManager.initialize(this);
// Load the configuration
configuration.load();
globalRegionManager.preload();
// Register events
(new WorldGuardPlayerListener(this)).registerEvents();
(new WorldGuardBlockListener(this)).registerEvents();
(new WorldGuardEntityListener(this)).registerEvents();
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
(worldListener = new WorldGuardWorldListener(this)).registerEvents();
lagStopper.registerEvents();
// Initialization
simulateWorldLoad();
if (hasHangingEvent()) {
(new WorldGuardHangingListener(this)).registerEvents();
} else {
(new WorldGuardPaintingListener(this)).registerEvents();
}
configuration.updateCommandBookGodMode();
}
@Override
public void onDisable() {
globalRegionManager.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
try {
commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
if (e.getCause() instanceof NumberFormatException) {
sender.sendMessage(ChatColor.RED + "Number expected, string received instead.");
} else {
sender.sendMessage(ChatColor.RED + "An error has occurred. See console.");
e.printStackTrace();
}
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
/**
* Dispatch {@link WorldLoadEvent}s to the world listener.
*/
public void simulateWorldLoad() {
for (World world : getServer().getWorlds()) {
WorldLoadEvent event = new WorldLoadEvent(world);
worldListener.onWorldLoad(event);
}
}
/**
* Get the GlobalRegionManager.
*
* @return The plugin's global region manager
*/
public RegionManager getGlobalRegionManager() {
return globalRegionManager;
}
/**
* Get the WorldGuard Configuration.
*
* @return ConfigurationManager
* @deprecated Use {@link #getGlobalStateManager()} instead
*/
@Deprecated
public ConfigurationManager getGlobalConfiguration() {
return getGlobalStateManager();
}
/**
* Get the global ConfigurationManager.
* USe this to access global configuration values and per-world configuration values.
* @return The global ConfigurationManager
*/
public ConfigurationManager getGlobalStateManager() {
return configuration;
}
/**
* Get the rules list manager.
*
* @return rule lists manager
*/
public RuleListsManager getRulesListManager() {
return ruleListsManager;
}
/**
* Get the region query cache.
*
* @return region query cache
*/
public RegionQueryCache getRegionCache() {
return regionCache;
}
/**
* Get the built-in rules.
*
* @return built-in rules
* @throws ConfigurationException on config error
* @throws IOException on I/O exception
*/
public YamlConfiguration getBuiltInRules() throws IOException, ConfigurationException {
YamlConfiguration rules = new YamlConfigurationResource(getClass(),
"/defaults/builtin_rules.yml");
rules.load();
return rules;
}
/**
* Register RuleList resolvers, criterion, and actions.
*/
private void registerRuleList() {
DefaultAttachments.registerWith(ruleListsManager.getAttachments());
// Subject resolvers
ResolverManager resolvers = ruleListsManager.getResolvers();
resolvers.register(BlockResolver.class, "source", new SourceBlockResolver());
resolvers.register(BlockResolver.class, "target", new TargetBlockResolver());
resolvers.register(BlockResolver.class, "placed", new PlacedBlockResolver());
resolvers.register(EntityResolver.class, "source", new SourceEntityResolver());
resolvers.register(EntityResolver.class, "target", new TargetEntityResolver());
resolvers.register(ItemStackSlotResolver.class, "held", new PlayerItemStackSlotResolver(Slot.HELD));
resolvers.register(ItemStackSlotResolver.class, "helmet", new PlayerItemStackSlotResolver(Slot.HELMET));
resolvers.register(ItemStackSlotResolver.class, "chestplate", new PlayerItemStackSlotResolver(Slot.CHESTPLATE));
resolvers.register(ItemStackSlotResolver.class, "leggings", new PlayerItemStackSlotResolver(Slot.LEGGINGS));
resolvers.register(ItemStackSlotResolver.class, "boots", new PlayerItemStackSlotResolver(Slot.BOOTS));
// Criterion
DefinitionManager<Criteria<?>> criterion = ruleListsManager.getCriterion();
criterion.register("match-block", new BlockCriteriaLoader(ruleListsManager));
criterion.register("match-item", new ItemCriteriaLoader(ruleListsManager));
criterion.register("match-entity", new EntityCriteriaLoader(ruleListsManager));
criterion.register("match-damage", new DamageCriteriaLoader());
criterion.register("match-spawn", new SpawnCriteriaLoader());
criterion.register("match-phenomenon", new PhenomenonCriteriaLoader());
criterion.register("match-weather", new WeatherCriteriaLoader());
criterion.register("region-of", new RegionCriteriaLoader(ruleListsManager));
criterion.register("has-flag", new FlagCriteriaLoader(this, ruleListsManager));
criterion.register("has-permission", new PermissionCriteriaLoader(this, ruleListsManager));
// Actions
DefinitionManager<Action<?>> actions = ruleListsManager.getActions();
actions.register("cancel", new CancelActionLoader());
actions.register("tell", new TellActionLoader(ruleListsManager));
actions.register("update-item", new UpdateItemActionLoader(ruleListsManager));
actions.register("update-world", new UpdateWorldActionLoader());
actions.register("update-entity", new UpdateEntityActionLoader(this, ruleListsManager));
actions.register("set-message", new SetMessageActionLoader(ruleListsManager));
actions.register("set-drop", new SetDropActionLoader());
actions.register("set-block", new SetBlockActionLoader(ruleListsManager));
}
/**
* Check whether a player is in a group.
* This calls the corresponding method in PermissionsResolverManager
*
* @param player The player to check
* @param group The group
* @return whether {@code player} is in {@code group}
*/
public boolean inGroup(Player player, String group) {
try {
return PermissionsResolverManager.getInstance().inGroup(player, group);
} catch (Throwable t) {
t.printStackTrace();
return false;
}
}
/**
* Get the groups of a player.
* This calls the corresponding method in PermissionsResolverManager.
* @param player The player to check
* @return The names of each group the playe is in.
*/
public String[] getGroups(Player player) {
try {
return PermissionsResolverManager.getInstance().getGroups(player);
} catch (Throwable t) {
t.printStackTrace();
return new String[0];
}
}
/**
* Gets the name of a command sender. This is a unique name and this
* method should never return a "display name".
*
* @param sender The sender to get the name of
* @return The unique name of the sender.
*/
public String toUniqueName(CommandSender sender) {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else {
return sender.getName();
}
}
/**
* Gets the name of a command sender. This play be a display name.
*
* @param sender The CommandSender to get the name of.
* @return The name of the given sender
*/
public String toName(CommandSender sender) {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else if (sender instanceof Player) {
return ((Player) sender).getDisplayName();
} else {
return sender.getName();
}
}
/**
* Checks permissions.
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @return whether {@code sender} has {@code perm}
*/
public boolean hasPermission(CommandSender sender, String perm) {
if (sender.isOp()) {
if (sender instanceof Player) {
if (this.getGlobalStateManager().get(((Player) sender).
getWorld()).opPermissions) {
return true;
}
} else {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
Player player = (Player) sender;
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player.getName(), perm);
}
return false;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @throws CommandPermissionsException if {@code sender} doesn't have {@code perm}
*/
public void checkPermission(CommandSender sender, String perm)
throws CommandPermissionsException {
if (!hasPermission(sender, perm)) {
throw new CommandPermissionsException();
}
}
/**
* Checks to see if the sender is a player, otherwise throw an exception.
*
* @param sender The {@link CommandSender} to check
* @return {@code sender} casted to a player
* @throws CommandException if {@code sender} isn't a {@link Player}
*/
public Player checkPlayer(CommandSender sender)
throws CommandException {
if (sender instanceof Player) {
return (Player) sender;
} else {
throw new CommandException("A player is expected.");
}
}
/**
* Match player names.
*
* The filter string uses the following format:
* @[name] looks up all players with the exact {@code name}
* *[name] matches any player whose name contains {@code name}
* [name] matches any player whose name starts with {@code name}
*
* @param filter The filter string to check.
* @return A {@link List} of players who match {@code filter}
*/
public List<Player> matchPlayerNames(String filter) {
Player[] players = getServer().getOnlinePlayers();
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (Player player : players) {
if (player.getName().equalsIgnoreCase(filter)) {
List<Player> list = new ArrayList<Player>();
list.add(player);
return list;
}
}
return new ArrayList<Player>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
/**
* Checks if the given list of players is greater than size 0, otherwise
* throw an exception.
*
* @param players The {@link List} to check
* @return {@code players} as an {@link Iterable}
* @throws CommandException If {@code players} is empty
*/
protected Iterable<Player> checkPlayerMatch(List<Player> players)
throws CommandException {
// Check to see if there were any matches
if (players.size() == 0) {
throw new CommandException("No players matched query.");
}
return players;
}
/**
* Matches players based on the specified filter string
*
* The filter string format is as follows:
* * returns all the players currently online
* If {@code sender} is a {@link Player}:
* #world returns all players in the world that {@code sender} is in
* #near reaturns all players within 30 blocks of {@code sender}'s location
* Otherwise, the format is as specified in {@link #matchPlayerNames(String)}
*
* @param source The CommandSender who is trying to find a player
* @param filter The filter string for players
* @return iterator for players
* @throws CommandException if no matches are found
*/
public Iterable<Player> matchPlayers(CommandSender source, String filter)
throws CommandException {
if (getServer().getOnlinePlayers().length == 0) {
throw new CommandException("No players matched query.");
}
if (filter.equals("*")) {
return checkPlayerMatch(Arrays.asList(getServer().getOnlinePlayers()));
}
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// Handle #world, which matches player of the same world as the
// calling source
if (filter.equalsIgnoreCase("#world")) {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
}
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
org.bukkit.util.Vector sourceVector
= sourcePlayer.getLocation().toVector();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)
&& player.getLocation().toVector().distanceSquared(
sourceVector) < 900) {
players.add(player);
}
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<Player> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
/**
* Match only a single player.
*
* @param sender The {@link CommandSender} who is requesting a player match
* @param filter The filter string.
* @see #matchPlayers(org.bukkit.entity.Player) for filter string syntax
* @return The single player
* @throws CommandException If more than one player match was found
*/
public Player matchSinglePlayer(CommandSender sender, String filter)
throws CommandException {
// This will throw an exception if there are no matches
Iterator<Player> players = matchPlayers(sender, filter).iterator();
Player match = players.next();
// We don't want to match the wrong person, so fail if if multiple
// players were found (we don't want to just pick off the first one,
// as that may be the wrong player)
if (players.hasNext()) {
throw new CommandException("More than one player found! " +
"Use @<name> for exact matching.");
}
return match;
}
/**
* Match only a single player or console.
*
* The filter string syntax is as follows:
* #console, *console, or ! return the server console
* All syntax from {@link #matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @param sender The sender trying to match a CommandSender
* @param filter The filter string
* @return The resulting CommandSender
* @throws CommandException if either zero or more than one player matched.
*/
public CommandSender matchPlayerOrConsole(CommandSender sender, String filter)
throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return getServer().getConsoleSender();
}
return matchSinglePlayer(sender, filter);
}
/**
* Get a single player as an iterator for players.
*
* @param player The player to return in an Iterable
* @return iterator for player
*/
public Iterable<Player> matchPlayers(Player player) {
return Arrays.asList(player);
}
/**
* Match a world.
*
* The filter string syntax is as follows:
* #main returns the main world
* #normal returns the first world with a normal environment
* #nether return the first world with a nether environment
* #player:[name] returns the world that a player named {@code name} is located in, if the player is online.
* [name] A world with the name {@code name}
*
* @param sender The sender requesting a match
* @param filter The filter string
* @return The resulting world
* @throws CommandException if no world matches
*/
public World matchWorld(CommandSender sender, String filter) throws CommandException {
List<World> worlds = getServer().getWorlds();
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
if (world.getEnvironment() == Environment.NORMAL) {
return world;
}
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
if (world.getEnvironment() == Environment.NETHER) {
return world;
}
}
throw new CommandException("No nether world found.");
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String parts[] = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
/**
* Gets a copy of the WorldEdit plugin.
*
* @return The WorldEditPlugin instance
* @throws CommandException If there is no WorldEditPlugin available
*/
public WorldEditPlugin getWorldEdit() throws CommandException {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
}
if (worldEdit instanceof WorldEditPlugin) {
return (WorldEditPlugin) worldEdit;
} else {
throw new CommandException("WorldEdit detection failed (report error).");
}
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player The player to wrap
* @return The wrapped player
*/
public LocalPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, player);
}
/**
* Create a default configuration file from the .jar.
*
* @param actual The destination file
* @param defaultName The name of the file inside the jar's defaults folder
*/
public void createDefaultConfiguration(File actual, String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (actual.exists()) {
return;
}
InputStream input = WorldGuardPlugin.class.getResourceAsStream("/defaults/" + defaultName);
if (input == null) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
try {
output = new FileOutputStream(actual);
byte[] buf = new byte[8192];
int length = 0;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
getLogger().info("Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ignore) {
}
try {
if (output != null) {
output.close();
}
} catch (IOException ignore) {
}
}
}
}
/**
* Notifies all with the worldguard.notify permission.
* This will check both superperms and WEPIF,
* but makes sure WEPIF checks don't result in duplicate notifications
*
* @param msg The notification to broadcast
*/
public void broadcastNotification(String msg) {
getServer().broadcast(msg, "worldguard.notify");
Set<Permissible> subs = getServer().getPluginManager().getPermissionSubscriptions("worldguard.notify");
for (Player player : getServer().getOnlinePlayers()) {
if (!(subs.contains(player) && player.hasPermission("worldguard.notify")) &&
hasPermission(player, "worldguard.notify")) { // Make sure the player wasn't already broadcasted to.
player.sendMessage(msg);
}
}
getLogger().info(msg);
}
/**
* Forgets a player.
*
* @param player The player to remove state information for
*/
public void forgetPlayer(Player player) {
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player The player to check.
* @param loc The location to check at.
* @see RegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.Location)
* @return whether {@code player} can build at {@code loc}
*/
public boolean canBuild(Player player, Location loc) {
return getGlobalRegionManager().canBuild(player, loc);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player The player to check
* @param block The block to check at.
* @see RegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.block.Block)
* @return whether {@code player} can build at {@code block}'s location
*/
public boolean canBuild(Player player, Block block) {
return getGlobalRegionManager().canBuild(player, block);
}
/**
* Gets the region manager for a world.
*
* @param world world to get the region manager for
* @return the region manager or null if regions are not enabled
*/
public RegionIndex getRegionManager(World world) {
if (!getGlobalStateManager().get(world).useRegions) {
return null;
}
return getGlobalRegionManager().get(world);
}
/**
* Get the "lag stop mode" controller.
*
* @return the lag stop mode
*/
public LagStopMode getLagStopMode() {
return lagStopper;
}
/**
* Replace macros in the text.
*
* The macros replaced are as follows:
* %name%: The name of {@code sender}. See {@link #toName(org.bukkit.command.CommandSender)}
* %id%: The unique name of the sender. See {@link #toUniqueName(org.bukkit.command.CommandSender)}
* %online%: The number of players currently online on the server
* If {@code sender} is a Player:
* %world%: The name of the world {@code sender} is located in
* %health%: The health of {@code sender}. See {@link org.bukkit.entity.Player#getHealth()}
*
* @param sender The sender to check
* @param message The message to replace macros in
* @return The message with macros replaced
*/
public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
message = message.replace("%name%", toName(sender));
message = message.replace("%id%", toUniqueName(sender));
message = message.replace("%online%", String.valueOf(online.length));
if (sender instanceof Player) {
Player player = (Player) sender;
World world = player.getWorld();
message = message.replace("%world%", world.getName());
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}
}
@@ -0,0 +1,48 @@
package com.sk89q.worldguard.bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* Listener for server events.
*/
class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
// Legacy god mode
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
// Legacy god mode
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
}
@@ -0,0 +1,57 @@
// $Id$
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* All rights reserved.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for vehicle events.
*/
class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
Vehicle vehicle = event.getVehicle();
Entity destroyer = event.getAttacker();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(vehicle.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(plugin, event);
context.setSourceEntity(destroyer);
context.setTargetEntity(vehicle);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,99 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for weather events.
*/
class WorldGuardWeatherListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WEATHER_TRANSITION);
BukkitContext context = new BukkitContext(plugin, event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WEATHER_TRANSITION);
BukkitContext context = new BukkitContext(plugin, event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
Location loc = event.getLightning().getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WEATHER_PHENOMENON);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetBlock(loc.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,79 @@
// $Id$
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* All rights reserved.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for world events.
*/
public class WorldGuardWorldListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register the events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WORLD_LOAD);
BukkitContext context = new BukkitContext(plugin, event);
rules.process(context);
}
@EventHandler
public void onWorldLoad(WorldUnloadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WORLD_UNLOAD);
BukkitContext context = new BukkitContext(plugin, event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void onWorldSave(WorldSaveEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
/* --- No short-circuit returns below this line --- */
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WORLD_SAVE);
BukkitContext context = new BukkitContext(plugin, event);
rules.process(context);
}
}
@@ -0,0 +1,303 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class GeneralCommands {
private final WorldGuardPlugin plugin;
public GeneralCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
@Command(aliases = {"god"}, usage = "[player]",
desc = "Enable godmode on a player", flags = "s", max = 1)
public void god(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
config.enableGodMode(player);
player.setFireTicks(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode enabled! Use /ungod to disable.");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God enabled by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players now have god mode.");
}
}
@SuppressWarnings("deprecation")
@Command(aliases = {"ungod"}, usage = "[player]",
desc = "Disable godmode on a player", flags = "s", max = 1)
public void ungod(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
config.disableGodMode(player);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode disabled!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God disabled by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players no longer have god mode.");
}
}
@Command(aliases = {"heal"}, usage = "[player]", desc = "Heal a player", flags = "s", max = 1)
public void heal(CommandContext args,CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal.other");
}
for (Player player : targets) {
player.setHealth(20);
player.setFoodLevel(20);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Healed!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Healed by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players healed.");
}
}
@Command(aliases = {"slay"}, usage = "[player]", desc = "Slay a player", flags = "s", max = 1)
public void slay(CommandContext args, CommandSender sender) throws CommandException {
Iterable<Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay.other");
}
for (Player player : targets) {
player.setHealth(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Slain!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Slain by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players slain.");
}
}
@Command(aliases = {"locate"}, usage = "[player]", desc = "Locate a player", max = 1)
@CommandPermissions({"worldguard.locate"})
public void locate(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
if (args.argsLength() == 0) {
player.setCompassTarget(player.getWorld().getSpawnLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass reset to spawn.");
} else {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
player.setCompassTarget(target.getLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass repointed.");
}
}
@Command(aliases = {"stack", ";"}, usage = "", desc = "Stack items", max = 0)
@CommandPermissions({"worldguard.stack"})
public void stack(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
boolean ignoreMax = plugin.hasPermission(player, "worldguard.stack.illegitimate");
boolean ignoreDamaged = plugin.hasPermission(player, "worldguard.stack.damaged");
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
int affected = 0;
for (int i = 0; i < len; i++) {
ItemStack item = items[i];
// Avoid infinite stacks and stacks with durability
if (item == null || item.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
int max = ignoreMax ? 64 : item.getMaxStackSize();
if (item.getAmount() < max) {
int needed = max - item.getAmount(); // Number of needed items until max
// Find another stack of the same type
for (int j = i + 1; j < len; j++) {
ItemStack item2 = items[j];
// Avoid infinite stacks and stacks with durability
if (item2 == null || item2.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
// Same type?
// Blocks store their color in the damage value
if (item2.getTypeId() == item.getTypeId() &&
((!ItemType.usesDamageValue(item.getTypeId()) && ignoreDamaged)
|| item.getDurability() == item2.getDurability()) &&
item.getEnchantments().equals(item2.getEnchantments())) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(max);
item2.setAmount(item2.getAmount() - needed);
break;
// This stack will
} else {
items[j] = null;
item.setAmount(item.getAmount() + item2.getAmount());
needed = max - item.getAmount();
}
affected++;
}
}
}
}
if (affected > 0) {
player.getInventory().setContents(items);
}
player.sendMessage(ChatColor.YELLOW + "Items compacted into stacks!");
}
}
@@ -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.bukkit.commands;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ProtectionCommands {
@SuppressWarnings("unused")
private final WorldGuardPlugin plugin;
public ProtectionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"region", "regions", "rg"}, desc = "Region management commands")
@NestedCommand({RegionCommands.class, RegionMemberCommands.class})
public void region(CommandContext args, CommandSender sender) {}
@Command(aliases = {"worldguard", "wg"}, desc = "WorldGuard commands")
@NestedCommand({WorldGuardCommands.class})
public void worldGuard(CommandContext args, CommandSender sender) {}
}
@@ -0,0 +1,965 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.region.ApplicableRegionSet;
import com.sk89q.worldguard.region.Region;
import com.sk89q.worldguard.region.flags.*;
import com.sk89q.worldguard.region.indices.RegionIndex;
import com.sk89q.worldguard.region.shapes.Cuboid;
import com.sk89q.worldguard.region.shapes.ExtrudedPolygon;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class RegionCommands {
private final WorldGuardPlugin plugin;
private MigratorKey migrateDBRequest;
private Date migrateDBRequestDate;
public RegionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"define", "def", "d"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Defines a region", min = 1)
@CommandPermissions({"worldguard.region.define"})
public void define(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!Region.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
RegionIndex mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (mgr.hasRegion(id)) {
throw new CommandException("That region is already defined. Use redefine instead.");
}
Region region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ExtrudedPolygon(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new Cuboid(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionDBUtil.parseDomainString(args.getSlice(1), 1));
}
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"redefine", "update", "move"}, usage = "<id>",
desc = "Re-defines the shape of a region", min = 1, max = 1)
public void redefine(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
WorldEditPlugin worldEdit = plugin.getWorldEdit();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region existing = mgr.getRegionExact(id);
if (existing == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (existing.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.redefine.own");
} else if (existing.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.redefine.member");
} else {
plugin.checkPermission(sender, "worldguard.region.redefine");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
Region region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ExtrudedPolygon(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new Cuboid(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
region.setMembers(existing.getMembers());
region.setOwners(existing.getOwners());
region.setFlags(existing.getFlags());
region.setPriority(existing.getPriority());
try {
region.setParent(existing.getParent());
} catch (CircularInheritanceException ignore) {
}
mgr.addRegion(region);
sender.sendMessage(ChatColor.YELLOW + "Region updated with new area.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"select", "sel", "s"}, usage = "[id]",
desc = "Load a region as a WorldEdit selection", min = 0, max = 1)
public void select(CommandContext args, CommandSender sender) throws CommandException {
final Player player = plugin.checkPlayer(sender);
final World world = player.getWorld();
final LocalPlayer localPlayer = plugin.wrapPlayer(player);
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final String id;
if (args.argsLength() == 0) {
final Vector pt = localPlayer.getPosition();
final ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (set.size() == 0) {
throw new CommandException("No region ID specified and no region found at current location!");
}
id = set.iterator().next().getId();
}
else {
id = args.getString(0);
}
final Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
selectRegion(player, localPlayer, region);
}
public void selectRegion(Player player, LocalPlayer localPlayer, Region region) throws CommandException, CommandPermissionsException {
final WorldEditPlugin worldEdit = plugin.getWorldEdit();
final String id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(player, "worldguard.region.select.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(player, "worldguard.region.select.member." + id.toLowerCase());
} else {
plugin.checkPermission(player, "worldguard.region.select." + id.toLowerCase());
}
final World world = player.getWorld();
if (region instanceof Cuboid) {
final Cuboid cuboid = (Cuboid) region;
final Vector pt1 = cuboid.getAABBMin();
final Vector pt2 = cuboid.getAABBMax();
final CuboidSelection selection = new CuboidSelection(world, pt1, pt2);
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a cuboid.");
} else if (region instanceof ExtrudedPolygon) {
final ExtrudedPolygon poly2d = (ExtrudedPolygon) region;
final Polygonal2DSelection selection = new Polygonal2DSelection(
world, poly2d.getPoints(),
poly2d.getAABBMin().getBlockY(),
poly2d.getAABBMax().getBlockY()
);
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
throw new CommandException("Can't select global regions.");
} else {
throw new CommandException("Unknown region type: " + region.getClass().getCanonicalName());
}
}
@Command(aliases = {"info", "i"}, usage = "[world] [id]", flags = "s",
desc = "Get information about a region", min = 0, max = 2)
public void info(CommandContext args, CommandSender sender) throws CommandException {
final LocalPlayer localPlayer;
final World world;
if (sender instanceof Player) {
final Player player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
} else if (args.argsLength() < 2) {
throw new CommandException("A player is expected.");
} else {
localPlayer = null;
world = plugin.matchWorld(sender, args.getString(0));
}
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final String id;
// Get different values based on provided arguments
switch (args.argsLength()) {
case 0:
if (localPlayer == null) {
throw new CommandException("A player is expected.");
}
final Vector pt = localPlayer.getPosition();
final ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (set.size() == 0) {
throw new CommandException("No region ID specified and no region found at current location!");
}
id = set.iterator().next().getId();
break;
case 1:
id = args.getString(0).toLowerCase();
break;
default:
id = args.getString(1).toLowerCase();
}
final Region region = mgr.getRegion(id);
if (region == null) {
if (!Region.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
}
displayRegionInfo(sender, localPlayer, region);
if (args.hasFlag('s')) {
selectRegion(plugin.checkPlayer(sender), localPlayer, region);
}
}
public void displayRegionInfo(CommandSender sender, final LocalPlayer localPlayer, Region region) throws CommandPermissionsException {
if (localPlayer == null) {
plugin.checkPermission(sender, "worldguard.region.info");
} else if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.own");
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.member");
} else {
plugin.checkPermission(sender, "worldguard.region.info");
}
final String id = region.getId();
sender.sendMessage(ChatColor.YELLOW + "Region: " + id + ChatColor.GRAY + ", type: " + region.getTypeName() + ", " + ChatColor.BLUE + "Priority: " + region.getPriority());
boolean hasFlags = false;
final StringBuilder s = new StringBuilder(ChatColor.BLUE + "Flags: ");
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object val = region.getFlag(flag), group = null;
if (val == null) {
continue;
}
if (hasFlags) {
s.append(", ");
}
RegionGroupFlag groupFlag = flag.getRegionGroupFlag();
if (groupFlag != null) {
group = region.getFlag(groupFlag);
}
if(group == null) {
s.append(flag.getName()).append(": ").append(String.valueOf(val));
} else {
s.append(flag.getName()).append(" -g ").append(String.valueOf(group)).append(": ").append(String.valueOf(val));
}
hasFlags = true;
}
if (hasFlags) {
sender.sendMessage(s.toString());
}
if (region.getParent() != null) {
sender.sendMessage(ChatColor.BLUE + "Parent: " + region.getParent().getId());
}
final DefaultDomain owners = region.getOwners();
if (owners.size() != 0) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Owners: " + owners.toUserFriendlyString());
}
final DefaultDomain members = region.getMembers();
if (members.size() != 0) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Members: " + members.toUserFriendlyString());
}
final BlockVector min = region.getAABBMin();
final BlockVector max = region.getAABBMax();
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds:"
+ " (" + min.getBlockX() + "," + min.getBlockY() + "," + min.getBlockZ() + ")"
+ " (" + max.getBlockX() + "," + max.getBlockY() + "," + max.getBlockZ() + ")"
);
}
public class RegionEntry implements Comparable<RegionEntry>{
private final String id;
private final int index;
private boolean isOwner;
private boolean isMember;
public RegionEntry(String id, int index) {
this.id = id;
this.index = index;
}
@Override
public int compareTo(RegionEntry o) {
if (isOwner != o.isOwner) {
return isOwner ? 1 : -1;
}
if (isMember != o.isMember) {
return isMember ? 1 : -1;
}
return id.compareTo(o.id);
}
@Override
public String toString() {
if (isOwner) {
return (index + 1) + ". +" + id;
} else if (isMember) {
return (index + 1) + ". -" + id;
} else {
return (index + 1) + ". " + id;
}
}
}
@Command(aliases = {"list"}, usage = "[.player] [page] [world]",
desc = "Get a list of regions", max = 3)
//@CommandPermissions({"worldguard.region.list"})
public void list(CommandContext args, CommandSender sender) throws CommandException {
World world;
int page = 0;
int argOffset = 0;
String name = "";
boolean own = false;
LocalPlayer localPlayer = null;
final String senderName = sender.getName().toLowerCase();
if (args.argsLength() > 0 && args.getString(0).startsWith(".")) {
name = args.getString(0).substring(1).toLowerCase();
argOffset = 1;
if (name.equals("me") || name.isEmpty() || name.equals(senderName)) {
own = true;
}
}
// Make /rg list default to "own" mode if the "worldguard.region.list" permission is not given
if (!own && !plugin.hasPermission(sender, "worldguard.region.list")) {
own = true;
}
if (own) {
plugin.checkPermission(sender, "worldguard.region.list.own");
name = senderName;
localPlayer = plugin.wrapPlayer(plugin.checkPlayer(sender));
}
if (args.argsLength() > argOffset) {
page = Math.max(0, args.getInteger(argOffset) - 1);
}
if (args.argsLength() > 1 + argOffset) {
world = plugin.matchWorld(sender, args.getString(1 + argOffset));
} else {
world = plugin.checkPlayer(sender).getWorld();
}
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final Map<String, Region> regions = mgr.getRegions();
List<RegionEntry> regionEntries = new ArrayList<RegionEntry>();
int index = 0;
for (String id : regions.keySet()) {
RegionEntry entry = new RegionEntry(id, index++);
if (!name.isEmpty()) {
if (own) {
entry.isOwner = regions.get(id).isOwner(localPlayer);
entry.isMember = regions.get(id).isMember(localPlayer);
}
else {
entry.isOwner = regions.get(id).isOwner(name);
entry.isMember = regions.get(id).isMember(name);
}
if (!entry.isOwner && !entry.isMember) {
continue;
}
}
regionEntries.add(entry);
}
Collections.sort(regionEntries);
final int totalSize = regionEntries.size();
final int pageSize = 10;
final int pages = (int) Math.ceil(totalSize / (float) pageSize);
sender.sendMessage(ChatColor.RED
+ (name.equals("") ? "Regions (page " : "Regions for " + name + " (page ")
+ (page + 1) + " of " + pages + "):");
if (page < pages) {
for (int i = page * pageSize; i < page * pageSize + pageSize; i++) {
if (i >= totalSize) {
break;
}
sender.sendMessage(ChatColor.YELLOW.toString() + regionEntries.get(i));
}
}
}
@Command(aliases = {"flag", "f"}, usage = "<id> <flag> [-g group] [value]", flags = "g:",
desc = "Set flags", min = 2)
public void flag(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
String flagName = args.getString(1);
String value = null;
RegionGroup groupValue = null;
if (args.argsLength() >= 3) {
value = args.getJoinedStrings(2);
}
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
if (id.equalsIgnoreCase("__global__")) {
region = new GlobalProtectedRegion(id);
mgr.addRegion(region);
} else {
throw new CommandException("Could not find a region by that ID.");
}
}
// @TODO deprecate "flag.[own./member./blank]"
boolean hasPerm = false;
if (region.isOwner(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.own." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.own." + id.toLowerCase())) hasPerm = true;
} else if (region.isMember(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.member." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.member." + id.toLowerCase())) hasPerm = true;
} else {
if (plugin.hasPermission(sender, "worldguard.region.flag." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions." + id.toLowerCase())) hasPerm = true;
}
if (!hasPerm) throw new CommandPermissionsException();
Flag<?> foundFlag = null;
// Now time to find the flag!
for (Flag<?> flag : DefaultFlag.getFlags()) {
// Try to detect the flag
if (flag.getName().replace("-", "").equalsIgnoreCase(flagName.replace("-", ""))) {
foundFlag = flag;
break;
}
}
if (foundFlag == null) {
StringBuilder list = new StringBuilder();
// Need to build a list
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (list.length() > 0) {
list.append(", ");
}
// @TODO deprecate inconsistant "owner" permission
if (region.isOwner(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".owner." + id.toLowerCase())
&& !plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".own." + id.toLowerCase())) {
continue;
}
} else if (region.isMember(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".member." + id.toLowerCase())) {
continue;
}
} else {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + "." + id.toLowerCase())) {
continue;
}
}
list.append(flag.getName());
}
player.sendMessage(ChatColor.RED + "Unknown flag specified: " + flagName);
player.sendMessage(ChatColor.RED + "Available flags: " + list);
return;
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".owner." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + "." + id.toLowerCase());
}
if (args.hasFlag('g')) {
String group = args.getFlag('g');
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
if (groupFlag == null) {
throw new CommandException("Region flag '" + foundFlag.getName()
+ "' does not have a group flag!");
}
// Parse the [-g group] separately so entire command can abort if parsing
// the [value] part throws an error.
try {
groupValue = groupFlag.parseInput(plugin, sender, group);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
}
if (value != null) {
// Set the flag if [value] was given even if [-g group] was given as well
try {
setFlag(region, foundFlag, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' set.");
}
if (value == null && !args.hasFlag('g')) {
// Clear the flag only if neither [value] nor [-g group] was given
region.setFlag(foundFlag, null);
// Also clear the associated group flag if one exists
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
if (groupFlag != null) {
region.setFlag(groupFlag, null);
}
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' cleared.");
}
if (groupValue != null) {
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
// If group set to the default, then clear the group flag
if (groupValue == groupFlag.getDefault()) {
region.setFlag(groupFlag, null);
sender.sendMessage(ChatColor.YELLOW
+ "Region group flag for '" + foundFlag.getName() + "' reset to default.");
} else {
region.setFlag(groupFlag, groupValue);
sender.sendMessage(ChatColor.YELLOW
+ "Region group flag for '" + foundFlag.getName() + "' set.");
}
}
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
public <V> void setFlag(Region region,
Flag<V> flag, CommandSender sender, String value)
throws InvalidFlagFormat {
region.setFlag(flag, flag.parseInput(plugin, sender, value));
}
@Command(aliases = {"setpriority", "priority", "pri"}, usage = "<id> <priority>",
desc = "Set the priority of a region", min = 2, max = 2)
public void setPriority(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
int priority = args.getInteger(1);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setpriority." + id.toLowerCase());
}
region.setPriority(priority);
sender.sendMessage(ChatColor.YELLOW
+ "Priority of '" + region.getId() + "' set to "
+ priority + ".");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"setparent", "parent", "par"}, usage = "<id> [parent-id]",
desc = "Set the parent of a region", min = 1, max = 2)
public void setParent(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a target region by that ID.");
}
id = region.getId();
if (args.argsLength() == 1) {
try {
region.setParent(null);
} catch (CircularInheritanceException ignore) {
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' cleared.");
} else {
String parentId = args.getString(1);
Region parent = mgr.getRegion(parentId);
if (parent == null) {
throw new CommandException("Could not find the parent region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
}
if (parent.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + parentId.toLowerCase());
} else if (parent.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + parentId.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + parentId.toLowerCase());
}
try {
region.setParent(parent);
} catch (CircularInheritanceException e) {
throw new CommandException("Circular inheritance detected!");
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' set to '"
+ parent.getId() + "'.");
}
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"remove", "delete", "del", "rem"}, usage = "<id>",
desc = "Remove a region", min = 1, max = 1)
public void remove(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegionExact(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.remove." + id.toLowerCase());
}
mgr.removeRegion(id);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' removed.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"load", "reload"}, usage = "[world]",
desc = "Reload regions from file", max = 1)
@CommandPermissions({"worldguard.region.load"})
public void load(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.load();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' load.");
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to read regions: "
+ e.getMessage());
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionIndex mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.load();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to read regions: "
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases loaded.");
}
}
@Command(aliases = {"save", "write"}, usage = "[world]",
desc = "Re-save regions to file", max = 1)
@CommandPermissions({"worldguard.region.save"})
public void save(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW
+ "Regions for '" + world.getName() + "' saved.");
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionIndex mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases saved.");
}
}
@Command(aliases = {"teleport", "tp"}, usage = "<id>", flags = "s",
desc = "Teleports you to the location associated with the region.", min = 1, max = 1)
@CommandPermissions({"worldguard.region.teleport"})
public void teleport(CommandContext args, CommandSender sender) throws CommandException {
final Player player = plugin.checkPlayer(sender);
final RegionIndex mgr = plugin.getGlobalRegionManager().get(player.getWorld());
String id = args.getString(0);
final Region region = mgr.getRegion(id);
if (region == null) {
if (!Region.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
}
id = region.getId();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.teleport.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.teleport.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.teleport." + id.toLowerCase());
}
final Location teleportLocation;
if (args.hasFlag('s')) {
teleportLocation = region.getFlag(DefaultFlag.SPAWN_LOC);
if (teleportLocation == null) {
throw new CommandException("The region has no spawn point associated.");
}
} else {
teleportLocation = region.getFlag(DefaultFlag.TELE_LOC);
if (teleportLocation == null) {
throw new CommandException("The region has no teleport point associated.");
}
}
player.teleport(BukkitUtil.toLocation(teleportLocation));
sender.sendMessage("Teleported you to the region '" + id + "'.");
}
}
@@ -0,0 +1,221 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.region.Region;
import com.sk89q.worldguard.region.flags.DefaultFlag;
import com.sk89q.worldguard.region.indices.RegionIndex;
import com.sk89q.worldguard.region.stores.ProtectionDatabaseException;
import com.sk89q.worldguard.region.stores.RegionDBUtil;
// @TODO: A lot of code duplication here! Need to fix.
public class RegionMemberCommands {
private final WorldGuardPlugin plugin;
public RegionMemberCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"addmember", "addmember"}, usage = "<id> <members...>",
desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
}
RegionDBUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"}, usage = "<id> <owners...>",
desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (flag != null && flag && owners != null && owners.size() == 0) {
if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
if (maxRegionCount >= 0 && mgr.getRegionCountOfPlayer(localPlayer)
>= maxRegionCount) {
throw new CommandException("You already own the maximum allowed amount of regions.");
}
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
} else {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
}
RegionDBUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
}
RegionDBUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeOwner(CommandContext args,
CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
}
RegionDBUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
throw new CommandException("Failed to write regions: "
+ e.getMessage());
}
}
}
@@ -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.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.LagStopMode;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ToggleCommands {
private final WorldGuardPlugin plugin;
public ToggleCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"stopfire"}, usage = "[<world>]",
desc = "Disables all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void stopFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (!wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(
ChatColor.YELLOW
+ "Fire spread has been globally disabled for '" + world.getName() + "' by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(
ChatColor.YELLOW
+ "Fire spread was already globally disabled.");
}
wcfg.fireSpreadDisableToggle = true;
}
@Command(aliases = {"allowfire"}, usage = "[<world>]",
desc = "Allows all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void allowFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "Fire spread has been globally for '" + world.getName() + "' re-enabled by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(ChatColor.YELLOW
+ "Fire spread was already globally enabled.");
}
wcfg.fireSpreadDisableToggle = false;
}
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "cag", max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public void stopLag(CommandContext args, CommandSender sender) throws CommandException {
LagStopMode lagStopper = plugin.getLagStopMode();
lagStopper.setRemoveAnimals(!args.hasFlag('c'));
if (!args.hasFlag('c')) {
sender.sendMessage(ChatColor.YELLOW + "Enabling lag stop mode...");
lagStopper.enable(!args.hasFlag('g'));
} else {
sender.sendMessage(ChatColor.YELLOW + "Disabling lag stop mode...");
lagStopper.disable();
}
}
}
@@ -0,0 +1,143 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.rebar.util.MaterialDatabase;
import com.sk89q.worldguard.bukkit.LoggerToChatHandler;
import com.sk89q.worldguard.bukkit.ReportWriter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
public class WorldGuardCommands {
private final WorldGuardPlugin plugin;
public WorldGuardCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"version"}, desc = "Get the WorldGuard version", max = 0)
public void version(CommandContext args, CommandSender sender) throws CommandException {
sender.sendMessage(ChatColor.YELLOW
+ "WorldGuard " + plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "http://www.sk89q.com");
}
@Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
@CommandPermissions({"worldguard.reload"})
public void reload(CommandContext args, CommandSender sender) throws CommandException {
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
if (sender instanceof Player) {
handler = new LoggerToChatHandler(sender);
handler.setLevel(Level.ALL);
minecraftLogger = Logger.getLogger("");
minecraftLogger.addHandler(handler);
}
try {
MaterialDatabase.reload();
plugin.getGlobalStateManager().unload();
plugin.getGlobalRegionManager().unload();
plugin.getGlobalStateManager().load();
plugin.getGlobalRegionManager().preload();
sender.sendMessage("WorldGuard configuration reloaded.");
} catch (Throwable t) {
sender.sendMessage("Error while reloading: "
+ t.getMessage());
} finally {
if (minecraftLogger != null) {
minecraftLogger.removeHandler(handler);
}
}
plugin.simulateWorldLoad();
}
@Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({"worldguard.report"})
public void report(CommandContext args, final CommandSender sender) throws CommandException {
File dest = new File(plugin.getDataFolder(), "report.txt");
ReportWriter report = new ReportWriter(plugin);
try {
report.write(dest);
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report written to "
+ dest.getAbsolutePath());
} catch (IOException e) {
throw new CommandException("Failed to write report: " + e.getMessage());
}
if (args.hasFlag('p')) {
plugin.checkPermission(sender, "worldguard.report.pastebin");
sender.sendMessage(ChatColor.YELLOW + "Now uploading to Pastebin...");
PastebinPoster.paste(report.toString(), new PasteCallback() {
@Override
public void handleSuccess(String url) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report (1 hour): " + url);
}
@Override
public void handleError(String err) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report pastebin error: " + err);
}
});
}
}
@Command(aliases = {"flushstates", "clearstates"},
usage = "[player]", desc = "Flush the state manager", max = 1)
@CommandPermissions("worldguard.flushstates")
public void flushStates(CommandContext args, CommandSender sender) throws CommandException {
if (args.argsLength() == 0) {
plugin.getFlagStateManager().forgetAll();
sender.sendMessage("Cleared all states.");
} else {
Player player = plugin.getServer().getPlayer(args.getString(0));
if (player != null) {
plugin.getFlagStateManager().forget(player);
sender.sendMessage("Cleared states for player \"" + player.getName() + "\".");
}
}
}
}
@@ -0,0 +1,117 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class BlockCriteria implements Criteria<BukkitContext> {
public enum Direction {
AT,
ABOVE,
BELOW,
AROUND
}
private final BlockResolver resolver;
private Direction direction;
private MaterialPattern[] patterns = new MaterialPattern[0];
public BlockCriteria(BlockResolver resolver) {
this.resolver = resolver;
}
public MaterialPattern[] getPatterns() {
return patterns;
}
public void setPatterns(MaterialPattern[] patterns) {
this.patterns = patterns;
}
public void setPatterns(List<MaterialPattern> patterns) {
MaterialPattern[] arr = new MaterialPattern[patterns.size()];
patterns.toArray(arr);
this.patterns = arr;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
private boolean matches(BlockState block) {
for (MaterialPattern pattern : patterns) {
if (pattern.matches(block.getTypeId(), block.getRawData())) {
return true;
}
}
return false;
}
private boolean matches(Block block) {
for (MaterialPattern pattern : patterns) {
if (pattern.matches(block.getTypeId(), block.getData())) {
return true;
}
}
return false;
}
@Override
public boolean matches(BukkitContext context) {
BlockState block = resolver.resolve(context);
if (block == null) {
return false;
}
switch (getDirection()) {
case AT:
return matches(block);
case ABOVE:
return matches(block.getBlock().getRelative(0, 1, 0));
case BELOW:
return matches(block.getBlock().getRelative(0, -1, 0));
case AROUND:
return matches(block.getBlock().getRelative(0, -1, 0)) ||
matches(block.getBlock().getRelative(0, 1, 0)) ||
matches(block.getBlock().getRelative(-1, 0, 0)) ||
matches(block.getBlock().getRelative(1, 0, 0)) ||
matches(block.getBlock().getRelative(0, 0, -1)) ||
matches(block.getBlock().getRelative(0, 0, 1));
}
return false;
}
}
@@ -0,0 +1,74 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.List;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.config.types.MaterialPatternLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.definitions.BlockCriteria.Direction;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class BlockCriteriaLoader extends AbstractNodeLoader<BlockCriteria> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
private EnumLoaderBuilder<Direction> dirLoader = new EnumLoaderBuilder<Direction>(Direction.class);
public BlockCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public BlockCriteria read(ConfigurationNode node)
throws DefinitionException {
BlockResolver resolver = manager.getResolvers()
.get(BlockResolver.class, node.getString("block", BlockResolver.DEFAULT));
// Load patterns
List<MaterialPattern> patterns = node.contains(INLINE) ?
node.listOf(INLINE, materialLoader) : node.listOf("material", materialLoader);
if (patterns.size() == 0) {
throw new LoaderBuilderException("No block materials specified");
}
// Load direction
Direction direction = node.getOf("relative", dirLoader, Direction.AT);
BlockCriteria criteria = new BlockCriteria(resolver);
criteria.setPatterns(patterns);
criteria.setDirection(direction);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"block", "material", "relative");
return criteria;
}
}
@@ -0,0 +1,31 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.Context;
public class CancelAction implements Action<Context> {
@Override
public void apply(Context context) {
context.cancel();
}
}
@@ -0,0 +1,39 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class CancelActionLoader extends AbstractNodeLoader<CancelAction> {
private final CancelAction instance = new CancelAction();
@Override
public CancelAction read(ConfigurationNode node)
throws DefinitionException {
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()));
return instance;
}
}
@@ -0,0 +1,58 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class DamageCriteria implements Criteria<BukkitContext> {
private Set<DamageCause> causes = new HashSet<DamageCause>();
public DamageCriteria(Set<DamageCause> causes) {
this.causes = causes;
}
public Set<DamageCause> getCauses() {
return causes;
}
public void setCauses(Set<DamageCause> causes) {
this.causes = causes;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof EntityDamageEvent) {
return causes.contains(((EntityDamageEvent) event).getCause());
} else {
return false;
}
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.Set;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class DamageCriteriaLoader extends AbstractNodeLoader<DamageCriteria> {
private EnumLoaderBuilder<DamageCause> typeLoader =
new EnumLoaderBuilder<DamageCause>(DamageCause.class);
@Override
public DamageCriteria read(ConfigurationNode node) throws DefinitionException {
Set<DamageCause> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
DamageCriteria criteria = new DamageCriteria(types);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more