Compare commits

..
144 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
212 changed files with 13442 additions and 11931 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
language: java
jdk:
- oraclejdk7
- openjdk7
- openjdk6
notifications:
email: false
+71 -26
View File
@@ -1,3 +1,39 @@
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.
@@ -19,32 +55,41 @@
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.
- 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
+69
View File
@@ -0,0 +1,69 @@
Contributing
============
Thank you for your interest in contributing to WorldGuard! We appreciate your
effort, but to make sure that the inclusion of your patch is a smooth process, we
ask that you make note of the following guidelines.
* **Follow the [Oracle coding conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html).**
We can't stress this enough; if your code has notable issues, it may delay
the process significantly.
* **Target Java 6 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
and other such tasks easier. Ignore this guideline if it makes the code
too unreadable.
* **Write complete Javadocs.** Do so only for public methods, and make sure
that your `@param` and `@return` fields are not just blank.
* **Don't tag classes with @author.** Some legacy classes may have this tag,
but we are phasing it out.
* **Make sure the code is efficient.** One way you can achieve this is to spend
around ten minutes to think about what the code is doing and whether it
seems awfully roundabout. If you had to copy the same large piece of
code in several places, that's bad.
* **Keep commit summaries under 70 characters.** For more details, place two
new lines after the summary line and write away!
* **Test your code.** We're not interested in broken code, for the obvious reasons.
* **Write unit tests.** While this is strictly optional, we recommend it for
complicated algorithms.
Checklist
---------
Ready to submit? Perform the checklist below:
1. Have all tabs been replaced into four spaces? Are indentations 4-space wide?
2. Have I written proper Javadocs for my public methods? Are the @param and
@return fields actually filled out?
3. Have I `git rebase`d my pull request to the latest commit of the target
branch?
4. Have I combined my commits into a reasonably small number (if not one)
commit using `git rebase`?
5. Have I made my pull request too large? Pull requests should introduce
small sets of changes at a time. Major changes should be discussed with
the team prior to starting work.
6. Are my commit messages descriptive?
You should be aware of [`git rebase`](http://learn.github.com/p/rebasing.html).
It allows you to modify existing commit messages, and combine, break apart, or
adjust past changes.
Example
-------
This is **GOOD:**
if (var.func(param1, param2)) {
// do things
}
This is **EXTREMELY BAD:**
if(var.func( param1, param2 ))
{
// do things
}
+204 -88
View File
@@ -1,116 +1,232 @@
<!DOCTYPE html>
<html>
<head>
<title>WorldGuard ${version}</title>
<title>${project.name} ${version}</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Ropa+Sans" rel="stylesheet" type="text/css">
<style>
body {
margin: 0;
padding: 20px;
background: #efefef;
color: #333;
margin: 0;
padding: 3em 1em;
background: #efefef;
color: #333;
line-height: 1.5;
}
#wrapper {
margin: 20px auto 20px auto;
width: 600px;
background: #fff;
padding: 40px;
border: 1px solid #fff;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
box-shadow: 0 0 2px #999;
-webkit-box-shadow: 0 0 3px #999;
}
a img {
border: 0;
width: 600px;
margin: auto;
}
body, th, td, input {
font: 13px/17px "Lucida Grande", "Lucida Sans Unicode", Arial, Verdana, sans-serif;
font: 14px 'Source Sans Pro', Arial, sans-serifsans-serif;
}
.section {
background: #fff;
position: relative;
padding: 2em 2.4em;
margin: 3em auto 4em auto;
width: 80%;
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.section:before, .section:after {
content: "";
position: absolute;
z-index: -2;
}
.section {
-moz-border-radius: 4px;
border-radius: 4px;
}
.section:before, .section:after {
bottom: 15px;
left: 10px;
width: 50%;
height: 20%;
max-width: 300px;
max-height: 100px;
-webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-webkit-transform: rotate(-1deg);
-moz-transform: rotate(-1deg);
-ms-transform: rotate(-1deg);
-o-transform: rotate(-1deg);
transform: rotate(-1deg);
}
.section:after {
right: 10px;
left: auto;
-webkit-transform: rotate(1deg);
-moz-transform: rotate(1deg);
-ms-transform: rotate(1deg);
-o-transform: rotate(1deg);
transform: rotate(1deg);
}
a:link, a:visited {
color: #00688f;
text-decoration: underline;
color: #0004b2;
text-decoration: none;
}
a:hover, a:active {
color: #000;
border: 0;
a:hover {
color: #ac0000;
text-decoration: none;
border-bottom: 1px solid #999;
}
h1 {
font: 170% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #b90000;
margin: 15px 0 5px 0;
font: 2.7em 'Ropa Sans', 'Trebuchet MS', Helvetica, Arial, sans-serif;
color: #000;
margin: 0 0;
padding: 0 0 0.2em 0;
font-weight: normal;
text-align: center;
text-shadow: 2px 2px #FFF;
}
h2 {
font: 130% "Trebuchet MS", Georgia, serif;
font-weight: bold;
color: #6a45ac;
margin: 50px 0 5px 0;
padding: 0 0 3px 0;
border-bottom: 1px solid #ccc;
font-size: 1.3em;
color: #FFF;
margin: -2.5em 0 0.8em 0;
float: left;
background: #0049FF;
padding: 0.4em 0.8em;
border-radius: 0.2em;
font-weight: normal;
text-align: center;
}
.warning {
background: #fffedf;
padding: 8px;
border: 1px dashed #ccc;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 90%;
h3 {
text-transform: uppercase;
font-weight: bold;
}
.subtle {
color: #999;
h2 + * {
clear: both;
}
.optional {
background: none repeat scroll 0 0 #FFE081;
border-radius: 3px 3px 3px 3px;
font-size: 80%;
font-weight: normal;
padding: 1px 4px;
@media (max-width: 650px) {
#wrapper {
width: 100%;
}
}
</style>
</head>
<body>
<div id="wrapper">
<h1>WorldGuard ${version}</h1>
<p>Thanks for choosing WorldGuard!</p>
<h2>Getting Started</h2>
<p>Now, to begin, you want to:</p>
<ol>
<li><strong>Install the plugin:</strong> Copy WorldGuard.jar into your Bukkit server's &quot;plugins&quot; directory.</li>
<li><strong>Change the configuration:</strong> Run your server once (with WorldGuard) to generate the default configuration files. There are <em>two</em> types of configuration files:
<ul>
<li>The main config.yml file inside &quot;plugins/WorldGuard&quot; is the main configuration. </li>
<li>Each world has a configuration file in &quot;plugins/WorldGuard/worlds&quot; that you can use to override any setting in the main configuration file for that specific world.</li>
</ul>
</li>
Use <em>/wg reload</em> in the console to reload the configuration.
<li><strong>Learn how to use WorldGuard:</strong> Check <a href="http://wiki.sk89q.com/wiki/WorldGuard">out the wiki</a> to learn how to disable things like fire and to protect regions.</li>
</ol>
<p class="warning"><strong>Note:</strong> <a href="http://www.sk89q.com/projects/worldedit/">WorldEdit</a> must be installed, but if you do not want it, put WorldEdit.jar into your Bukkit root folder (outside of plugins/). Note that region protection requires WorldEdit in plugins/.</p>
<p>Be sure to:</p>
<ul>
<li>Subscribe to <a href="http://minecraftnews.sk89q.com/">SK's Minecraft blog</a> for news about WorldGuard</li>
<li>Idle with us in IRC at <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a></li>
</ul>
<h2>Getting Help</h2>
<p>If you need help, the best two ways to ask are:</p>
<ul>
<li><a href="http://forum.sk89q.com/">Visit the WorldGuard forum</a></li>
<li>Ask in IRC chat on <a href="http://skq.me/irc/irc.esper.net/worldguard">irc.esper.net in #worldguard</a> (idle with us!)</li>
<li>Submit bug reports and suggestions to the <a href="http://redmine.sk89q.com/projects/worldguard/issues">issue tracker</a></li>
</ul>
<h2>Contributing</h2>
<p>WorldGuard is entirely open source! You can download all of the plugin code to learn from it, modify it for your own self, or even contribute back!</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">Download WorldGuard code from GitHub</a></li>
<li>You can also <a href="http://www.sk89q.com/donate/">donate</a></li>
</ul>
<p>The code is covered under the GNU General Public License v3.</p>
<p class="subtle">Maven information: ${groupId}/${artifactId}/${version}</p>
<h1>${project.name} ${version}</h1>
<div class="section">
<h2>Getting Started</h2>
<p>
Thanks for choosing ${project.name}! When you first install ${project.name},
nothing will be enabled, so you will need to switch on the features
that you need to use, whenever it is convenient for you.
</p>
<ul>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Installation">How do I install ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Upgrading">How do I update ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}#Usage">How do I use ${project.name}?</a></li>
</ul>
<p>
Need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Common Issues</h2>
<h3>What are the other files that come with the download?</h3>
<p>
Inside the folder "contrib" of the download are the following files:
</p>
<ul>
<li>blacklist_table.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Blacklist">blacklist feature</a>.</li>
<li>region_storage.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Regions">region protection feature</a>.</li>
<li>region_storage_update_20110325.sql is for updating your region protection
database (if you're using it) if your database was made before March 25, 2011.</li>
</ul>
<h3>${project.name} doesn't seem to work.</h3>
<p>
Two common mistakes include forgetting to install WorldEdit
(${project.name} needs it), or making
a syntax error in one of ${project.name}'s configuration files (this is very
fatal unfortunately, and can be caused by a single character typed in the wrong place). Try
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">asking in IRC</a>
to see whether anyone can help you.
</p>
<h3>How do I protect my spawn, or another area?</h3>
<p>
Read the <a href="http://wiki.sk89q.com/wiki/${project.name}/Regions/Tutorial">area protection tutorial</a>
on our wiki. For more detailed information, be sure to read about
<a href="http://wiki.sk89q.com/wiki/WorldGuard/Regions">region protection on the wiki</a>. Note
that if you can't build in spawn, don't forget that Minecraft comes with its own
limited spawn protection that you have to disable (see below).
</p>
<h3>I or others don't have permission to build.</h3>
<p>
Unless you copied configuration files from an older installation of
${project.name}, your problem is either caused by another plugin, or by not
disabling the built-in spawn protection of the Minecraft server.
</p>
<h3>No one can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'deny' means that
no one can modify the things inside the region.</li>
<li>That you added the player as an owner or member of the region. If you are using
a group (g:groupName), you may have to give the group the permission of
group.groupName for ${project.name} to recognize it.</li>
<li>That you disabled spawn protection. The Minecraft server has an automatic
spawn protection feature where only 'ops' can build in a definable
radius around spawn (by default, it is 16 blocks). If you are on Minecraft
1.4 or newer, edit "spawn-protection" in server.properties; otherwise, modify bukkit.yml
and change the spawn-radius setting.</li>
<li>That it's not another plugin causing you trouble. The error messages of ${project.name} are of
a dark red shade. If the color of the "no permission" message is not
that color, it is not ${project.name}.</li>
</ul>
<h3>Everyone can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'allow' means that
anyone can modify the things inside the region.</li>
<li>That it's not caused by another plugin. If players are getting a dark red
permission denied message, but they can still build, another plugin
is likely causing the conflict.</li>
</ul>
<h3>Where do I report bugs or suggest ideas?</h3>
<p>
Make sure you are using the latest version of ${project.name}, try asking in
IRC first (see "Need help?" above) if it's a problem, and if you think you've
found a bug or have a great suggestion to provide, please
report it to <a href="http://youtrack.sk89q.com/issues/WORLDGUARD">our issue tracker</a>.
</p>
<p>
Still need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Contributing</h2>
<p>
Did you know that ${project.name} is open source? That means that you can
read the code and learn from it, as well as modify it and submit back
changes to help the community!
</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">View the source code</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Development">More information</a></li>
</ul>
</div>
</div>
</body>
</html>
+23 -13
View File
@@ -1,25 +1,35 @@
WorldGuard
![WorldGuard](http://static.sk89q.com/readme/worldguard.png)
==========
WorldGuard protects your Minecraft server. As Minecraft's oldest surviving world protection mod, you know you're in safe hands.
WorldGuard is a toolbox of various functions, useful for multiplayer servers, that lets you:
* Protect your server from a number of problems.
* Block fire spread, lava spread, endermen, and more.
* Flag areas as "no PVP" or "no TNT."
* Assign ownership to areas so only selected individuals can build.
* Use a number of useful commands.
WorldGuard is open source and is available under the GNU General Public License v3.
Compiling
---------
You need to have Maven installed (http://maven.apache.org). Once installed,
simply run:
The project is written for Java 6 and our build process makes use of [Maven](http://maven.apache.org). Detailed compilation information [can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
mvn clean install
Maven will automatically download dependencies for you. Note: For that to work,
be sure to add Maven to your "PATH".
Dependencies are automatically handled by Maven.
Contributing
------------
We happily accept contributions. The best way to do this is to fork WorldGuard
on GitHub, add your changes, and then submit a pull request. We'll look at it,
make comments, and merge it into WorldGuard if everything works out.
We happily accept contributions, especially through pull requests on GitHub. Submissions
must be licensed under the GNU General Public License v3.
By submitting code, you agree to place to license your code under the
GNU General Public License v3.
Please read CONTRIBUTING.md for important guidelines to follow.
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)
@@ -1,24 +1,24 @@
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`world` varchar(32) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
-- Blacklist table for MySQL.
-- You must still configure WorldGuard to use your database.
-- If you do not plan on using a database for logging blacklist events,
-- you do not need to do anything with this file.
CREATE TABLE `blacklist_events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event` varchar(25) NOT NULL,
`world` varchar(32) NOT NULL,
`player` varchar(16) NOT NULL,
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`z` int(11) NOT NULL,
`item` int(11) NOT NULL,
`time` int(11) NOT NULL,
`comment` varchar(255) NULL,
PRIMARY KEY (`id`)
);
-- Required update if you have an older version of the table:
ALTER TABLE `blacklist_events` ADD `comment` VARCHAR( 255 ) NULL
ALTER TABLE `blacklist_events` ADD `world` VARCHAR( 32 ) NOT NULL
+67 -30
View File
@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.5.4</version>
<version>5.7-SNAPSHOT</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
@@ -23,14 +23,14 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<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>
@@ -40,38 +40,54 @@
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4</version>
<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>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.3.2-R1.0</version>
<version>1.4.2-R0.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
<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>
<!-- Additional libraries -->
<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.4</version>
<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>
@@ -79,6 +95,24 @@
<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>
@@ -87,6 +121,7 @@
</site>
</distributionManagement>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions>
@@ -97,7 +132,6 @@
</extension>
</extensions>
<!-- Resources -->
<resources>
<resource>
<targetPath>.</targetPath>
@@ -112,15 +146,23 @@
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<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>
<!-- Compile plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -130,8 +172,7 @@
<target>1.6</target>
</configuration>
</plugin>
<!-- JAR creation plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
@@ -149,9 +190,7 @@
</archive>
</configuration>
</plugin>
<!-- Shade -->
<!-- We want to bundle in some dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
@@ -164,17 +203,17 @@
</goals>
<configuration>
<artifactSet>
<!-- We want to bundle in the modified CSV library -->
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
<include>com.sk89q:rebar</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
@@ -191,8 +230,7 @@
</execution>
</executions>
</plugin>
<!-- Release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
@@ -204,7 +242,6 @@
</configuration>
</plugin>
<!-- Site generation -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
+4 -2
View File
@@ -3,6 +3,7 @@
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>
@@ -28,8 +29,9 @@
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>blacklist_table.sql</include>
<include>region_storage.sql</include>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_storage.sql</include>
<include>contrib/region_storage_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
@@ -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 {
}
@@ -82,11 +82,9 @@ public abstract class LocalPlayer {
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LocalPlayer)) {
return false;
}
return ((LocalPlayer)obj).getName().equals(getName());
return obj instanceof LocalPlayer && ((LocalPlayer) obj).getName().equals(getName());
}
@Override
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.blacklist;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -105,9 +106,7 @@ public class BlacklistEntry {
*/
public void setIgnorePermissions(String[] ignorePermissions) {
Set<String> ignorePermissionsSet = new HashSet<String>();
for (String perm : ignorePermissions) {
ignorePermissionsSet.add(perm);
}
Collections.addAll(ignorePermissionsSet, ignorePermissions);
this.ignorePermissions = ignorePermissionsSet;
}
@@ -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;
}
}
@@ -19,29 +19,20 @@
package com.sk89q.worldguard.bukkit;
import java.util.List;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.FallingSand;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import java.util.List;
public class BukkitUtil {
@@ -140,20 +131,16 @@ public class BukkitUtil {
/**
* Checks if the given block is water
*
* @param world
* @param ox
* @param oy
* @param oz
* @return
* @param world the world
* @param ox x
* @param oy y
* @param oz z
* @return true if it's water
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
return true;
} else {
return false;
}
return id == 8 || id == 9;
}
/**
@@ -239,18 +226,50 @@ public class BukkitUtil {
}
/**
* Returns whether an entity should be removed for the halt activity mode.
* Returns whether our running CraftBukkit already supports
* the HangingEvent instead of the PaintingEvent
*
* @param entity
* @return
* @return true if the hanging event is supported
*/
public static boolean isIntensiveEntity(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingSand
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
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);
}
}
@@ -26,94 +26,70 @@ 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.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.World;
import org.bukkit.entity.Player;
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.
*
* @author sk89q
* @author Michael
*/
public class ConfigurationManager {
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace most settings in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" +
"# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
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);
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Holds configurations for different worlds.
*/
private ConcurrentMap<String, WorldConfiguration> worlds;
private YamlConfigurationFile config;
/**
* The global configuration for use when loading worlds
*/
private YAMLProcessor 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>();
/**
* List of people with god mode.
*/
@Deprecated
private Set<String> hasGodMode = new HashSet<String>();
/**
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
/* Configuration data start */
public boolean useRegionsScheduler;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
public boolean useSqlDatabase = false;
public String sqlDsn;
public String sqlUsername;
public String sqlPassword;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin The plugin instance
* @param plugin the plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -123,60 +99,66 @@ public class ConfigurationManager {
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
plugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
loadConfig();
config = new YAMLProcessor(new File(plugin.getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for global config: ");
e.printStackTrace();
}
config.removeProperty("suppress-tick-sync-warnings");
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
useRegionsCreatureSpawnEvent = config.getBoolean(
"regions.use-creature-spawn-event", true);
autoGodMode = config.getBoolean(
"auto-invincible", config.getBoolean("auto-invincible-permission", false));
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
hostKeys = new HashMap<String, String>();
Object hostKeysRaw = config.getProperty("host-keys");
if (hostKeysRaw == null || !(hostKeysRaw instanceof Map)) {
config.setProperty("host-keys", new HashMap<String, String>());
} else {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
hostKeys.put(key.toLowerCase(), value);
}
}
useSqlDatabase = config.getBoolean(
"regions.sql.use", false);
// 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);
}
config.setHeader(CONFIG_HEADER);
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
}
saveConfig();
}
/**
@@ -186,6 +168,41 @@ public class ConfigurationManager {
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.
*
@@ -199,7 +216,7 @@ public class ConfigurationManager {
while (config == null) {
if (newConfig == null) {
newConfig = new WorldConfiguration(plugin, worldName, this.config);
newConfig = new WorldConfiguration(plugin, worldName, this, this.config);
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
@@ -208,12 +225,91 @@ public class ConfigurationManager {
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
*/
public void forgetPlayer(LocalPlayer player) {
void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
@@ -235,7 +331,6 @@ public class ConfigurationManager {
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
@@ -293,7 +388,10 @@ public class ConfigurationManager {
return hasAmphibious.contains(player.getName());
}
public void updateCommandBookGodMode() {
/**
* Check and store whether CommandBook is installed.
*/
void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
@@ -304,7 +402,12 @@ public class ConfigurationManager {
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
/**
* Return whether CommandBook is available for God mode usage.
*
* @return true if it available
*/
boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -17,7 +17,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.events;
package com.sk89q.worldguard.bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
@@ -1,236 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* This processes per-player state information and is also meant to be used
* as a scheduled task.
*
* @author sk89q
*/
public class FlagStateManager implements Runnable {
public static final int RUN_DELAY = 20;
private WorldGuardPlugin plugin;
private Map<String, PlayerFlagState> states;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public FlagStateManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
states = new HashMap<String, PlayerFlagState>();
}
/**
* Run the task.
*/
public void run() {
Player[] players = plugin.getServer().getOnlinePlayers();
ConfigurationManager config = plugin.getGlobalStateManager();
for (Player player : players) {
WorldConfiguration worldConfig = config.get(player.getWorld());
if (!worldConfig.useRegions) {
continue;
}
PlayerFlagState state;
synchronized (this) {
state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
}
Vector playerLocation = toVector(player.getLocation());
RegionManager regionManager = plugin.getGlobalRegionManager()
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
&& !(player.getGameMode() == GameMode.CREATIVE)) {
processHeal(applicable, player, state);
processFeed(applicable, player, state);
}
}
}
/**
* Process healing for a player.
*
* @param applicable The set of applicable regions
* @param player The player to process healing flags on
* @param state The player's state
*/
private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (minHealth == null) minHealth = 0;
if (maxHealth == null) maxHealth = 20;
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
// clamp health between minimum and maximum
player.setHealth(Math.min(maxHealth, Math.max(minHealth, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
/**
* Process restoring hunger for a player.
*
* @param applicable The set of applicable regions
* @param player The player to process hunger flags on
* @param state The player's state
*/
private void processFeed(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
long now = System.currentTimeMillis();
Integer feedAmount = applicable.getFlag(DefaultFlag.FEED_AMOUNT);
Integer feedDelay = applicable.getFlag(DefaultFlag.FEED_DELAY);
Integer minHunger = applicable.getFlag(DefaultFlag.MIN_FOOD);
Integer maxHunger = applicable.getFlag(DefaultFlag.MAX_FOOD);
if (feedAmount == null || feedDelay == null || feedAmount == 0 || feedDelay < 0) {
return;
}
if (minHunger == null) minHunger = 0;
if (maxHunger == null) maxHunger = 20;
if (player.getFoodLevel() >= maxHunger && feedAmount > 0) {
return;
}
if (feedDelay <= 0) {
player.setFoodLevel(feedAmount > 0 ? maxHunger : minHunger);
state.lastFeed = now;
} else if (now - state.lastFeed > feedDelay * 1000) {
// clamp health between minimum and maximum
player.setFoodLevel(Math.min(maxHunger, Math.max(minHunger, player.getFoodLevel() + feedAmount)));
state.lastFeed = now;
}
}
/**
* Forget a player.
*
* @param player The player to forget
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
}
/**
* Forget all managed players. Use with caution.
*/
public synchronized void forgetAll() {
states.clear();
}
/**
* Get a player's flag state. A new state will be created if there is no existing
* state for the player.
*
* @param player The player to get a state for
* @return The {@code player}'s state
*/
public synchronized PlayerFlagState getState(Player player) {
PlayerFlagState state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
return state;
}
/**
* Keeps state per player.
*/
public static class PlayerFlagState {
public long lastHeal;
public long lastFeed;
public String lastGreeting;
public String lastFarewell;
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public GameMode lastGameMode;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
public int lastBlockZ;
/* Used to cache invincibility status */
public World lastInvincibleWorld;
public int lastInvincibleX;
public int lastInvincibleY;
public int lastInvincibleZ;
public boolean wasInvincible;
}
}
@@ -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());
}
}
}
@@ -1,154 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.CSVDatabase;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Utility methods for porting from legacy versions.
*
* @author sk89q
*/
public class LegacyWorldGuardMigration {
/**
* Port over the blacklist.
*
* @param plugin The plugin instance
*/
public static void migrateBlacklist(WorldGuardPlugin plugin) {
World mainWorld = plugin.getServer().getWorlds().get(0);
String mainWorldName = mainWorld.getName();
String newPath = "worlds/" + mainWorldName + "/blacklist.txt";
File oldFile = new File(plugin.getDataFolder(), "blacklist.txt");
File newFile = new File(plugin.getDataFolder(), newPath);
if (!newFile.exists() && oldFile.exists()) {
plugin.getLogger().warning("WorldGuard will now update your blacklist "
+ "from an older version of WorldGuard.");
// Need to make root directories
newFile.getParentFile().mkdirs();
if (copyFile(oldFile, newFile)) {
oldFile.renameTo(new File(plugin.getDataFolder(),
"blacklist.txt.old"));
} else {
plugin.getLogger().warning("blacklist.txt has been converted " +
"for the main world at " + newPath + "");
plugin.getLogger().warning("Your other worlds currently have no " +
"blacklist defined!");
}
}
}
/**
* Migrate region settings.
*
* @param plugin The plugin instance
*/
public static void migrateRegions(WorldGuardPlugin plugin) {
try {
File oldDatabase = new File(plugin.getDataFolder(), "regions.txt");
if (!oldDatabase.exists()) return;
plugin.getLogger().info("The regions database has changed in 5.x. "
+ "Your old regions database will be converted to the new format "
+ "and set as your primary world's database.");
World w = plugin.getServer().getWorlds().get(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
// First load up the old database using the CSV loader
CSVDatabase db = new CSVDatabase(oldDatabase, plugin.getLogger());
db.load();
// Then save the new database
mgr.setRegions(db.getRegions());
mgr.save();
oldDatabase.renameTo(new File(plugin.getDataFolder(), "regions.txt.old"));
plugin.getLogger().info("Regions database converted!");
} catch (ProtectionDatabaseException e) {
plugin.getLogger().warning("Failed to load regions: "
+ e.getMessage());
}
}
/**
* Copies a file.
*
* @param from The source file
* @param to The destination file
* @return true if successful
*/
private static boolean copyFile(File from, File to) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (FileNotFoundException ignore) {
} catch (IOException ignore) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException ignore) {
}
}
}
return false;
}
}
@@ -20,6 +20,7 @@
package com.sk89q.worldguard.bukkit;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
@@ -27,8 +28,6 @@ import org.bukkit.command.CommandSender;
/**
* Sends all logger messages to a player.
*
* @author sk89q
*/
public class LoggerToChatHandler extends Handler {
/**
@@ -64,7 +63,12 @@ public class LoggerToChatHandler extends Handler {
*/
@Override
public void publish(LogRecord record) {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.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));
}
}
@@ -1,83 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
public class RegionQueryUtil {
public static boolean isInvincible(WorldGuardPlugin plugin, Player player) {
return isInvincible(plugin, player, null);
}
public static boolean isInvincible(WorldGuardPlugin plugin, Player player,
ApplicableRegionSet set) {
Location loc = player.getLocation();
World world = player.getWorld();
FlagStateManager.PlayerFlagState state = plugin.getFlagStateManager().getState(player);
if (state.lastInvincibleWorld == null ||
!state.lastInvincibleWorld.equals(world) ||
state.lastInvincibleX != loc.getBlockX() ||
state.lastInvincibleY != loc.getBlockY() ||
state.lastInvincibleZ != loc.getBlockZ()) {
state.lastInvincibleX = loc.getBlockX();
state.lastInvincibleY = loc.getBlockY();
state.lastInvincibleZ = loc.getBlockZ();
state.lastInvincibleWorld = world;
if (set == null) {
Vector vec = new Vector(state.lastInvincibleX,
state.lastInvincibleY, state.lastInvincibleZ);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
set = mgr.getApplicableRegions(vec);
}
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
}
return state.wasInvincible;
}
public static Boolean isAllowedInvinciblity(WorldGuardPlugin plugin, Player player) {
World world = player.getWorld();
FlagStateManager.PlayerFlagState state = plugin.getFlagStateManager().getState(player);
Vector vec = new Vector(state.lastInvincibleX, state.lastInvincibleY, state.lastInvincibleZ);
StateFlag.State regionState = plugin.getGlobalRegionManager().get(world).
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
if (regionState == StateFlag.State.ALLOW) {
return Boolean.TRUE;
} else if (regionState == StateFlag.State.DENY) {
return Boolean.FALSE;
} else {
return null;
}
}
}
@@ -35,22 +35,17 @@ import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.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());
@@ -63,38 +58,38 @@ public class ReportWriter {
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);
@@ -104,7 +99,7 @@ public class ReportWriter {
output.append("\r\n");
appendln();
}
private void appendReportHeader(WorldGuardPlugin plugin) {
appendln("WorldGuard Configuration Report");
appendln("Generated " + dateFmt.format(date));
@@ -112,13 +107,13 @@ public class ReportWriter {
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 {
@@ -130,16 +125,16 @@ public class ReportWriter {
} 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)",
@@ -164,23 +159,23 @@ public class ReportWriter {
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())
@@ -191,20 +186,20 @@ public class ReportWriter {
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());
@@ -212,21 +207,21 @@ public class ReportWriter {
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()) {
@@ -235,18 +230,18 @@ public class ReportWriter {
entry.getValue(),
(float) (entry.getValue() / (double) loadedChunkCount));
}
i++;
}
append(log);
appendln();
}
private void appendWorldConfigurations(WorldGuardPlugin plugin, List<World> worlds,
GlobalRegionManager regionMgr, ConfigurationManager mgr) {
RegionManager regionMgr, ConfigurationManager mgr) {
appendHeader("World Configurations");
LogListBlock log = new LogListBlock();
int i = 0;
@@ -264,9 +259,9 @@ public class ReportWriter {
+ 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 {
@@ -277,7 +272,7 @@ public class ReportWriter {
} catch (IllegalAccessException ignore) {
}
}
if (config.getBlacklist() == null) {
blacklistLog.put("State", "DISABLED");
} else {
@@ -288,13 +283,13 @@ public class ReportWriter {
config.getBlacklist().isWhitelist());
}
RegionManager worldRegions = regionMgr.get(world);
/*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");
ProtectedRegion globalRegion = worldRegions.getRegion("__global__");
Region globalRegion = worldRegions.getRegion("__global__");
if (globalRegion == null) {
globalRegionLog.put("Status", "UNDEFINED");
} else {
@@ -304,17 +299,17 @@ public class ReportWriter {
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);
@@ -329,7 +324,7 @@ public class ReportWriter {
}
}
}
@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);
}
}
}
}
}
@@ -1,126 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.isBlockWater;
import static com.sk89q.worldguard.bukkit.BukkitUtil.setBlockToWater;
import org.bukkit.World;
public class SpongeUtil {
/**
* Remove water around a sponge.
*
* @param plugin The plugin instace
* @param world The world the sponge isin
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void clearSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water around a sponge.
*
* @param plugin The plugin instance
* @param world The world the sponge is located in
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void addSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// The negative x edge
int cx = ox - wcfg.spongeRadius - 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx + 1, cy, cz);
}
}
}
// The positive x edge
cx = ox + wcfg.spongeRadius + 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx - 1, cy, cz);
}
}
}
// The negative y edge
int cy = oy - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy + 1, cz);
}
}
}
// The positive y edge
cy = oy + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy - 1, cz);
}
}
}
// The negative z edge
int cz = oz - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz + 1);
}
}
}
// The positive z edge
cz = oz + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz - 1);
}
}
}
}
}
@@ -23,517 +23,349 @@ 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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
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;
import com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.chest.SignChestProtection;
/**
* Holds the configuration for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class WorldConfiguration {
public static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's world configuration file\r\n" +
"#\r\n" +
"# This is a world configuration file. Anything placed into here will only\r\n" +
"# affect this world. If you don't put anything in this file, then the\r\n" +
"# settings will be inherited from the main configuration file.\r\n" +
"#\r\n" +
"# If you see {} below, that means that there are NO entries in this file.\r\n" +
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private static Logger logger = LoggerUtils.getLogger(WorldConfiguration.class, "[WorldGuard] ");
private WorldGuardPlugin plugin;
private String worldName;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File blacklistFile;
private final WorldGuardPlugin plugin;
private final ConfigurationManager configMan;
private final YamlConfigurationFile config;
private final String worldName;
private Blacklist blacklist;
private ChestProtection chestProtection = new SignChestProtection();
private RuleList ruleList = new RuleList();
private SpongeApplicator spongeApplicator = null;
/* Configuration data start */
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean itemDurability;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockLighter;
public boolean disableFireSpread;
public Set<Integer> disableFireSpreadBlocks;
public boolean preventLavaFire;
public Set<Integer> allowedLavaSpreadOver;
public boolean blockTNTExplosions;
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public boolean blockEnderDragonBlockDamage;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockEntityPaintingDestroy;
public boolean blockPluginSpawning;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
public boolean disableFireDamage;
public boolean disableLightningDamage;
public boolean disableDrowningDamage;
public boolean disableSuffocationDamage;
public boolean teleportOnSuffocation;
public boolean disableVoidDamage;
public boolean teleportOnVoid;
public boolean disableExplosionDamage;
public boolean disableMobDamage;
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand = 287;
public Set<EntityType> blockCreatureSpawn;
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 antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
public boolean preventLightningFire;
public Set<Integer> disallowedLightningBlocks;
public boolean disableThunder;
public boolean disableWeather;
public boolean alwaysRaining;
public boolean alwaysThundering;
public boolean disablePigZap;
public boolean disableCreeperPower;
public boolean disableHealthRegain;
public boolean disableMushroomSpread;
public boolean disableIceMelting;
public boolean disableSnowMelting;
public boolean disableSnowFormation;
public boolean disableIceFormation;
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableEndermanGriefing;
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
public boolean fireSpreadDisableToggle;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin The WorldGuardPlugin instance
* @param worldName The world name that this WorldConfiguration is for.
* @param parentConfig The parent configuration to read defaults from
* @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, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
File configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
public WorldConfiguration(WorldGuardPlugin plugin, String worldName,
ConfigurationManager configMan, ConfigurationNode parentConfig) {
this.plugin = plugin;
this.worldName = worldName;
this.parentConfig = parentConfig;
this.configMan = configMan;
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
File file = configMan.getWorldConfigFile(worldName);
config = new YamlConfigurationFile(file, ConfigurationManager.YAML_STYLE);
config.setParent(parentConfig);
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
}
private boolean getBoolean(String node, boolean def) {
boolean val = parentConfig.getBoolean(node, def);
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return val;
}
}
private String getString(String node, String def) {
String val = parentConfig.getString(node, def);
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return val;
}
}
private int getInt(String node, int def) {
int val = parentConfig.getInt(node, def);
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return val;
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return val;
}
}
private List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res = parentConfig.getIntList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
}
return res;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res = parentConfig.getStringList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
}
return res;
}
private List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
private Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
load();
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
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) {
plugin.getLogger().severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
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);
}
opPermissions = getBoolean("op-permissions", true);
signChestProtection = config.getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = config.getBoolean("chest-protection.disable-off-check", false);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", 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);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
pumpkinScuba = getBoolean("default.pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
noPhysicsGravel = getBoolean("physics.no-physics-gravel", false);
noPhysicsSand = getBoolean("physics.no-physics-sand", false);
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
blockTNTExplosions = getBoolean("ignition.block-tnt", false);
blockTNTBlockDamage = getBoolean("ignition.block-tnt-block-damage", false);
blockLighter = getBoolean("ignition.block-lighter", false);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", true);
disableFireSpread = getBoolean("fire.disable-all-fire-spread", false);
disableFireSpreadBlocks = new HashSet<Integer>(getIntList("fire.disable-fire-spread-blocks", null));
allowedLavaSpreadOver = new HashSet<Integer>(getIntList("fire.lava-spread-blocks", null));
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
disableFireDamage = getBoolean("player-damage.disable-fire-damage", false);
disableLightningDamage = getBoolean("player-damage.disable-lightning-damage", false);
disableDrowningDamage = getBoolean("player-damage.disable-drowning-damage", false);
disableSuffocationDamage = getBoolean("player-damage.disable-suffocation-damage", false);
disableContactDamage = getBoolean("player-damage.disable-contact-damage", false);
teleportOnSuffocation = getBoolean("player-damage.teleport-on-suffocation", false);
disableVoidDamage = getBoolean("player-damage.disable-void-damage", false);
teleportOnVoid = getBoolean("player-damage.teleport-on-void-falling", false);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
disableDeathMessages = getBoolean("player-damage.disable-death-messages", false);
signChestProtection = getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", false);
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<Integer>(getIntList("weather.prevent-lightning-strike-blocks", null));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
disableWeather = getBoolean("weather.disable-weather", false);
disablePigZap = getBoolean("weather.disable-pig-zombification", false);
disableCreeperPower = getBoolean("weather.disable-powered-creepers", false);
alwaysRaining = getBoolean("weather.always-raining", false);
alwaysThundering = getBoolean("weather.always-thundering", false);
disableMushroomSpread = getBoolean("dynamics.disable-mushroom-spread", false);
disableIceMelting = getBoolean("dynamics.disable-ice-melting", false);
disableSnowMelting = getBoolean("dynamics.disable-snow-melting", false);
disableSnowFormation = getBoolean("dynamics.disable-snow-formation", false);
disableIceFormation = getBoolean("dynamics.disable-ice-formation", false);
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
regionWand = getInt("regions.wand", 287);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCountPerPlayer = config.getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
for (String key : config.getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
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);
blockCreatureSpawn = new HashSet<EntityType>();
for (String creatureName : getStringList("mobs.block-creature-spawn", null)) {
EntityType creature = EntityType.fromName(creatureName);
if (creature == null) {
plugin.getLogger().warning("Unknown mob type '" + creatureName + "'");
} else if (!creature.isAlive()) {
plugin.getLogger().warning("Entity type '" + creatureName + "' is not a creature");
} else {
blockCreatureSpawn.add(creature);
}
}
boolean useBlacklistAsWhitelist = getBoolean("blacklist.use-as-whitelist", false);
// Console log configuration
boolean logConsole = getBoolean("blacklist.logging.console.enable", true);
// Database log configuration
boolean logDatabase = getBoolean("blacklist.logging.database.enable", false);
String dsn = getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = getString("blacklist.logging.database.user", "root");
String pass = getString("blacklist.logging.database.pass", "");
String table = getString("blacklist.logging.database.table", "blacklist_events");
// File log configuration
boolean logFile = getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, getInt("blacklist.logging.file.open-files", 10));
// Load the blacklist
try {
// If there was an existing blacklist, close loggers
if (blacklist != null) {
blacklist.getLogger().close();
}
// First load the blacklist data from worldguard-blacklist.txt
Blacklist blist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
blist.load(blacklistFile);
// If the blacklist is empty, then set the field to null
// and save some resources
if (blist.isEmpty()) {
this.blacklist = null;
} else {
this.blacklist = blist;
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
BlacklistLogger blacklistLogger = blist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName, plugin.getLogger()));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName, plugin.getLogger()));
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger());
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist.");
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: "
+ e.getMessage());
}
// Print an overview of settings
if (getBoolean("summary-on-start", true)) {
plugin.getLogger().log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockLighter
? "(" + worldName + ") Lighters are blocked."
: "(" + worldName + ") Lighters are PERMITTED.");
plugin.getLogger().log(Level.INFO, preventLavaFire
? "(" + worldName + ") Lava fire is blocked."
: "(" + worldName + ") Lava fire is PERMITTED.");
if (disableFireSpread) {
plugin.getLogger().log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
}
config.setHeader(CONFIG_HEADER);
config.save();
}
public Blacklist getBlacklist() {
return this.blacklist;
/**
* 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;
}
public boolean isChestProtected(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtected(block, player);
}
public boolean isChestProtected(Block block) {
if (!signChestProtection) {
return false;
}
return chestProtection.isProtected(block, null);
}
public boolean isChestProtectedPlacement(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtectedPlacement(block, player);
}
public boolean isAdjacentChestProtected(Block block, Player player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isAdjacentChestProtected(block, player);
}
public ChestProtection getChestProtection() {
return chestProtection;
}
/**
* 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)) {
@@ -547,4 +379,56 @@ public class WorldConfiguration {
}
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;
}
}
@@ -16,14 +16,14 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.Location;
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;
@@ -31,548 +31,310 @@ 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.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
* Construct the listener.
*
* @param plugin The plugin instance
* @param plugin WorldGuard plugin
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
* Register the events.
*/
public void registerEvents() {
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
/*
* Called when a block is damaged.
*/
@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) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockDamaged)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
// 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;
}
}
}
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getTypeId() > 0
&& !(ItemType.usesDamageValue(held.getTypeId())
|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) -1);
player.setItemInHand(held);
}
}
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())
|| !plugin.getGlobalRegionManager().canConstruct(player, event.getBlock())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
event.getBlock().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
if (!wcfg.getBlacklist().check(
new DestroyWithBlacklistEvent(plugin.wrapPlayer(player),
toVector(event.getBlock()),
player.getItemInHand().getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
return;
}
}
/*
* Called when fluids flow.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
boolean isAir = blockFrom.getTypeId() == 0;
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// 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;
}
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
/* --- No short-circuit returns below this line --- */
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
}
}
}
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
}
}
}
/*if (plugin.classicWater && isWater) {
int blockBelow = blockFrom.getRelative(0, -1, 0).getTypeId();
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
blockFrom.setTypeId(9);
if (blockTo.getTypeId() == 0) {
blockTo.setTypeId(9);
}
return;
}
}*/
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
// Check the fluid block (from) whether it is air.
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
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;
}
}
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.highFreqFlags && isWater
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.WATER_FLOW,
blockFrom.getLocation())) {
// 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;
}
if (wcfg.highFreqFlags && isLava
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.LAVA_FLOW,
blockFrom.getLocation())) {
event.setCancelled(true);
return;
}
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& blockTo.getTypeId() == 55) {
blockTo.setTypeId(0);
return;
}
}
/*
* Called when a block gets ignited.
*/
@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);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
// RuleLists
RuleSet rules;
BukkitContext context;
BlockState placedState;
if (wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
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());
if (wcfg.useRegions) {
Vector pt = toVector(block);
Player player = event.getPlayer();
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
// Make a virtual source state
BlockState sourceState = event.getBlock().getState();
sourceState.setType(event.getCause() == IgniteCause.LAVA ? Material.LAVA : Material.FIRE);
context.setSourceBlock(sourceState);
if (player != null && !plugin.getGlobalRegionManager().hasBypass(player, world)) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL) {
if (!set.canBuild(localPlayer)) {
event.setCancelled(true);
return;
}
if (!set.allows(DefaultFlag.LIGHTER, localPlayer)
&& !plugin.hasPermission(player, "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
}
}
if (wcfg.highFreqFlags && isFireSpread
&& !set.allows(DefaultFlag.FIRE_SPREAD)) {
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());
if (wcfg.highFreqFlags && cause == IgniteCause.LAVA
&& !set.allows(DefaultFlag.LAVA_FIRE)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
// 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;
}
}
/*
* Called when a block is destroyed from burning.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
BukkitUtil.checkAndDestroyAround(block.getWorld(), block.getX(),
block.getY(), block.getZ(), BlockID.FIRE);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
if (wcfg.isChestProtected(event.getBlock())) {
// 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;
}
if (wcfg.useRegions) {
Block block = event.getBlock();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
Vector pt = toVector(block);
RegionManager mgr = plugin.getGlobalRegionManager().get(block.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, BlockID.FIRE);
event.setCancelled(true);
return;
}
}
}
private void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
private void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
}
}
/*
* Called when block physics occurs.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// 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;
}
int id = event.getChangedTypeId();
/* --- No short-circuit returns below this line --- */
if (id == 13 && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
} else {
spongeAppl.clearWater(block);
}
}
}
/*
* Called when a player places a block.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
final Location location = blockPlaced.getLocation();
if (!plugin.getGlobalRegionManager().canBuild(player, location)
|| !plugin.getGlobalRegionManager().canConstruct(player, location)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && spongeAppl.isActiveSponge(blockPlaced)) {
spongeAppl.clearWater(blockPlaced);
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(blockPlaced),
blockPlaced.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getTypeId())) {
if (wcfg.isAdjacentChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
event.setCancelled(true);
return;
}
}
if (wcfg.simulateSponge && blockPlaced.getTypeId() == 19) {
if (wcfg.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
return;
}
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
SpongeUtil.clearSpongeWater(plugin, world, ox, oy, oz);
}
}
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -1; cx <= 1; cx++) {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
}
}
}
}
// 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;
}
}
/*
* Called when a sign is changed.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
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 (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
@@ -617,12 +379,6 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -630,176 +386,78 @@ public class WorldGuardBlockListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// 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;
}
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY,
event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
}
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// 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;
}
int type = event.getNewState().getTypeId();
if (type == BlockID.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_FORM, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (type == BlockID.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_FALL, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// 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;
}
int fromType = event.getSource().getTypeId();
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.MUSHROOMS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.GRASS) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.GRASS_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
int type = event.getBlock().getTypeId();
if (type == BlockID.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (type == BlockID.SNOW) {
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
// 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;
}
}
/*
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
for (Block block : event.getBlocks()) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, block.getLocation())) {
event.setCancelled(true);
return;
}
}
}
}
/*
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.useRegions && event.isSticky()) {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
// 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;
}
}
}
@@ -1,75 +0,0 @@
/*
* WorldGuard
* Copyright (C) 2012 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.InfoComponent;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
/**
* @author zml2008
*/
public class WorldGuardCommandBookListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardCommandBookListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerWhois(InfoComponent.PlayerWhoisEvent event) {
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (plugin.getGlobalStateManager().get(player.getWorld()).useRegions) {
ApplicableRegionSet regions = plugin.getGlobalRegionManager()
.get(player.getWorld()).getApplicableRegions(player.getLocation());
// Current regions
StringBuilder regionStr = new StringBuilder();
boolean first = true;
for (ProtectedRegion region : regions) {
if (!first) {
regionStr.append(", ");
}
if (region.isOwner(localPlayer)) {
regionStr.append("+");
} else if (region.isMemberOnly(localPlayer)) {
regionStr.append("-");
}
regionStr.append(region.getId());
first = false;
}
if (regions.size() > 0) {
event.addWhoisInformation("Current Regions", regionStr);
}
event.addWhoisInformation("Can build", regions.canBuild(localPlayer));
}
}
}
}
@@ -18,33 +18,15 @@
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Set;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import org.bukkit.ChatColor;
import java.util.Iterator;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -55,399 +37,121 @@ 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.EntityRegainHealthEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldguard.region.RegionManager;
import com.sk89q.worldguard.region.flags.DefaultFlag;
/**
* Listener for entity related events.
*
* @author sk89q
* The listener for entity events.
*/
public class WorldGuardEntityListener implements Listener {
class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
* Construct the listener.
*
* @param plugin The plugin instance
* @param plugin WorldGuard plugin
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
* Register the events.
*/
public void registerEvents() {
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (block.getTypeId() == BlockID.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
// 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) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
if (wcfg.disableExpDrops || !plugin.getGlobalRegionManager().allows(DefaultFlag.EXP_DROPS,
event.getEntity().getLocation())) {
event.setDroppedExp(0);
}
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
}
}
private void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
/* --- No short-circuit returns below this line --- */
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.ENTITY_DEATH);
BukkitContext context = new BukkitContext(plugin, event);
context.setTargetEntity(event.getEntity());
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
player.setFireTicks(0);
return;
}
if (wcfg.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
if (wcfg.teleportOnVoid && type == DamageCause.VOID) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableVoidDamage && type == DamageCause.VOID) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && type == DamageCause.BLOCK_EXPLOSION) {
event.setCancelled(true);
return;
}
}
}
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getCause() == DamageCause.PROJECTILE) {
onEntityDamageByProjectile(event);
return;
// Set a message if it's a death from a player
if (event instanceof PlayerDeathEvent) {
context.setMessage(((PlayerDeathEvent) event).getDeathMessage());
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
rules.process(context);
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
// Set the message back
if (event instanceof PlayerDeathEvent) {
((PlayerDeathEvent) event).setDeathMessage(context.getMessage());
}
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
if (wcfg.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
event.setCancelled(true);
return;
}
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.ENTITY_EXPLOSION) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof TNTPrimed) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Fireball) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
private void onEntityDamageByProjectile(EntityDamageByEntityEvent event) {
Entity defender = event.getEntity();
Entity attacker = ((Projectile) event.getDamager()).getShooter();
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof Skeleton) {
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof EntityDamageByEntityEvent) {
this.onEntityDamageByEntity((EntityDamageByEntityEvent) event);
return;
} else if (event instanceof EntityDamageByBlockEvent) {
this.onEntityDamageByBlock((EntityDamageByBlockEvent) event);
return;
}
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (isInvincible(player)) {
event.setCancelled(true);
player.setFireTicks(0);
return;
}
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(player)) {
player.setRemainingAir(player.getMaximumAir());
// 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;
}
ItemStack helmet = player.getInventory().getHelmet();
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& helmet != null
&& (helmet.getTypeId() == BlockID.PUMPKIN
|| helmet.getTypeId() == BlockID.JACKOLANTERN)) {
player.setRemainingAir(player.getMaximumAir());
// 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;
}
if (wcfg.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (wcfg.disableDrowningDamage && type == DamageCause.DROWNING) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
// 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;
}
@@ -461,185 +165,78 @@ public class WorldGuardEntityListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (entity instanceof Player) {
Player player = (Player) entity;
if (cfg.hasGodMode(player) || (wcfg.useRegions && RegionQueryUtil.isInvincible(plugin, player))) {
event.setCancelled(true);
return;
}
// 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;
}
}
/*
* Called on entity explode.
*/
@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);
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
ent.remove();
// 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;
}
if (ent instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage) {
event.blockList().clear();
return;
}
/* --- No short-circuit returns below this line --- */
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
// Now apply RuleLists for each block
Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
Block block = iter.next();
if (wcfg.useRegions) {
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof EnderDragon) {
if (wcfg.blockEnderDragonBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE)) {
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof TNTPrimed) {
if (wcfg.blockTNTBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.TNT)) {
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof Fireball) {
if (wcfg.blockFireballBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.GHAST_FIREBALL)) {
event.blockList().clear();
return;
}
}
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();
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
event.blockList().clear();
return;
}
}
}
}
/*
* Called on explosion prime
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Entity ent = event.getEntity();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (cfg.activityHaltToggle) {
ent.remove();
// 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();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM)
return;
EntityType entityType = event.getEntityType();
if (wcfg.blockCreatureSpawn.contains(entityType)) {
// 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;
}
Location eventLoc = event.getLocation();
if (wcfg.useRegions && cfg.useRegionsCreatureSpawnEvent) {
Vector pt = toVector(eventLoc);
RegionManager mgr = plugin.getGlobalRegionManager().get(eventLoc.getWorld());
// @TODO get victims' stacktraces and find out why it's null anyway
if (mgr == null) return;
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_SPAWNING)) {
event.setCancelled(true);
return;
}
Set<EntityType> entityTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (entityTypes != null && entityTypes.contains(entityType)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -647,8 +244,13 @@ public class WorldGuardEntityListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disablePigZap) {
// 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;
}
}
@@ -657,226 +259,56 @@ public class WorldGuardEntityListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event.getRemover() instanceof Player) {
Player player = (Player) event.getRemover();
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (event.getRemover() instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.blockEntityPaintingDestroy) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.disableHealthRegain) {
// 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;
}
}
/**
* Called when an enderman picks up or puts down a block and some other cases.
*
* @param event Relevant event details
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEndermanPickup(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity entity = event.getEntity();
if (ent instanceof Enderman) {
if (event.getTo() == Material.AIR) {
// pickup
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
} else {
// place
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
event.setCancelled(true);
}
// 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) {
GlobalRegionManager global = plugin.getGlobalRegionManager();
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)) {
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);
}
}
/**
* Check if a player is invincible, via either god mode or region flag. If
* the region denies invincibility, the player must have an extra permission
* to override it. (worldguard.god.override-regions)
*
* @param player The player to check
* @return Whether {@code player} is invincible
*/
private boolean isInvincible(Player player) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
boolean god = cfg.hasGodMode(player);
if (wcfg.useRegions) {
Boolean flag = RegionQueryUtil.isAllowedInvinciblity(plugin, player);
boolean allowed = flag == null || flag;
boolean invincible = RegionQueryUtil.isInvincible(plugin, player);
if (allowed) {
return god || invincible;
} else {
return (god && plugin.hasPermission(player, "worldguard.god.override-regions"))
|| invincible;
}
} else {
return god;
}
}
/**
* Using a DisallowedPVPEvent, notifies other plugins that WorldGuard
* wants to cancel a PvP damage event.<br />
* If this event is not cancelled, the attacking player is notified that
* PvP is disabled and WorldGuard cancels the damage event.
*
* @param attackingPlayer The attacker
* @param defendingPlayer The defender
* @param event The event that caused WorldGuard to act
*/
public void tryCancelPVPEvent(final Player attackingPlayer, final Player defendingPlayer, EntityDamageByEntityEvent event) {
final DisallowedPVPEvent disallowedPVPEvent = new DisallowedPVPEvent(attackingPlayer, defendingPlayer, event);
plugin.getServer().getPluginManager().callEvent(disallowedPVPEvent);
if (!disallowedPVPEvent.isCancelled()) {
attackingPlayer.sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
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;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -19,8 +19,9 @@
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.hasHangingEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -29,12 +30,6 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.wepif.PermissionsResolverManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
@@ -44,55 +39,88 @@ 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.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.util.FatalConfigurationLoadingException;
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.
*
* @author sk89q
*/
public class WorldGuardPlugin extends JavaPlugin {
/**
* Manager for commands. This automatically handles nested commands,
* permissions checking, and a number of other fancy command things.
* We just set it up and register commands against it.
*/
private final CommandsManager<CommandSender> commands;
/**
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final RegionManager globalRegionManager;
private final ConfigurationManager configuration;
private RuleListsManager ruleListsManager;
private RegionQueryCache regionCache;
private final LagStopMode lagStopper;
private WorldGuardWorldListener worldListener;
/**
* Used for scheduling flags.
*/
private FlagStateManager flagStateManager;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
* 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 GlobalRegionManager(this);
globalRegionManager = new RegionManager(this);
lagStopper = new LagStopMode(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@@ -103,11 +131,18 @@ public class WorldGuardPlugin extends JavaPlugin {
};
}
/**
* Called on plugin enable.
*/
@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));
@@ -131,27 +166,9 @@ public class WorldGuardPlugin extends JavaPlugin {
PermissionsResolverManager.initialize(this);
// This must be done before configuration is loaded
LegacyWorldGuardMigration.migrateBlacklist(this);
try {
// Load the configuration
configuration.load();
globalRegionManager.preload();
} catch (FatalConfigurationLoadingException e) {
e.printStackTrace();
getServer().shutdown();
}
// Migrate regions after the regions were loaded because
// the migration code reuses the loaded region managers
LegacyWorldGuardMigration.migrateRegions(this);
flagStateManager = new FlagStateManager(this);
if (configuration.useRegionsScheduler) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
// Load the configuration
configuration.load();
globalRegionManager.preload();
// Register events
(new WorldGuardPlayerListener(this)).registerEvents();
@@ -160,42 +177,27 @@ public class WorldGuardPlugin extends JavaPlugin {
(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();
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
getServer().getPluginManager().registerEvents(new WorldGuardCommandBookListener(this), this);
}
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
for (World world : getServer().getWorlds()) {
worldListener.initWorld(world);
}
worldListener.registerEvents();
if (!configuration.hasCommandBookGodMode()) {
// Check god mode for existing players, if any
for (Player player : getServer().getOnlinePlayers()) {
if (inGroup(player, "wg-invincible") ||
(configuration.autoGodMode && hasPermission(player, "worldguard.auto-invincible"))) {
configuration.enableGodMode(player);
}
}
}
}
/**
* Called on plugin disable.
*/
@Override
public void onDisable() {
globalRegionManager.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
@@ -222,12 +224,22 @@ public class WorldGuardPlugin extends JavaPlugin {
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 GlobalRegionManager getGlobalRegionManager() {
public RegionManager getGlobalRegionManager() {
return globalRegionManager;
}
@@ -242,15 +254,6 @@ public class WorldGuardPlugin extends JavaPlugin {
return getGlobalStateManager();
}
/**
* Gets the flag state manager.
*
* @return The flag state manager
*/
public FlagStateManager getFlagStateManager() {
return flagStateManager;
}
/**
* Get the global ConfigurationManager.
* USe this to access global configuration values and per-world configuration values.
@@ -260,6 +263,85 @@ public class WorldGuardPlugin extends JavaPlugin {
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
@@ -691,9 +773,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* @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) {
public void createDefaultConfiguration(File actual, String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
@@ -704,16 +784,10 @@ public class WorldGuardPlugin extends JavaPlugin {
return;
}
InputStream input =
null;
try {
JarFile file = new JarFile(getFile());
ZipEntry copy = file.getEntry("defaults/" + defaultName);
if (copy == null) throw new FileNotFoundException();
input = file.getInputStream(copy);
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
InputStream input = WorldGuardPlugin.class.getResourceAsStream("/defaults/" + defaultName);
if (input == null) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
@@ -773,7 +847,6 @@ public class WorldGuardPlugin extends JavaPlugin {
* @param player The player to remove state information for
*/
public void forgetPlayer(Player player) {
flagStateManager.forget(player);
}
/**
@@ -782,7 +855,7 @@ public class WorldGuardPlugin extends JavaPlugin {
*
* @param player The player to check.
* @param loc The location to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.Location)
* @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) {
@@ -795,7 +868,7 @@ public class WorldGuardPlugin extends JavaPlugin {
*
* @param player The player to check
* @param block The block to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.block.Block)
* @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) {
@@ -808,7 +881,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* @param world world to get the region manager for
* @return the region manager or null if regions are not enabled
*/
public RegionManager getRegionManager(World world) {
public RegionIndex getRegionManager(World world) {
if (!getGlobalStateManager().get(world).useRegions) {
return null;
}
@@ -816,6 +889,15 @@ public class WorldGuardPlugin extends JavaPlugin {
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.
*
@@ -7,23 +7,32 @@ import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* @author zml2008
* Listener for server events.
*/
public class WorldGuardServerListener implements Listener {
class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardServerListener(WorldGuardPlugin plugin) {
/**
* Construct the listener.
*
* @param plugin WorldGuard plugin
*/
WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
/**
* 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();
}
@@ -31,6 +40,7 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
// Legacy god mode
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
@@ -5,42 +5,34 @@
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.FlagStateManager.PlayerFlagState;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
public class WorldGuardVehicleListener implements Listener {
/**
* Listener for vehicle events.
*/
class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
* Construct the listener.
*
* @param plugin
* @param plugin WorldGuard plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
* Register the events.
*/
public void registerEvents() {
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@@ -49,130 +41,17 @@ public class WorldGuardVehicleListener implements Listener {
Vehicle vehicle = event.getVehicle();
Entity destroyer = event.getAttacker();
if (!(destroyer instanceof Player)) return; // don't care
Player player = (Player) destroyer;
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = cfg.get(vehicle.getWorld());
if (wcfg.useRegions) {
Vector pt = toVector(vehicle.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.DESTROY_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to destroy vehicles here.");
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
if (vehicle.getPassenger() == null
|| !(vehicle.getPassenger() instanceof Player)) return;
Player player = (Player) vehicle.getPassenger();
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// unfortunate code duplication
if (wcfg.useRegions) {
// Did we move a block?
if (event.getFrom().getBlockX() != event.getTo().getBlockX()
|| event.getFrom().getBlockY() != event.getTo().getBlockY()
|| event.getFrom().getBlockZ() != event.getTo().getBlockZ()) {
PlayerFlagState state = plugin.getFlagStateManager().getState(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
boolean hasBypass = plugin.getGlobalRegionManager().hasBypass(player, world);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Vector pt = new Vector(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
boolean entryAllowed = set.allows(DefaultFlag.ENTRY, localPlayer);
if (!hasBypass && !entryAllowed) {
vehicle.setVelocity(new org.bukkit.util.Vector(0,0,0));
vehicle.teleport(event.getFrom());
return;
}
// Have to set this state
if (state.lastExitAllowed == null) {
state.lastExitAllowed = mgr.getApplicableRegions(toVector(event.getFrom()))
.allows(DefaultFlag.EXIT, localPlayer);
}
boolean exitAllowed = set.allows(DefaultFlag.EXIT, localPlayer);
if (!hasBypass && exitAllowed && !state.lastExitAllowed) {
player.sendMessage(ChatColor.DARK_RED + "You are not permitted to leave this area.");
vehicle.setVelocity(new org.bukkit.util.Vector(0,0,0));
vehicle.teleport(event.getFrom());
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE, localPlayer);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE, localPlayer);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER, localPlayer);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE, localPlayer);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
}
if ((notifyLeave == null || !notifyLeave)
&& state.notifiedForLeave != null && state.notifiedForLeave) {
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " left NOTIFY region");
}
if (notifyEnter != null && notifyEnter && (state.notifiedForEnter == null
|| !state.notifiedForEnter)) {
StringBuilder regionList = new StringBuilder();
for (ProtectedRegion region : set) {
if (regionList.length() != 0) {
regionList.append(", ");
}
regionList.append(region.getId());
}
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
+ regionList);
}
state.lastGreeting = greeting;
state.lastFarewell = farewell;
state.notifiedForEnter = notifyEnter;
state.notifiedForLeave = notifyLeave;
state.lastExitAllowed = exitAllowed;
state.lastWorld = event.getTo().getWorld();
state.lastBlockX = event.getTo().getBlockX();
state.lastBlockY = event.getTo().getBlockY();
state.lastBlockZ = event.getTo().getBlockZ();
}
// 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;
}
}
}
@@ -18,8 +18,6 @@
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -27,28 +25,30 @@ 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.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
public class WorldGuardWeatherListener implements Listener {
import com.sk89q.rulelists.DefaultAttachments;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for weather events.
*/
class WorldGuardWeatherListener implements Listener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
* Construct the listener.
*
* @param plugin The plugin instance
* @param plugin WorldGuard plugin
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
/**
* Register the events.
*/
void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@@ -57,14 +57,12 @@ public class WorldGuardWeatherListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysRaining) {
event.setCancelled(true);
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WEATHER_TRANSITION);
BukkitContext context = new BukkitContext(plugin, event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@@ -73,38 +71,29 @@ public class WorldGuardWeatherListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toThunderState()) {
if (wcfg.disableThunder) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysThundering) {
event.setCancelled(true);
}
// 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());
if (wcfg.disallowedLightningBlocks.size() > 0) {
int targetId = event.getLightning().getLocation().getBlock().getTypeId();
if (wcfg.disallowedLightningBlocks.contains(targetId)) {
event.setCancelled(true);
}
}
Location loc = event.getLightning().getLocation();
if (wcfg.useRegions) {
Vector pt = toVector(loc);
RegionManager mgr = plugin.getGlobalRegionManager().get(loc.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
}
// 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;
}
}
}
@@ -5,79 +5,75 @@
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
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 object;
* Construct the listener.
*
* @param plugin The plugin instance
* @param plugin WorldGuard plugin
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
* Register the events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
public void onWorldLoad(WorldLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (cfg.activityHaltToggle) {
int removed = 0;
/* --- No short-circuit returns below this line --- */
for (Entity entity : event.getChunk().getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(DefaultAttachments.WORLD_LOAD);
BukkitContext context = new BukkitContext(plugin, event);
rules.process(context);
}
if (removed > 50) {
plugin.getLogger().info("Halt-Act: " + removed + " entities (>50) auto-removed from "
+ event.getChunk().toString());
}
@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 onWorldLoad(WorldLoadEvent event) {
initWorld(event.getWorld());
}
/**
* Initialize the settings for the specified world
* @see WorldConfiguration#alwaysRaining
* @see WorldConfiguration#disableWeather
* @see WorldConfiguration#alwaysThundering
* @see WorldConfiguration#disableThunder
* @param world The specified world
*/
public void initWorld(World world) {
public void onWorldSave(WorldSaveEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
world.setStorm(false);
}
if (wcfg.alwaysThundering && !wcfg.disableThunder) {
world.setThundering(true);
} else if (wcfg.disableThunder && !wcfg.alwaysThundering) {
world.setStorm(false);
}
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);
}
}
@@ -19,23 +19,7 @@
package com.sk89q.worldguard.bukkit.commands;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.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.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
@@ -47,74 +31,71 @@ 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.domains.DefaultDomain;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.migrators.AbstractDatabaseMigrator;
import com.sk89q.worldguard.protection.databases.migrators.MigrationException;
import com.sk89q.worldguard.protection.databases.migrators.MigratorKey;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
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 (!ProtectedRegion.isValidId(id)) {
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.");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
RegionIndex mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (mgr.hasRegion(id)) {
throw new CommandException("That region is already defined. Use redefine instead.");
}
ProtectedRegion region;
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 ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
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 ProtectedCuboidRegion(id, min, max);
region = new Cuboid(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
@@ -124,9 +105,9 @@ public class RegionCommands {
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 + ".");
@@ -135,23 +116,23 @@ public class RegionCommands {
+ 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__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion existing = mgr.getRegionExact(id);
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.");
@@ -163,27 +144,27 @@ public class RegionCommands {
plugin.checkPermission(sender, "worldguard.region.redefine.member");
} else {
plugin.checkPermission(sender, "worldguard.region.redefine");
}
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
ProtectedRegion region;
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 ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
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 ProtectedCuboidRegion(id, min, max);
region = new Cuboid(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
@@ -197,11 +178,11 @@ public class RegionCommands {
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) {
@@ -209,137 +190,6 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"claim"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Claim a region", min = 1)
@CommandPermissions({"worldguard.region.claim"})
public void claim(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (mgr.hasRegion(id)) {
throw new CommandException("That region already exists. Please choose a different name.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
region = new ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
} else if (sel instanceof CuboidSelection) {
BlockVector min = sel.getNativeMinimumPoint().toBlockVector();
BlockVector max = sel.getNativeMaximumPoint().toBlockVector();
region = new ProtectedCuboidRegion(id, min, max);
} else {
throw new CommandException(
"The type of region selected in WorldEdit is unsupported in WorldGuard!");
}
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionDBUtil.parseDomainString(args.getSlice(1), 1));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
if (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
// Check whether the player has created too many regions
int maxRegionCount = wcfg.getMaxRegionCount(player);
if (maxRegionCount >= 0
&& mgr.getRegionCountOfPlayer(localPlayer) >= maxRegionCount) {
throw new CommandException("You own too many regions, delete one first to claim a new one.");
}
}
ProtectedRegion existing = mgr.getRegionExact(id);
// Check for an existing region
if (existing != null) {
if (!existing.getOwners().contains(localPlayer)) {
throw new CommandException("This region already exists and you don't own it.");
}
}
ApplicableRegionSet regions = mgr.getApplicableRegions(region);
// Check if this region overlaps any other region
if (regions.size() > 0) {
if (!regions.isOwnerOfAll(localPlayer)) {
throw new CommandException("This region overlaps with someone else's region.");
}
} else {
if (wcfg.claimOnlyInsideExistingRegions) {
throw new CommandException("You may only claim regions inside " +
"existing regions that you or your group own.");
}
}
/*if (plugin.getGlobalConfiguration().getiConomy() != null && wcfg.useiConomy && wcfg.buyOnClaim) {
if (iConomy.getBank().hasAccount(player.getName())) {
Account account = iConomy.getBank().getAccount(player.getName());
double balance = account.getBalance();
double regionCosts = region.countBlocks() * wcfg.buyOnClaimPrice;
if (balance >= regionCosts) {
account.subtract(regionCosts);
player.sendMessage(ChatColor.YELLOW + "You have bought that region for "
+ iConomy.getBank().format(regionCosts));
account.save();
} else {
player.sendMessage(ChatColor.RED + "You have not enough money.");
player.sendMessage(ChatColor.RED + "The region you want to claim costs "
+ iConomy.getBank().format(regionCosts));
player.sendMessage(ChatColor.RED + "You have " + iConomy.getBank().format(balance));
return;
}
} else {
player.sendMessage(ChatColor.YELLOW + "You have not enough money.");
return;
}
}*/
if (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
if (region.volume() > wcfg.maxClaimVolume) {
player.sendMessage(ChatColor.RED + "This region is too large to claim.");
player.sendMessage(ChatColor.RED +
"Max. volume: " + wcfg.maxClaimVolume + ", your volume: " + region.volume());
return;
}
}
region.getOwners().addPlayer(player.getName());
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
} catch (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)
@@ -349,7 +199,7 @@ public class RegionCommands {
final World world = player.getWorld();
final LocalPlayer localPlayer = plugin.wrapPlayer(player);
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final String id;
if (args.argsLength() == 0) {
@@ -365,7 +215,7 @@ public class RegionCommands {
id = args.getString(0);
}
final ProtectedRegion region = mgr.getRegion(id);
final Region region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
@@ -374,7 +224,7 @@ public class RegionCommands {
selectRegion(player, localPlayer, region);
}
public void selectRegion(Player player, LocalPlayer localPlayer, ProtectedRegion region) throws CommandException, CommandPermissionsException {
public void selectRegion(Player player, LocalPlayer localPlayer, Region region) throws CommandException, CommandPermissionsException {
final WorldEditPlugin worldEdit = plugin.getWorldEdit();
final String id = region.getId();
@@ -387,19 +237,19 @@ public class RegionCommands {
}
final World world = player.getWorld();
if (region instanceof ProtectedCuboidRegion) {
final ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
final Vector pt1 = cuboid.getMinimumPoint();
final Vector pt2 = cuboid.getMaximumPoint();
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 ProtectedPolygonalRegion) {
final ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
} else if (region instanceof ExtrudedPolygon) {
final ExtrudedPolygon poly2d = (ExtrudedPolygon) region;
final Polygonal2DSelection selection = new Polygonal2DSelection(
world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(),
poly2d.getMaximumPoint().getBlockY()
poly2d.getAABBMin().getBlockY(),
poly2d.getAABBMax().getBlockY()
);
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
@@ -427,7 +277,7 @@ public class RegionCommands {
world = plugin.matchWorld(sender, args.getString(0));
}
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final String id;
@@ -455,10 +305,10 @@ public class RegionCommands {
id = args.getString(1).toLowerCase();
}
final ProtectedRegion region = mgr.getRegion(id);
final Region region = mgr.getRegion(id);
if (region == null) {
if (!ProtectedRegion.isValidId(id)) {
if (!Region.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
@@ -471,7 +321,7 @@ public class RegionCommands {
}
}
public void displayRegionInfo(CommandSender sender, final LocalPlayer localPlayer, ProtectedRegion region) throws CommandPermissionsException {
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)) {
@@ -489,17 +339,27 @@ public class RegionCommands {
boolean hasFlags = false;
final StringBuilder s = new StringBuilder(ChatColor.BLUE + "Flags: ");
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object val = region.getFlag(flag);
Object val = region.getFlag(flag), group = null;
if (val == null) {
continue;
}
if (s.length() > 0) {
if (hasFlags) {
s.append(", ");
}
s.append(flag.getName() + ": " + String.valueOf(val));
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) {
@@ -520,8 +380,8 @@ public class RegionCommands {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Members: " + members.toUserFriendlyString());
}
final BlockVector min = region.getMinimumPoint();
final BlockVector max = region.getMaximumPoint();
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() + ")"
@@ -605,8 +465,8 @@ public class RegionCommands {
world = plugin.checkPlayer(sender).getWorld();
}
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final Map<String, ProtectedRegion> regions = mgr.getRegions();
final RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
final Map<String, Region> regions = mgr.getRegions();
List<RegionEntry> regionEntries = new ArrayList<RegionEntry>();
int index = 0;
@@ -653,21 +513,22 @@ public class RegionCommands {
@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);
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
Region region = mgr.getRegion(id);
if (region == null) {
if (id.equalsIgnoreCase("__global__")) {
@@ -691,9 +552,9 @@ public class RegionCommands {
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
@@ -702,10 +563,10 @@ public class RegionCommands {
break;
}
}
if (foundFlag == null) {
StringBuilder list = new StringBuilder();
// Need to build a list
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (list.length() > 0) {
@@ -730,8 +591,8 @@ public class RegionCommands {
+ flag.getName() + "." + id.toLowerCase())) {
continue;
}
}
}
list.append(flag.getName());
}
@@ -753,38 +614,63 @@ public class RegionCommands {
if (args.hasFlag('g')) {
String group = args.getFlag('g');
if (foundFlag.getRegionGroupFlag() == null) {
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 {
setFlag(region, foundFlag.getRegionGroupFlag(), sender, group);
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 group flag for '" + foundFlag.getName() + "' set.");
} else {
if (value != null) {
try {
setFlag(region, foundFlag, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
+ "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 flag '" + foundFlag.getName() + "' set.");
+ "Region group flag for '" + foundFlag.getName() + "' reset to default.");
} else {
// Clear the flag
region.setFlag(foundFlag, null);
region.setFlag(groupFlag, groupValue);
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' cleared.");
+ "Region group flag for '" + foundFlag.getName() + "' set.");
}
}
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -792,29 +678,29 @@ public class RegionCommands {
+ e.getMessage());
}
}
public <V> void setFlag(ProtectedRegion region,
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__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
}
@@ -827,14 +713,14 @@ public class RegionCommands {
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) {
@@ -842,22 +728,22 @@ public class RegionCommands {
+ 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__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
}
@@ -869,25 +755,25 @@ public class RegionCommands {
region.setParent(null);
} catch (CircularInheritanceException ignore) {
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' cleared.");
} else {
String parentId = args.getString(1);
ProtectedRegion parent = mgr.getRegion(parentId);
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)) {
@@ -895,18 +781,18 @@ public class RegionCommands {
} 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) {
@@ -914,24 +800,24 @@ public class RegionCommands {
+ 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);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegionExact(id);
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)) {
@@ -939,12 +825,12 @@ public class RegionCommands {
} 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) {
@@ -952,21 +838,21 @@ public class RegionCommands {
+ 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) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.load();
sender.sendMessage(ChatColor.YELLOW
@@ -977,8 +863,8 @@ public class RegionCommands {
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
RegionIndex mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.load();
} catch (ProtectionDatabaseException e) {
@@ -986,26 +872,26 @@ public class RegionCommands {
+ 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) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
RegionIndex mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW
@@ -1016,8 +902,8 @@ public class RegionCommands {
}
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
RegionIndex mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -1025,74 +911,24 @@ public class RegionCommands {
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases saved.");
}
}
@Command(aliases = {"migratedb"}, usage = "<from> <to>",
desc = "Migrate from one Protection Database to another.", min = 1)
@CommandPermissions({"worldguard.region.migratedb"})
public void migratedb(CommandContext args, CommandSender sender) throws CommandException {
String from = args.getString(0).toLowerCase().trim();
String to = args.getString(1).toLowerCase().trim();
if (from.equals(to)) {
throw new CommandException("Will not migrate with common source and target.");
}
Map<MigratorKey, Class<? extends AbstractDatabaseMigrator>> migrators = AbstractDatabaseMigrator.getMigrators();
MigratorKey key = new MigratorKey(from,to);
if (!migrators.containsKey(key)) {
throw new CommandException("No migrator found for that combination and direction.");
}
long lastRequest = 10000000;
if (this.migrateDBRequestDate != null) {
lastRequest = new Date().getTime() - this.migrateDBRequestDate.getTime();
}
if (this.migrateDBRequest == null || lastRequest > 60000) {
this.migrateDBRequest = key;
this.migrateDBRequestDate = new Date();
throw new CommandException("This command is potentially dangerous.\n" +
"Please ensure you have made a backup of your data, and then re-enter the command exactly to procede.");
}
Class<? extends AbstractDatabaseMigrator> cls = migrators.get(key);
try {
AbstractDatabaseMigrator migrator = cls.getConstructor(WorldGuardPlugin.class).newInstance(plugin);
migrator.migrate();
} catch (IllegalArgumentException ignore) {
} catch (SecurityException ignore) {
} catch (InstantiationException ignore) {
} catch (IllegalAccessException ignore) {
} catch (InvocationTargetException ignore) {
} catch (NoSuchMethodException ignore) {
} catch (MigrationException e) {
throw new CommandException("Error migrating database: " + e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW + "Regions have been migrated successfully.\n" +
"If you wish to use the destination format as your new backend, please update your config and reload WorldGuard.");
}
@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 RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
final RegionIndex mgr = plugin.getGlobalRegionManager().get(player.getWorld());
String id = args.getString(0);
final ProtectedRegion region = mgr.getRegion(id);
final Region region = mgr.getRegion(id);
if (region == null) {
if (!ProtectedRegion.isValidId(id)) {
if (!Region.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
@@ -30,11 +30,11 @@ import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
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.
@@ -55,8 +55,8 @@ public class RegionMemberCommands {
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
@@ -95,8 +95,8 @@ public class RegionMemberCommands {
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
@@ -148,8 +148,8 @@ public class RegionMemberCommands {
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
@@ -189,8 +189,8 @@ public class RegionMemberCommands {
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
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.");
@@ -22,15 +22,11 @@ package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.LagStopMode;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
@@ -45,15 +41,15 @@ public class ToggleCommands {
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) {
@@ -74,15 +70,14 @@ public class ToggleCommands {
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) {
@@ -98,48 +93,20 @@ public class ToggleCommands {
}
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "c", max = 0)
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();
ConfigurationManager configManager = plugin.getGlobalStateManager();
configManager.activityHaltToggle = !args.hasFlag('c');
if (configManager.activityHaltToggle) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted by "
+ plugin.toName(sender) + ".");
for (World world : plugin.getServer().getWorlds()) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
if (removed > 10) {
sender.sendMessage("" + removed + " entities (>10) auto-removed from "
+ world.toString());
}
}
lagStopper.setRemoveAnimals(!args.hasFlag('c'));
if (!args.hasFlag('c')) {
sender.sendMessage(ChatColor.YELLOW + "Enabling lag stop mode...");
lagStopper.enable(!args.hasFlag('g'));
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity no longer halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity is now allowed.");
sender.sendMessage(ChatColor.YELLOW + "Disabling lag stop mode...");
lagStopper.disable();
}
}
}
@@ -32,6 +32,7 @@ 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;
@@ -56,18 +57,19 @@ public class WorldGuardCommands {
@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("Minecraft");
minecraftLogger = Logger.getLogger("");
minecraftLogger.addHandler(handler);
}
try {
MaterialDatabase.reload();
plugin.getGlobalStateManager().unload();
plugin.getGlobalRegionManager().unload();
plugin.getGlobalStateManager().load();
@@ -81,15 +83,17 @@ public class WorldGuardCommands {
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 "
@@ -97,18 +101,20 @@ public class WorldGuardCommands {
} 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);
@@ -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;
}
}
@@ -0,0 +1,137 @@
// $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.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Tameable;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.SourceEntityResolver;
public class EntityCriteria implements Criteria<BukkitContext> {
private final EntityResolver entityResolver;
private Set<EntityType> types = new HashSet<EntityType>();
private Class<?>[] ofTypes = new Class<?>[0];
private Boolean isTamed = null;
// Counteract 1.3->1.4 breaking change
private EntityType fireballType =
BukkitUtil.tryEnum(EntityType.class, "FIREBALL", "LARGE_FIREBALL");
public EntityCriteria(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
public Class<?>[] getOfTypes() {
return ofTypes;
}
public void setOfTypes(Class<?>[] ofTypes) {
this.ofTypes = ofTypes;
}
public Set<EntityType> getTypes() {
return types;
}
public void setTypes(Set<EntityType> types) {
this.types = types;
}
public Boolean getIsTamed() {
return isTamed;
}
public void setIsTamed(Boolean isTamed) {
this.isTamed = isTamed;
}
@Override
public boolean matches(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
boolean matched = false;
// Hack because BlockIgniteEvent doesn't give an entity
if (context.getEvent() instanceof BlockIgniteEvent && entityResolver instanceof SourceEntityResolver) {
BlockIgniteEvent igniteEvent = (BlockIgniteEvent) context.getEvent();
if (igniteEvent.getCause() == IgniteCause.FIREBALL) {
if (types.contains(fireballType)) {
matched = true;
}
}
if (igniteEvent.getCause() == IgniteCause.LIGHTNING) {
if (types.contains(EntityType.LIGHTNING)) {
matched = true;
}
}
}
if (entity == null) {
return matched;
}
if (ofTypes.length != 0) {
Class<?> cls = entity.getClass();
for (Class<?> type : ofTypes) {
if (type.isAssignableFrom(cls)) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
if (isTamed != null) {
if (entity instanceof Tameable && ((Tameable) entity).isTamed() == isTamed) {
matched = true;
}
if (!matched) {
return false;
}
}
if (types.size() != 0) {
matched = types.contains(entity.getType());
if (!matched) {
return false;
}
}
return matched;
}
}
@@ -0,0 +1,91 @@
// $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.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
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;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class EntityCriteriaLoader extends AbstractNodeLoader<EntityCriteria> {
private final RuleListsManager manager;
private EnumLoaderBuilder<EntityType> typeLoader =
new EnumLoaderBuilder<EntityType>(EntityType.class);
public EntityCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public EntityCriteria read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
Set<EntityType> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
EntityCriteria criteria = new EntityCriteria(entityResolver);
List<Class<?>> ofTypes = new ArrayList<Class<?>>();
if (node.getBoolean("is-animal", false))
ofTypes.add(Animals.class);
if (node.getBoolean("is-monster", false))
ofTypes.add(Monster.class);
if (node.getBoolean("is-creature", false))
ofTypes.add(Creature.class);
if (node.getBoolean("is-living", false))
ofTypes.add(LivingEntity.class);
if (node.getBoolean("is-player", false))
ofTypes.add(Player.class);
if (node.getBoolean("is-tameable", false))
ofTypes.add(Tameable.class);
criteria.setTypes(types);
criteria.setOfTypes(ofTypes.toArray(new Class<?>[ofTypes.size()]));
criteria.setIsTamed(node.getBoolean("is-tamed"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "type", "is-animal", "is-monster", "is-creature",
"is-living", "is-player", "is-tameable", "is-tamed");
return criteria;
}
}
@@ -0,0 +1,113 @@
// $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 org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.region.ApplicableRegionSet;
import com.sk89q.worldguard.region.flags.DefaultFlag;
import com.sk89q.worldguard.region.flags.StateFlag;
public class FlagCriteria implements Criteria<BukkitContext> {
private final WorldGuardPlugin plugin;
private final StateFlag flag;
private BlockResolver blockResolver;
private EntityResolver entityResolver;
public FlagCriteria(WorldGuardPlugin plugin, StateFlag flag) {
this.plugin = plugin;
this.flag = flag;
}
public BlockResolver getBlockResolver() {
return blockResolver;
}
public void setBlockResolver(BlockResolver blockResolver) {
this.blockResolver = blockResolver;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
@Override
public boolean matches(BukkitContext context) {
boolean matches = false;
ApplicableRegionSet set = context.getApplicableRegionSet();
if (set == null) {
return false;
}
if (blockResolver != null) {
BlockState block = blockResolver.resolve(context);
if (block == null) {
return false;
}
if (flag == DefaultFlag.BUILD) {
matches = false;
} else {
matches = set.allows(flag);
}
if (!matches) {
return false;
}
}
if (entityResolver != null) {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
LocalPlayer localPlayer = null;
if (entity instanceof Player) {
localPlayer = plugin.wrapPlayer((Player) entity);
}
if (flag == DefaultFlag.BUILD) {
matches = localPlayer != null && set.canBuild(localPlayer);
} else {
matches = set.allows(flag, localPlayer);
}
}
return matches;
}
}
@@ -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.worldguard.bukkit.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.StaticFieldLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.region.flags.DefaultFlag;
import com.sk89q.worldguard.region.flags.StateFlag;
public class FlagCriteriaLoader extends AbstractNodeLoader<FlagCriteria> {
private final WorldGuardPlugin plugin;
private final RuleListsManager manager;
private final StaticFieldLoaderBuilder<StateFlag> stateFlagLoader =
new StaticFieldLoaderBuilder<StateFlag>(DefaultFlag.class, StateFlag.class);
public FlagCriteriaLoader(WorldGuardPlugin plugin, RuleListsManager manager) {
this.plugin = plugin;
this.manager = manager;
}
@Override
public FlagCriteria read(ConfigurationNode node)
throws DefinitionException {
BlockResolver blockResolver = null;
EntityResolver entityResolver = null;
String entity = node.getString("entity");
String block = node.getString("block");
if (block != null) {
blockResolver = manager.getResolvers().get(BlockResolver.class, block);
}
if (entity != null) {
entityResolver = manager.getResolvers().get(EntityResolver.class, entity);
}
if (block == null && entity == null) {
throw new LoaderBuilderException("Flag criteria needs either a block resolver or an entity resolver");
}
StateFlag flag = node.getOf("flag", stateFlagLoader);
if (flag == null) {
throw new LoaderBuilderException("A flag must be specified");
}
FlagCriteria criteria = new FlagCriteria(plugin, flag);
criteria.setBlockResolver(blockResolver);
criteria.setEntityResolver(entityResolver);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"flag", "block", "entity");
return criteria;
}
}
@@ -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.worldguard.bukkit.definitions;
import java.util.List;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class ItemCriteria implements Criteria<BukkitContext> {
private final EntityResolver entityResolver;
private final ItemStackSlotResolver itemResolver;
private MaterialPattern[] patterns = new MaterialPattern[0];
private Set<PotionEffectType> potionEffects = null;
private Boolean hasData = false;
public ItemCriteria(EntityResolver entityResolver, ItemStackSlotResolver itemResolver) {
this.entityResolver = entityResolver;
this.itemResolver = itemResolver;
}
public Boolean hasDataCheck() {
return hasData;
}
public void setDataCheck(Boolean hasData) {
this.hasData = hasData;
}
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 Set<PotionEffectType> getPotionEffects() {
return potionEffects;
}
public void setPotionEffects(Set<PotionEffectType> effects) {
this.potionEffects = effects;
}
@Override
public boolean matches(BukkitContext context) {
ItemStack item;
boolean matched = false;
if (entityResolver == null) {
item = context.getItem();
} else {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
item = itemResolver.resolve(entity).get();
}
if (item == null) {
return false;
}
if (hasData != null) {
matched = hasData == (item.getDurability() != 0);
if (!matched) {
return false;
}
}
if (item.getType() == Material.POTION && potionEffects.size() > 0) {
for (PotionEffect effect : Potion.fromItemStack(item).getEffects()) {
if (potionEffects.contains(effect.getType())) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
for (MaterialPattern pattern : patterns) {
if (pattern.matches(item.getTypeId(), item.getDurability())) {
matched = true;
break;
}
}
return matched;
}
}
@@ -0,0 +1,92 @@
// $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 java.util.Set;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.MaterialPatternLoaderBuilder;
import com.sk89q.rebar.config.types.StaticFieldLoaderBuilder;
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.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class ItemCriteriaLoader extends AbstractNodeLoader<ItemCriteria> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
private StaticFieldLoaderBuilder<PotionEffectType> effectLoader =
new StaticFieldLoaderBuilder<PotionEffectType>(PotionEffectType.class);
public ItemCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public ItemCriteria read(ConfigurationNode node) throws DefinitionException {
String entity = node.getString("entity");
EntityResolver entityResolver = null;
ItemStackSlotResolver resolver = null;
if (entity != null) {
entityResolver = manager.getResolvers()
.get(EntityResolver.class, entity);
resolver = manager.getResolvers()
.get(ItemStackSlotResolver.class, node.getString("item", ItemStackSlotResolver.DEFAULT));
}
// has-data
Boolean hasData = null;
if (node.contains("has-data")) {
hasData = node.getBoolean("has-data", false);
}
// Patterns
List<MaterialPattern> patterns = node.contains(INLINE) ? node.listOf(INLINE,
materialLoader) : node.listOf("material", materialLoader);
if (patterns.size() == 0 && hasData == null) {
throw new LoaderBuilderException("No block materials specified");
}
// Potion effects
Set<PotionEffectType> effects = node.setOf("potion-effect", effectLoader);
ItemCriteria criteria = new ItemCriteria(entityResolver, resolver);
criteria.setPatterns(patterns);
criteria.setDataCheck(hasData);
criteria.setPotionEffects(effects);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"item", "entity", "has-data", "material", "potion-effect");
return criteria;
}
}
@@ -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.worldguard.bukkit.definitions;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class PermissionCriteria implements Criteria<BukkitContext> {
private final WorldGuardPlugin wg;
private final EntityResolver entityResolver;
private String permission;
public PermissionCriteria(WorldGuardPlugin wg, EntityResolver entityResolver) {
this.wg = wg;
this.entityResolver = entityResolver;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
@Override
public boolean matches(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
if (entity instanceof Player) {
return wg.hasPermission((Player) entity, permission);
}
return false;
}
}
@@ -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.worldguard.bukkit.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
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;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class PermissionCriteriaLoader extends AbstractNodeLoader<PermissionCriteria> {
private final WorldGuardPlugin wg;
private final RuleListsManager manager;
public PermissionCriteriaLoader(WorldGuardPlugin wg, RuleListsManager manager) {
this.wg = wg;
this.manager = manager;
}
@Override
public PermissionCriteria read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
String permission = node.contains(INLINE) ?
node.getString(INLINE, "") :
node.getString("permission", "");
PermissionCriteria criteria = new PermissionCriteria(wg, entityResolver);
criteria.setPermission(permission);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "permission");
return criteria;
}
}
@@ -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 org.bukkit.event.Event;
import org.bukkit.event.weather.LightningStrikeEvent;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class PhenomenonCriteria implements Criteria<BukkitContext> {
private Boolean isLightning = null;
public PhenomenonCriteria(Boolean isLightning) {
}
public Boolean getIsLightning() {
return isLightning;
}
public void setIsLightning(Boolean isLightning) {
this.isLightning = isLightning;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (isLightning != null && isLightning && event instanceof LightningStrikeEvent) {
return true;
} else {
return isLightning == null;
}
}
}
@@ -0,0 +1,55 @@
// $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 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 PhenomenonCriteriaLoader extends AbstractNodeLoader<PhenomenonCriteria> {
public enum Phenomenon {
LIGHTNING;
}
private EnumLoaderBuilder<Phenomenon> typeLoader =
new EnumLoaderBuilder<Phenomenon>(Phenomenon.class);
@Override
public PhenomenonCriteria read(ConfigurationNode node) throws DefinitionException {
Set<Phenomenon> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
PhenomenonCriteria criteria = new PhenomenonCriteria(types.contains(Phenomenon.LIGHTNING));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
@@ -0,0 +1,92 @@
// $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 org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.region.ApplicableRegionSet;
public class RegionCriteria implements Criteria<BukkitContext> {
private BlockResolver blockResolver;
private EntityResolver entityResolver;
public BlockResolver getBlockResolver() {
return blockResolver;
}
public void setBlockResolver(BlockResolver blockResolver) {
this.blockResolver = blockResolver;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
public void setEntityResolver(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
@Override
public boolean matches(BukkitContext context) {
boolean matches = false;
if (blockResolver != null) {
BlockState block = blockResolver.resolve(context);
if (block == null) {
return false;
}
ApplicableRegionSet set = context.getRegionQuery().lookup(block.getBlock());
if (set == null) {
return false;
}
context.setApplicableRegionSet(set);
matches = true;
}
if (entityResolver != null) {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
ApplicableRegionSet set = context.getRegionQuery().lookup(entity);
if (set == null) {
return false;
}
context.setApplicableRegionSet(set);
matches = true;
}
return matches;
}
}
@@ -0,0 +1,70 @@
// $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.config.LoaderBuilderException;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class RegionCriteriaLoader extends AbstractNodeLoader<RegionCriteria> {
private final RuleListsManager manager;
public RegionCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public RegionCriteria read(ConfigurationNode node)
throws DefinitionException {
BlockResolver blockResolver = null;
EntityResolver entityResolver = null;
String entity = node.getString("entity");
String block = node.getString("block");
if (block != null) {
blockResolver = manager.getResolvers().get(BlockResolver.class, block);
}
if (entity != null) {
entityResolver = manager.getResolvers().get(EntityResolver.class, entity);
}
if (block == null && entity == null) {
throw new LoaderBuilderException("Region criteria needs either a block resolver or an entity resolver");
}
RegionCriteria criteria = new RegionCriteria();
criteria.setBlockResolver(blockResolver);
criteria.setEntityResolver(entityResolver);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"block", "entity");
return criteria;
}
}
@@ -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.worldguard.bukkit.definitions;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class SetBlockAction implements Action<BukkitContext> {
private final BlockResolver blockResolver;
private MaterialPattern material;
public SetBlockAction(BlockResolver blockResolver) {
this.blockResolver = blockResolver;
}
public MaterialPattern getMaterial() {
return material;
}
public void setMaterial(MaterialPattern material) {
this.material = material;
}
@Override
public void apply(BukkitContext context) {
BlockState state = blockResolver.resolve(context);
Event event = context.getEvent();
if (state == null) {
return;
}
state.setTypeId(material.getMaterial());
state.setRawData((byte) material.getDefaultData());
if (!(event instanceof BlockPlaceEvent || event instanceof BlockBreakEvent)) {
state.update();
}
}
}
@@ -0,0 +1,64 @@
// $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 com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
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.resolvers.BlockResolver;
public class SetBlockActionLoader extends AbstractNodeLoader<SetBlockAction> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
public SetBlockActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public SetBlockAction read(ConfigurationNode node) throws DefinitionException {
BlockResolver resolver = manager.getResolvers()
.get(BlockResolver.class, node.getString("block", BlockResolver.DEFAULT));
// Load patterns
MaterialPattern material = node.contains(INLINE) ?
node.getOf(INLINE, materialLoader) : node.getOf("material", materialLoader);
if (material == null) {
throw new LoaderBuilderException("One block material must be specified");
}
SetBlockAction criteria = new SetBlockAction(resolver);
criteria.setMaterial(material);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"block", "material");
return criteria;
}
}
@@ -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 org.bukkit.event.Event;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SetDropAction implements Action<BukkitContext> {
private Integer exp;
public Integer getExp() {
return exp;
}
public void setExp(Integer exp) {
this.exp = exp;
}
@Override
public void apply(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof PlayerDeathEvent) {
PlayerDeathEvent deathEvent = (PlayerDeathEvent) event;
if (exp != null) {
deathEvent.setDroppedExp(exp);
}
}
}
}
@@ -0,0 +1,41 @@
// $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 SetDropActionLoader extends AbstractNodeLoader<SetDropAction> {
@Override
public SetDropAction read(ConfigurationNode node) throws DefinitionException {
SetDropAction criteria = new SetDropAction();
criteria.setExp(node.getInt("set-xp"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"set-xp");
return criteria;
}
}
@@ -0,0 +1,61 @@
// $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.ExpressionParser;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SetMessageAction implements Action<BukkitContext> {
private ExpressionParser parser;
private String message;
public SetMessageAction(String message) {
this.message = message;
}
public ExpressionParser getParser() {
return parser;
}
public void setParser(ExpressionParser parser) {
this.parser = parser;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void apply(BukkitContext context) {
String newMessage = message;
if (parser != null) {
newMessage = parser.format(context, newMessage);
}
context.setMessage(newMessage);
}
}
@@ -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 static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
public class SetMessageActionLoader extends AbstractNodeLoader<SetMessageAction> {
private final RuleListsManager manager;
public SetMessageActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public SetMessageAction read(ConfigurationNode node) throws DefinitionException {
String message = node.contains(INLINE) ?
node.getString(INLINE) :
node.getString("message");
if (message == null) {
throw new LoaderBuilderException("No message specified");
}
SetMessageAction action = new SetMessageAction(message);
action.setParser(manager.getParser());
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"message");
return action;
}
}
@@ -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.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SpawnCriteria implements Criteria<BukkitContext> {
private Set<SpawnReason> causes = new HashSet<SpawnReason>();
public SpawnCriteria(Set<SpawnReason> causes) {
this.causes = causes;
}
public Set<SpawnReason> getCauses() {
return causes;
}
public void setCauses(Set<SpawnReason> causes) {
this.causes = causes;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof CreatureSpawnEvent) {
return causes.contains(((CreatureSpawnEvent) event).getSpawnReason());
} 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.CreatureSpawnEvent.SpawnReason;
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 SpawnCriteriaLoader extends AbstractNodeLoader<SpawnCriteria> {
private EnumLoaderBuilder<SpawnReason> typeLoader =
new EnumLoaderBuilder<SpawnReason>(SpawnReason.class);
@Override
public SpawnCriteria read(ConfigurationNode node) throws DefinitionException {
Set<SpawnReason> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
SpawnCriteria criteria = new SpawnCriteria(types);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
@@ -0,0 +1,68 @@
// $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 org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.ExpressionParser;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class TellAction implements Action<BukkitContext> {
private ExpressionParser parser;
private EntityResolver entityResolver;
private String message;
public TellAction(EntityResolver entityResolver, String message) {
this.entityResolver = entityResolver;
this.message = message;
}
public ExpressionParser getParser() {
return parser;
}
public void setParser(ExpressionParser parser) {
this.parser = parser;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void apply(BukkitContext context) {
Entity sender = entityResolver.resolve(context);
if (sender != null && sender instanceof CommandSender) {
if (parser != null) {
message = parser.format(context, message);
}
((CommandSender) sender).sendMessage(message);
}
}
}
@@ -0,0 +1,55 @@
// $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 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;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class TellActionLoader extends AbstractNodeLoader<TellAction> {
private final RuleListsManager manager;
public TellActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public TellAction read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
String message = node.contains(INLINE) ? node.getString(INLINE) : node.getString("message");
TellAction action = new TellAction(entityResolver, message);
action.setParser(manager.getParser());
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "message");
return action;
}
}
@@ -0,0 +1,344 @@
// $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 org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import com.sk89q.rulelists.Action;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class UpdateEntityAction implements Action<BukkitContext> {
private final WorldGuardPlugin wg;
private final EntityResolver entityResolver;
private Boolean explode;
private Float fallDistance;
private Integer fireTicks;
private Integer health;
private Integer damage;
private Integer remainingAir;
private Integer foodLevel;
private Float exhaustionLevel;
private Float saturationLevel;
private Float walkSpeed;
private Boolean allowFlight;
private Boolean flying;
private Float flySpeed;
private Boolean sneaking;
private Boolean sprinting;
private Boolean invincible;
private Boolean openWorkbench;
private String performCommand;
private Boolean teleportSafely;
public UpdateEntityAction(WorldGuardPlugin wg, EntityResolver entityResolver) {
this.wg = wg;
this.entityResolver = entityResolver;
}
public Boolean getExplode() {
return explode;
}
public void setExplode(Boolean explode) {
this.explode = explode;
}
public Float getFallDistance() {
return fallDistance;
}
public void setFallDistance(Float fallDistance) {
this.fallDistance = fallDistance;
}
public Integer getFireTicks() {
return fireTicks;
}
public void setFireTicks(Integer fireTicks) {
this.fireTicks = fireTicks;
}
public Integer getHealth() {
return health;
}
public void setHealth(Integer health) {
this.health = health;
}
public Integer getDamage() {
return damage;
}
public void setDamage(Integer damage) {
this.damage = damage;
}
public Integer getRemainingAir() {
return remainingAir;
}
public void setRemainingAir(Integer remainingAir) {
this.remainingAir = remainingAir;
}
public Integer getFoodLevel() {
return foodLevel;
}
public void setFoodLevel(Integer foodLevel) {
this.foodLevel = foodLevel;
}
public Float getExhaustionLevel() {
return exhaustionLevel;
}
public void setExhaustionLevel(Float exhaustionLevel) {
this.exhaustionLevel = exhaustionLevel;
}
public Float getSaturationLevel() {
return saturationLevel;
}
public void setSaturationLevel(Float saturationLevel) {
this.saturationLevel = saturationLevel;
}
public Float getWalkSpeed() {
return walkSpeed;
}
public void setWalkSpeed(Float walkSpeed) {
this.walkSpeed = walkSpeed;
}
public Boolean getAllowFlight() {
return allowFlight;
}
public void setAllowFlight(Boolean allowFlight) {
this.allowFlight = allowFlight;
}
public Boolean getFlying() {
return flying;
}
public void setFlying(Boolean flying) {
this.flying = flying;
}
public Float getFlySpeed() {
return flySpeed;
}
public void setFlySpeed(Float flySpeed) {
this.flySpeed = flySpeed;
}
public Boolean getSneaking() {
return sneaking;
}
public void setSneaking(Boolean sneaking) {
this.sneaking = sneaking;
}
public Boolean getSprinting() {
return sprinting;
}
public void setSprinting(Boolean sprinting) {
this.sprinting = sprinting;
}
public Boolean getInvincible() {
return invincible;
}
public void setInvincible(Boolean invincible) {
this.invincible = invincible;
}
public Boolean getOpenWorkbench() {
return openWorkbench;
}
public void setOpenWorkbench(Boolean openWorkbench) {
this.openWorkbench = openWorkbench;
}
public String getPerformCommand() {
return performCommand;
}
public void setPerformCommand(String performCommand) {
this.performCommand = performCommand;
}
public Boolean getTeleportSafely() {
return teleportSafely;
}
public void setTeleportSafely(Boolean teleportSafely) {
this.teleportSafely = teleportSafely;
}
@SuppressWarnings("deprecation")
@Override
public void apply(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
if (explode != null)
entity.getWorld().createExplosion(null, 4);
if (fireTicks != null)
entity.setFireTicks(fireTicks);
if (fallDistance != null)
entity.setFallDistance(fallDistance);
if (entity instanceof LivingEntity) {
LivingEntity living = (LivingEntity) entity;
if (health != null)
living.setHealth(health);
if (damage != null)
living.damage(damage);
if (remainingAir != null)
living.setRemainingAir(remainingAir);
}
if (entity instanceof Player) {
Player player = (Player) entity;
if (foodLevel != null)
player.setFoodLevel(foodLevel);
if (saturationLevel != null)
player.setSaturation(saturationLevel);
if (exhaustionLevel != null)
player.setExhaustion(exhaustionLevel);
if (walkSpeed != null)
player.setWalkSpeed(walkSpeed);
if (allowFlight != null)
player.setAllowFlight(allowFlight);
if (flying != null)
player.setFlying(flying);
if (flySpeed != null)
player.setFlySpeed(flySpeed);
if (sneaking != null)
player.setSneaking(sneaking);
if (sprinting != null)
player.setSneaking(sprinting);
if (invincible != null) {
ConfigurationManager cfg = wg.getGlobalStateManager();
if (invincible) {
cfg.enableGodMode(player);
} else {
cfg.disableGodMode(player);
}
}
if (openWorkbench != null && openWorkbench)
player.openWorkbench(player.getLocation(), true);
if (performCommand != null)
player.performCommand(performCommand);
}
if (teleportSafely != null && teleportSafely) {
Location loc = entity.getLocation();
World world = loc.getWorld();
// In case we're in void!
if (loc.getY() < 1) {
loc.setY(1);
}
int maxY = world.getMaxHeight();
int x = loc.getBlockX();
int y = Math.max(0, loc.getBlockY());
int z = loc.getBlockZ();
byte free = 0;
loop:
while (y <= maxY + 2) {
if (BlockType.canPassThrough(new Location(world, x, y, z).getBlock().getTypeId())) {
++free;
} else {
free = 0;
}
if (free == 2) {
Block block = world.getBlockAt(x, y - 2, z);
int id = block.getTypeId();
int data = block.getData();
Location newLoc = new Location(world, x + 0.5,
y - 2 + BlockType.centralTopLimit(id, data), z + 0.5);
// Don't want the player falling into void
if (newLoc.getBlockY() <= 1) {
Block bottomBlock = world.getBlockAt(x, 0, z);
bottomBlock.setType(Material.GLASS);
newLoc.add(0, 1, 0);
}
entity.teleport(newLoc);
entity.setFallDistance(0);
break loop;
}
++y;
}
}
}
}
@@ -0,0 +1,81 @@
// $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;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class UpdateEntityActionLoader extends AbstractNodeLoader<UpdateEntityAction> {
private final WorldGuardPlugin wg;
private final RuleListsManager manager;
public UpdateEntityActionLoader(WorldGuardPlugin wg, RuleListsManager manager) {
this.wg = wg;
this.manager = manager;
}
@Override
public UpdateEntityAction read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
UpdateEntityAction criteria = new UpdateEntityAction(wg, entityResolver);
criteria.setExplode(node.getBoolean("explode"));
criteria.setFallDistance(node.getFloat("set-fall-distance"));
criteria.setFireTicks(node.getInt("set-fire-ticks"));
criteria.setTeleportSafely(node.getBoolean("teleport-safely"));
criteria.setHealth(node.getInt("set-health"));
criteria.setDamage(node.getInt("damage"));
criteria.setRemainingAir(node.getInt("set-air"));
criteria.setFoodLevel(node.getInt("food-level"));
criteria.setSaturationLevel(node.getFloat("set-saturation"));
criteria.setExhaustionLevel(node.getFloat("set-exhaustion"));
criteria.setWalkSpeed(node.getFloat("set-walk-speed"));
criteria.setAllowFlight(node.getBoolean("set-allow-flight"));
criteria.setFlying(node.getBoolean("set-flying"));
criteria.setFlySpeed(node.getFloat("set-fly-speed"));
criteria.setSneaking(node.getBoolean("set-sneaking"));
criteria.setSprinting(node.getBoolean("set-sprinting"));
criteria.setInvincible(node.getBoolean("set-invincible"));
criteria.setOpenWorkbench(node.getBoolean("open-workbench"));
criteria.setPerformCommand(node.getString("perform-command"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "explode", "set-fall-distance",
"set-fire-ticks", "set-health", "damage", "set-air",
"food-level", "set-saturation", "set-exhaustion",
"set-walk-speed", "set-allow-flight", "set-flying",
"set-fly-speed", "set-sneaking", "set-sprinting",
"set-invincible", "open-workbench", "perform-command",
"teleport-safely");
return criteria;
}
}
@@ -0,0 +1,95 @@
// $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 org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlot;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class UpdateItemAction implements Action<BukkitContext> {
private final EntityResolver entityResolver;
private final ItemStackSlotResolver itemResolver;
private boolean destroy = false;
private short newData = -1;
public UpdateItemAction(EntityResolver entityResolver, ItemStackSlotResolver itemResolver) {
this.entityResolver = entityResolver;
this.itemResolver = itemResolver;
}
public boolean isDestroy() {
return destroy;
}
public void setDestroy(boolean destroy) {
this.destroy = destroy;
}
public short getNewData() {
return newData;
}
public void setNewData(short newData) {
this.newData = newData;
}
@Override
public void apply(BukkitContext context) {
ItemStackSlot slot = null;
ItemStack item;
if (entityResolver == null) {
item = context.getItem();
} else {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return;
}
slot = itemResolver.resolve(entity);
item = slot.get();
}
if (item == null) {
return;
}
boolean updated = false;
if (destroy) {
item = null;
updated = true;
} else if (newData >= 0) {
item.setDurability(newData);
updated = true;
}
if (updated && slot != null) {
slot.update(item);
}
}
}
@@ -0,0 +1,64 @@
// $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;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class UpdateItemActionLoader extends AbstractNodeLoader<UpdateItemAction> {
private final RuleListsManager manager;
public UpdateItemActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public UpdateItemAction read(ConfigurationNode node) throws DefinitionException {
String entity = node.getString("entity");
EntityResolver entityResolver = null;
ItemStackSlotResolver resolver = null;
if (entity != null) {
entityResolver = manager.getResolvers()
.get(EntityResolver.class, entity);
resolver = manager.getResolvers()
.get(ItemStackSlotResolver.class, node.getString("item", ItemStackSlotResolver.DEFAULT));
}
boolean destroy = node.getBoolean("destroy", false);
short newData = (short) node.getInt("set-data", -1);
UpdateItemAction action = new UpdateItemAction(entityResolver, resolver);
action.setDestroy(destroy);
action.setNewData(newData);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"item", "entity", "destroy", "set-data");
return action;
}
}
@@ -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.worldguard.bukkit.definitions;
import org.bukkit.World;
import org.bukkit.event.Event;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.world.WorldEvent;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class UpdateWorldAction implements Action<BukkitContext> {
private Boolean storm = null;
private Boolean thunderstorm = null;
public UpdateWorldAction() {
}
public Boolean getStorm() {
return storm;
}
public void setStorm(Boolean storm) {
this.storm = storm;
}
public Boolean getThunderstorm() {
return thunderstorm;
}
public void setThunderstorm(Boolean thunderstorm) {
this.thunderstorm = thunderstorm;
}
@Override
public void apply(BukkitContext context) {
Event event = context.getEvent();
World world = null;
if (event instanceof WeatherChangeEvent) {
world = ((WeatherChangeEvent) event).getWorld();
} else if (event instanceof WorldEvent) {
world = ((WorldEvent) event).getWorld();
}
if (world != null) {
if (storm != null) {
world.setStorm(storm);
}
if (thunderstorm != null) {
world.setThundering(thunderstorm);
}
}
}
}
@@ -0,0 +1,44 @@
// $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 UpdateWorldActionLoader extends AbstractNodeLoader<UpdateWorldAction> {
@Override
public UpdateWorldAction read(ConfigurationNode node) throws DefinitionException {
Boolean storm = node.getBoolean("set-storm");
Boolean thunderstorm = node.getBoolean("set-thunderstorm");
UpdateWorldAction action = new UpdateWorldAction();
action.setStorm(storm);
action.setThunderstorm(thunderstorm);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"set-storm", "set-thunderstorm");
return action;
}
}
@@ -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.worldguard.bukkit.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.Event;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class WeatherCriteria implements Criteria<BukkitContext> {
public enum Type {
STORM,
THUNDERSTORM,
}
private Set<Type> causes = new HashSet<Type>();
private Boolean isStarting = null;
public WeatherCriteria(Set<Type> causes) {
this.causes = causes;
}
public Set<Type> getCauses() {
return causes;
}
public void setCauses(Set<Type> causes) {
this.causes = causes;
}
public Boolean getIsStarting() {
return isStarting;
}
public void setIsStarting(Boolean isStarting) {
this.isStarting = isStarting;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
boolean startVal = true;
if (isStarting != null) {
startVal = event instanceof WeatherChangeEvent &&
((WeatherChangeEvent) event).toWeatherState() == isStarting;
}
if (event instanceof WeatherChangeEvent) {
return startVal && causes.contains(Type.STORM);
} else if (event instanceof ThunderChangeEvent) {
return startVal && causes.contains(Type.THUNDERSTORM);
} else {
return startVal;
}
}
}
@@ -0,0 +1,52 @@
// $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 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 WeatherCriteriaLoader extends AbstractNodeLoader<WeatherCriteria> {
private EnumLoaderBuilder<WeatherCriteria.Type> typeLoader =
new EnumLoaderBuilder<WeatherCriteria.Type>(WeatherCriteria.Type.class);
@Override
public WeatherCriteria read(ConfigurationNode node) throws DefinitionException {
Set<WeatherCriteria.Type> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
WeatherCriteria criteria = new WeatherCriteria(types);
criteria.setIsStarting(node.getBoolean("is-starting"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type", "is-starting");
return criteria;
}
}
@@ -0,0 +1,32 @@
// $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.resolvers;
import org.bukkit.block.BlockState;
import com.sk89q.rulelists.Context;
import com.sk89q.rulelists.Resolver;
public interface BlockResolver extends Resolver {
public static final String DEFAULT = "target";
public BlockState resolve(Context context);
}
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more