Compare commits

...
580 Commits
Author SHA1 Message Date
sk89q 9cf85caf3c Set version to 6.1. 2015-06-08 15:04:59 -07:00
sk89q 2f1343f408 Updated changelog for v6.1. 2015-06-08 15:04:52 -07:00
wizjany 3cb6c4e46f Check both attacker and defender locations for PvP.
Fixes WORLDGUARD-3494.
2015-06-08 14:37:32 -07:00
sk89q 7f9b850288 Always generate Javadocs and sources .jar. 2015-06-08 14:37:32 -07:00
sk89q e8d4f2fd84 Turn off doclint. 2015-06-08 14:37:32 -07:00
sk89q f3891aaaf9 Add a workaround for incorrect piston retract information. 2015-06-03 23:46:24 -07:00
wizjany ea75549a29 Clean up Heal and Feed flags.
Allow the flags to increase values for players who are invincible (or in creative mode),
but not decrease them.
Fixes WORLDGUARD-3492.
2015-06-04 02:02:53 -04:00
wizjany fbd8206038 Check for connected chests.
Fixes WORLDGUARD-3021.
2015-05-29 03:56:14 -04:00
wizjany 522ac459db Fix weather lock flag.
Probably. Maybe.
Fixes WORLDGUARD-3452.
2015-05-29 02:26:32 -04:00
wizjany 255dd2d41a Add support for Spigot's BlockExplodeEvent.
Also update Bukkit dependency and guava version quirks.
Fixes WORLDGUARD-3484.
2015-05-29 01:49:20 -04:00
wizjany cf1716ff37 Separate vehicles and animals from INTERACT flag.
Destroying vehicles now checks only the vehicle-destroy flag.
Damaging animals checks the new damage-animals flag.
These are both allowed for members by default, like other build-dependent flags.

Fixes WORLDGUARD-3427 and WORLDGUARD-3358.
2015-05-28 17:21:58 -04:00
sk89q a277e69e9c Get the session during the gamemode event lazily. 2015-05-28 11:28:02 -07:00
sk89q ec5bb32510 Add -s to show stack traces with the event debugging command. 2015-05-27 22:18:30 -07:00
Wizjany 8ddb7d4b99 Don't add a period for custom blacklist messages.
Fixes WORLDGUARD-3472
2015-05-02 22:38:42 -04:00
Wizjany 3258bff2d1 Fix CommandFilter matching emoticons etc.
Fixes WORLDGUARD-3461.
2015-04-18 12:01:21 -04:00
Wizjany 8d7d32a2d2 Check event cancellation before playing deny effect for bucket events. 2015-04-05 15:44:43 -04:00
Wizjany a907eb2348 Move repeaters/comparators from use to build.
This should mirror the protection given in WG 5.9.
2015-03-13 23:34:22 -04:00
wizjany 32132b5b0a Protect against spawn egg usage.
Fixes WORLDGUARD-3347.
2015-03-11 01:46:55 -04:00
wizjany c0c7c3215e Mark Player/Group Domains as dirty in a few missing places.
Fixes WORLDGUARD-3404.
2015-03-11 00:44:41 -04:00
Wizjany ddf0f41061 Actually register WorldRulesListener for events.
Fixes WORLDGUARD-3406.
2015-03-03 13:09:50 -05:00
Wizjany d3ecbcb18a Protect switching inverted daylight detectors too. 2015-02-28 18:39:54 -05:00
wizjany b7f4262978 Add comparators to USE too for consistency. 2015-02-19 21:21:17 -05:00
wizjany 60e6f92c64 Have repeaters be covered by the USE flag. 2015-02-19 21:17:45 -05:00
wizjany 98af7966cd Added weather-lock flag.
Valid values are clear or downfall. Unset to restore to normal world weather.
2015-02-18 02:24:31 -05:00
wizjany 99d042d260 Added time-lock flag.
Valid values are 0 to 24000 for absolute time, or +- any number for relative time.
Closes WORLDGUARD-3379.
2015-02-18 01:59:30 -05:00
wizjany c9d6166fcb Check for null task fields.
Fixes WORLDGUARD-3372.
2015-02-17 16:51:02 -05:00
sk89q 752ccec150 Don't call initialize() on non-cancellable movements.
Fixes WORLDGUARD-3362.
2015-02-11 17:12:10 -08:00
sk89q 91ccb95672 Add classloader override to the build POM. 2015-02-11 17:09:10 -08:00
wizjany 4caff457d3 Add Citizens NPCs to NPC detection for region whitelisting.
Fixes WORLDGUARD-3356.
2015-02-04 17:03:01 -05:00
wizjany a1a6ee7107 Fixed blocks (e.g. sugar canes) adjacent to physics blocks (e.g. sand) not updating.
Fixes WORLDGUARD-3367. This change MAY have breaking unintended consequences,
but the physics configs seem to still be working.
2015-02-04 03:33:37 -05:00
sk89q af157b88bd Handle empty sets in SetFlag. 2015-01-30 00:03:25 -08:00
sk89q ea4f4c088b Have enderchests be covered by the USE flag.
Fixes WORLDGUARD-3336.
2015-01-28 01:36:07 -08:00
sk89q 6559ed5c1a Have tripwire be covered by the USE flag.
Fixes WORLDGUARD-3351.
2015-01-28 01:35:17 -08:00
sk89q deddcf8dd2 Handle null block attacker.
Fixes WORLDGUARD-3350.
2015-01-28 01:26:50 -08:00
sk89q dfe536a2d2 Fix issues with MC 1.7 compatibility. 2015-01-28 01:11:36 -08:00
sk89q 5bfb348354 Add a fall-damage flag.
Closes WORLDGUARD-2279.
2015-01-28 01:01:43 -08:00
sk89q afcf93b7b1 Reset handler caches when a move type is non-cancellable. 2015-01-27 15:21:56 -08:00
sk89q e1843624bb Add exit-via-teleport flag (default allow). 2015-01-27 15:01:01 -08:00
wizjany 0f4e7b5061 Creeper explosions with a player target cause should no longer be ignored.
Also fixed primed tnt being checked twice for tnt flags. TNT Minecarts are not included, as was prior behavior.
Fixes WORLDGUARD-3344
2015-01-24 23:00:19 -05:00
wizjany 869ead63bc Fix armor stands to behave more like item frames.
Placing and modifying them respects permissions, and  they are no longer blocked by mob-spawning deny.
2015-01-24 17:02:55 -05:00
sk89q 6a6de7802b Fix missing material data for 1.8 items.
Fixes WORLDGUARD-3306.
2015-01-22 21:42:53 -08:00
sk89q b50302d9d0 Set version back to 6.0.0-SNAPSHOT. 2015-01-20 19:28:22 -08:00
sk89q c841d74aaf Set version to 6.0.0-beta-05. 2015-01-20 19:26:39 -08:00
sk89q 09cce39aff Update changelog for 6.0 beta 5. 2015-01-20 19:25:34 -08:00
sk89q e5b76a571b Always call boundary crossing handlers. 2015-01-20 19:24:55 -08:00
sk89q 7c58fa4be6 Add BukkitUtil.toRegion(Chunk).
Closes WORLDGUARD-3292.
2015-01-19 23:19:44 -08:00
sk89q f150a41d72 Ensure that region properties are immutable. 2015-01-19 23:11:28 -08:00
sk89q bca1c2bdb3 Fix region intersection tests involving polygons.
Fixes WORLDGUARD-3216.
2015-01-19 22:56:16 -08:00
sk89q 47a8bcc442 Floor components in getApplicableRegions(Location).
Fixes WORLDGUARD-3288.
2015-01-19 19:22:15 -08:00
sk89q 83cad75916 Fix /wg flushstates not doing anything. 2015-01-19 19:04:49 -08:00
sk89q 6b5a12105e Group together invincibility listeners.
Fixes WORLDGUARD-3315.
2015-01-19 19:03:54 -08:00
sk89q 451b679323 Track cause through targets.
Fixes WORLDGUARD-3314.
2015-01-19 18:28:41 -08:00
sk89q 66a8bfd5b1 Fix typo in region gamemode change log message. 2015-01-19 14:12:04 -08:00
sk89q 2a2b2f6f64 Limit the cause chain to 40 items. 2015-01-19 14:08:53 -08:00
sk89q 73dea11de2 Restore game mode flag logic to pre-refactor version.
Fixes WORLDGUARD-3320.
2015-01-19 13:23:23 -08:00
wizjany 9998a6c930 Restore Java 6 compatibility. 2015-01-19 15:01:43 -05:00
wizjany 5111d40aaf Add colorification to entry and exit messages as well. 2015-01-19 14:23:04 -05:00
sk89q 972ccaed7e Rename InteropUtil -> InteropUtils. 2015-01-19 11:20:53 -08:00
sk89q f7d36bc1f3 Protect enderchests as well. 2015-01-19 11:20:23 -08:00
sk89q 8073945af0 Fix color codes in greeting/farewell messages.
Fixes WORLDGUARD-3319.
2015-01-19 11:17:06 -08:00
sk89q 91353d6b01 Improve fake player detection. 2015-01-19 03:23:52 -08:00
sk89q bfbcc8dcf8 Fix a typo in the class source warning message. 2015-01-19 01:55:56 -08:00
sk89q 8f65798141 Check when plugins shade WorldGuard inappropriately. 2015-01-19 01:54:23 -08:00
sk89q fdddb17d2f TypeToken is not available on old Guava. 2015-01-17 19:26:33 -08:00
sk89q 520f9e3fcf Check movement with vehicle enter. 2015-01-17 19:25:15 -08:00
sk89q a3d2a1b127 Don't call boundary crossing handlers unless a boundary was crossed. 2015-01-17 19:17:17 -08:00
sk89q 7ecf73165b Handle entry flag only on boundary crossing. 2015-01-17 19:17:02 -08:00
sk89q e90a7ed075 Add new exit-override flag instead of fiddling with default exit flag values. 2015-01-17 19:13:25 -08:00
sk89q aae521b727 Rewrite session and movement flag code.
Also adds entry-deny-message and exit-deny-message.

Fixes WORLDGUARD-3086, WORLDGUARD-2542, WORLDGUARD-2731.
2015-01-17 18:54:10 -08:00
sk89q 643345b459 Add Locations.isDifferentBlock(). 2015-01-17 15:04:42 -08:00
sk89q a62d9f5617 Reuse set in RegionResultSet for getRegions(). 2015-01-17 14:29:14 -08:00
sk89q 2f3f76c8cf Funnel pre-allowed events too.
Fixes WORLDGUARD-3308.
2015-01-16 15:43:13 -08:00
sk89q a03aaa45b1 Revert "Have the PvP flag apply to self-attack."
This reverts commit d8dd86dfe8.

Fixes WORLDGUARD-3312.
2015-01-16 14:22:46 -08:00
sk89q 372155b5c3 Don't check player inventories for protection.
Fixes WORLDGUARD-3309, WORLDGUARD-3310.
2015-01-16 14:20:01 -08:00
sk89q 159de771bf Fix build perms item use event not working correctly. 2015-01-15 18:42:26 -08:00
sk89q 41d922cb27 Add special case for global regions in RegionOverlapAssociation too. 2015-01-15 16:49:07 -08:00
sk89q 6a4fac63e8 Change version back to 6.0.0-SNAPSHOT. 2015-01-13 12:44:17 -08:00
sk89q 3daf8db113 Bump to 6.0.0 beta 04. 2015-01-13 12:42:11 -08:00
sk89q 9c62a35e07 Update CHANGELOG for 6.0 beta 4. 2015-01-13 12:29:43 -08:00
sk89q 931f438b14 Add material flags for MC 1.8.
Fixes WORLDGUARD-3306.
2015-01-13 12:19:53 -08:00
sk89q 3109612c1b Expand the USE flag to cover 1.8 doors and gates.
Fixes WORLDGUARD-3304.
2015-01-13 12:12:12 -08:00
sk89q e4d63ffbcc Permit org.json.simple package usage. 2015-01-13 03:24:00 -08:00
sk89q 866a554d30 Shade JSON simple. 2015-01-13 03:23:49 -08:00
sk89q ab2811ed2d Remove boot class / library path report values. 2015-01-13 03:19:47 -08:00
sk89q 8cc7bcc849 Improve report output. 2015-01-13 02:44:58 -08:00
sk89q 547e89b85d Add CPU profiling with WarmRoast "lite." 2015-01-13 01:49:59 -08:00
sk89q 477f1188df Use EH pastebin and remove debug code. 2015-01-12 22:19:49 -08:00
sk89q d9e4b27cd2 Handle PlayerInteractAtEntityEvent again.
Fixes WORLDGUARD-3291.
2015-01-11 02:34:12 -08:00
sk89q 37f39eaf66 Use a less coarse can-interact-on-click check.
Fixes WORLDGUARD-3303.
2015-01-11 02:05:31 -08:00
sk89q 223d22e79f Fire UseEntityEvent for InventoryOpenEvent for entities. 2015-01-11 00:10:52 -08:00
sk89q 04214a96eb Ignore unknown cause entity damage.
Fixes WORLDGUARD-3293.
2015-01-11 00:08:41 -08:00
sk89q f40cb69f38 Ignore unknown cause hanging breaks.
Fixes WORLDGUARD-3301.
2015-01-11 00:05:07 -08:00
sk89q 6c1489d434 Make NormativeOrders non-instantiable. 2015-01-10 23:44:31 -08:00
sk89q 6fe63838f5 testState(relevant flags) == DENY on whitelist cases.
Fixes WORLDGUARD-3294.
2015-01-10 23:31:24 -08:00
sk89q d883c22d64 Document flag classes and make BUILD slightly less magic. 2015-01-10 23:15:32 -08:00
sk89q 3bd1c869f1 Sort applicable regions by inheritance too. 2015-01-10 22:45:15 -08:00
sk89q e7273aaf6f ALLOW on a child region should override DENY on a parent. 2015-01-10 18:37:28 -08:00
zml 6e02f80f6c Pass Player objects during WEPIF permission checks 2015-01-10 16:14:17 -08:00
sk89q 01276dfc62 Fix incorrect region group inheritance and broken flag override in children. 2015-01-09 13:21:17 -08:00
sk89q f516fd5e54 Have on-acquire also check inventory transfers.
Fixes WORLDGUARD-2752.
2015-01-08 15:43:02 -08:00
sk89q 79612915a7 Fix NPE caused by flag value permissions. 2015-01-08 14:29:06 -08:00
sk89q f04f9093bc Add &r as a reset color code.
Closes WORLDGUARD-3286.
2015-01-08 13:40:57 -08:00
sk89q 9dac950faf Fix a little typo in the UPGRADE document. 2015-01-08 11:58:20 -08:00
sk89q f2a8ff3f64 Add missing wood plate to USE flag. 2015-01-08 11:25:19 -08:00
sk89q b78317dd42 Add color code support to the blacklist.
Fixes WORLDGUARD-3284.
2015-01-08 11:24:22 -08:00
sk89q 048dd25099 Remove outdated information in the upgrade document. 2015-01-08 01:14:12 -08:00
sk89q 0900289437 Add permissions for individual flag values.
Closes WORLDGUARD-3103.
2015-01-08 01:04:36 -08:00
sk89q d8dd86dfe8 Have the PvP flag apply to self-attack.
Closes WORLDGUARD-3278.
2015-01-08 00:35:30 -08:00
sk89q 9a569d7ed8 Don't throw internal DamageEntityEvents for unknown cause entity combusts.
Fixes WORLDGUARD-3277.
2015-01-08 00:32:57 -08:00
sk89q 53132ce83a Add support for slightly older versions of Bukkit 1.7.9. 2015-01-08 00:25:07 -08:00
sk89q c3bdc33215 Set version to 6.0.0-SNAPSHOT. 2015-01-07 18:51:07 -08:00
sk89q c6bf8ceb5c Bump version to 6.0.0-beta-03. 2015-01-07 18:49:34 -08:00
sk89q 792d041078 Update CHANGELOG. 2015-01-07 18:48:58 -08:00
sk89q cb965c9bf9 Update the UPGRADE document. 2015-01-07 18:42:57 -08:00
sk89q f33889b88f Support both MC 1.7.10 and 1.8. 2015-01-07 18:07:30 -08:00
sk89q e747e3a3fa Bump Bukkit dependency to 1.7.9-R0.3-SNAPSHOT. 2015-01-07 16:28:26 -08:00
sk89q fd460337f4 Don't apply the region override permission to PvP. 2015-01-06 15:14:30 -08:00
sk89q 38c9479385 Fix incorrect detection of hostile and ambient creatures. 2015-01-06 15:01:07 -08:00
sk89q da032cb04e Fix the splash potion flag not working with the other flags.
Fixes WORLDGUARD-3274.
2015-01-06 15:00:54 -08:00
sk89q 37a80338f5 Adjust USE flag material filter to include the proper items. 2015-01-05 13:31:14 -08:00
sk89q 8a5f233e84 Use an interact event for non-damaging splash potions.
Fixes WORLDGUARD-3184.
2015-01-04 19:54:34 -08:00
sk89q e3a9131929 Fix potion blocking.
Fixes WORLDGUARD-3207
2015-01-04 19:43:55 -08:00
sk89q bab98d5463 Fix broken recursive dump in DataReport. 2015-01-04 19:19:53 -08:00
sk89q 4333b39377 Consider enchantment table + workbench MODIFIED_ON_CLICK. 2015-01-04 19:13:07 -08:00
sk89q 8bd427a6ab Make PASSTHROUGH=DENY useful on __global__. 2015-01-04 18:58:00 -08:00
sk89q d3493a3361 Fix missing __global__ constant. 2015-01-04 18:51:32 -08:00
sk89q 51982cda28 Do a better check of the global region. 2015-01-04 18:51:18 -08:00
sk89q a2e14bc76a Fix issues caused by adding members to __global__.
Fixes WORLDGUARD-3195.
2015-01-04 18:44:57 -08:00
sk89q c050d274f5 Make the EXP_DROPS flag a build-compat flag and set its deny message.
Fixes WORLDGUARD-3231.
2015-01-04 18:26:11 -08:00
sk89q bdff22cbac Give the player back his/her XP bottle if it was blocked. 2015-01-04 18:20:33 -08:00
sk89q 7da10198e3 Expand interaction whitelist to "physical" events.
Closes WORLDGUARD-3238.
2015-01-04 18:05:50 -08:00
sk89q b11e2b3d11 Catch command prefixes in the filter.
Fixes WORLDGUARD-3196.
2015-01-04 17:56:00 -08:00
sk89q c95b619974 Add a RIDE flag for vehicles. 2015-01-04 17:52:32 -08:00
sk89q e61b2e18c1 Also permit hoppers. 2015-01-04 16:09:57 -08:00
sk89q e9d64dbf03 Check for names in addition to UUIDs with /rg list. 2015-01-04 14:25:04 -08:00
sk89q 3c8121d088 Whitelist hoppers and let them cross regions regardless of permissions. 2015-01-04 13:57:03 -08:00
sk89q 93ced5ca7a Revert USE flag's functionality to 5.x, add new INTERACT flag. 2015-01-04 13:50:48 -08:00
sk89q 7580583fbf Fix spawn egg blocking.
Closes WORLDGUARD-3254.
2014-12-31 02:30:58 -08:00
sk89q 41c68664d7 Fix failed detection of incorrect blacklist names. 2014-12-31 02:30:31 -08:00
sk89q c8393cdcec Fix bypass with the block op configuration. 2014-12-31 02:13:35 -08:00
sk89q 42d12e4fa8 Reorganize some packages. 2014-12-31 02:05:47 -08:00
sk89q bed9bd77a6 Merge pull request #336 from ST-DDT/configLoadExceptions
Show more details in error log which world the error belongs to.
2014-12-31 01:59:57 -08:00
sk89q f3c2390fbb Attempt to clean up the move listener. 2014-12-31 01:41:41 -08:00
sk89q 83a7ed58a5 Cache bypass permission checks in the move listener.
Some permission plugins are slow.
2014-12-31 01:39:11 -08:00
sk89q ddc1f77825 Move move listener to a new class. 2014-12-31 01:31:30 -08:00
sk89q 88169236cb Rewrite and update report generation. 2014-12-31 01:18:23 -08:00
sk89q 0cb36b3b8b Remove ArrayReader and FatalConfigurationLoadingException. 2014-12-30 22:37:54 -08:00
sk89q ce169461a3 Add event cancellation debug commands. 2014-12-30 20:05:42 -08:00
sk89q 18ec3db1bb Modernize pastebin code. 2014-12-30 17:41:56 -08:00
sk89q 53fdff1d9b Add hack to make Location flags work with unloaded worlds. 2014-12-29 16:35:22 -08:00
ST-DDT 9a91336958 Show more details in error log which world the error belongs to. 2014-12-19 13:55:18 +01:00
sk89q 7bd69bebf4 Add missing color codes when parsing input. 2014-11-14 12:57:38 -08:00
sk89q 57b6f04b79 Let players use NPCs always.
Fixes WORLDGUARD-3190.
2014-11-11 00:32:42 -08:00
sk89q c7442c2a9e Fix [WorldGuard] in log messages stacking on reloads.
Fixes WORLDGUARD-3192.
2014-11-11 00:29:25 -08:00
sk89q df985013eb Handle null EntityTypes from SpawnEggs.
Fixes WORLDGUARD-3179.
2014-11-11 00:02:54 -08:00
sk89q 41f520845a Better handle empty group / player names due to bad region data.
Fixes WORLDGUARD-3182.
2014-11-10 23:59:57 -08:00
sk89q dac09c64c8 Fix players being invincible with BUILD = deny.
Fixes WORLDGUARD-3201.
2014-11-10 23:56:11 -08:00
sk89q a2defe5971 Fix certain entities not being damaged in protected regions. 2014-11-10 23:52:53 -08:00
sk89q ba4e5d6ea9 Improve entity detection in Entities utility class, add Entities.isNonPlayerCreature(). 2014-11-10 23:52:53 -08:00
sk89q 25f12e9733 Remove CraftBukkit runtime dependency in pom.xml. 2014-09-18 20:32:59 -07:00
sk89q ca37dc0fc6 Merge pull request #328 from zreed/master
Add missing SQL table prefix in statement selecting world names.
2014-09-02 23:30:26 -07:00
zreed 7d41835794 Add missing SQL table prefix in statement selecting world names. 2014-09-02 17:05:28 -04:00
sk89q b37014463f Reset version back to 6.0.0-SNAPSHOT. 2014-08-31 20:04:04 -07:00
sk89q 2b94883e70 Bump version to 6.0.0-beta-02. 2014-08-31 19:58:10 -07:00
sk89q 5c7468ffb5 Remove "multiple categories" point about related flags handling. 2014-08-31 19:55:32 -07:00
sk89q 343632cbf2 Update changelog for 6.0 beta 2. 2014-08-31 19:54:27 -07:00
sk89q 2a3ccec429 Fix boat placement not being properly prevented.
Fixes WORLDGUARD-3174.
2014-08-31 19:36:39 -07:00
sk89q d6f12804ea Don't show a deny message if it's an empty string. 2014-08-31 19:35:13 -07:00
sk89q f858c175f9 Add -e flag to /rg flag to set a flag to an empty value.
Closes WORLDGUARD-3161.
2014-08-31 19:34:55 -07:00
sk89q cdab004505 Add option to consider use of an item as a block use at the player's feet.
Closes WORLDGUARD-3151.
2014-08-31 19:30:14 -07:00
sk89q 59bd11e742 Don't use deny effects for entities because they look bad. 2014-08-31 19:18:32 -07:00
sk89q 2e6faff8c1 Add option to whiteist some blocks / items so they can always be used.
Closes WORLDGUARD-3159.
2014-08-31 19:17:05 -07:00
sk89q 722cc2e38c Block polygonal regions for claiming for now.
volume() returns 0.
2014-08-31 19:05:59 -07:00
sk89q 669c0e9651 Add more deny effects.
Closes WORLDGUARD-3158.
2014-08-31 19:00:45 -07:00
sk89q d2252c6142 Warn about claim volume setting being too high. 2014-08-31 18:42:43 -07:00
sk89q eab4101d1c Consider XP drops under ITEM_PICKUP.
Fixes WORLDGUARD-3171.
2014-08-31 18:38:04 -07:00
sk89q db31c35d8e Don't consider vehicles a known cause.
Fixes WORLDGUARD-3170.
2014-08-31 18:33:14 -07:00
sk89q 125595e6b9 Fix mobs not being able to attack players regardless of permission.
Fixes WORLDGUARD-3172.
2014-08-31 18:28:50 -07:00
sk89q 6d5d9934cc Fix Enums.findFuzzyByValue() not handling _ correctly. 2014-08-31 18:21:58 -07:00
sk89q bd2a8daad3 Fix sapling + bonemeal considered as usage rather than building.
Fixes WORLDGUARD-3169.
2014-08-31 18:21:22 -07:00
sk89q c4b3c1d033 Destroy sapling if some of its blocks could be placed.
Fixes WORLDGUARD-3168.
2014-08-31 18:08:13 -07:00
sk89q eb051bc194 Set MODIFIES_BLOCKS flag on ink dye.
Fixes WORLDGUARD-3167.
2014-08-31 18:03:52 -07:00
sk89q 1a12faf5ab Fix trees not growing naturally in protected regions.
Fixes WORLDGUARD-3166.
2014-08-31 17:52:03 -07:00
sk89q 73fe9cd62f Debounce piston events and add a deny effect.
Fixes WORLDGUARD-3157.
2014-08-31 17:39:01 -07:00
sk89q 7ab4a283fe Document the delegate events.
Fixes WORLDGUARD-3164.
2014-08-31 16:10:11 -07:00
sk89q 46138c9abe Merge pull request #304 from stuntguy3000/master
Add silent (s) and information (i) flags to /stoplag.
2014-08-31 16:06:25 -07:00
sk89q 841cc8e033 Don't apply USE to hanging entities. 2014-08-29 21:51:55 -07:00
sk89q cb0844c64d Ignore _ when fuzzy searching enums. 2014-08-29 12:38:43 -07:00
sk89q 6e8e59aee5 Check Material in TargetMatcherParser. 2014-08-29 12:38:27 -07:00
sk89q 358eebf96b Mention Spigot issue with settings.global-api-cache. 2014-08-29 12:32:33 -07:00
sk89q 01892b609f Have other flags override BUILD but not the other way like in WG 5. 2014-08-29 12:18:01 -07:00
sk89q 096981bd27 Fix condition error in handling of PVP flag. 2014-08-29 12:18:01 -07:00
sk89q 0852fc0d65 Have membership override BUILD=DENY like in WG 5. 2014-08-29 12:18:00 -07:00
sk89q 40ceb3d0b8 Fix NPE when handling PlayerFishEvent.
Fixes WORLDGUARD-3149.
2014-08-25 14:18:26 -07:00
sk89q b52a6bd6d6 Ignore sneaking when checking the events. 2014-08-25 00:29:37 -07:00
sk89q 992e53856d Add some deny effects. 2014-08-25 00:28:26 -07:00
sk89q f776d15e03 Allow right clicking hostile mobs in protected regions too.
Fixes WORLDGUARD-3144.
2014-08-25 00:09:29 -07:00
sk89q 438bc59fbc Silence spam from not being able to walk on crops.
Fixes WORLDGUARD-3143.
2014-08-25 00:05:44 -07:00
sk89q 453f253e77 Remove outdated line in UPGRADE about flags and BUILD. 2014-08-24 18:52:02 -07:00
sk89q 550df20f18 Set version back to 6.0.0-SNAPSHOT. 2014-08-24 18:44:01 -07:00
sk89q e8ee0a8c5b Bump version to 6.0.0-beta-01. 2014-08-24 18:42:39 -07:00
sk89q 5fcd7ddf7a Handle multiple related flags more like in WG 5. 2014-08-24 18:34:14 -07:00
sk89q b11d416035 Revert the default region groups of the entry/exit flags back to WG 5. 2014-08-24 18:11:25 -07:00
sk89q f7e216ba84 Mention how to report bugs in the UPGRADE document. 2014-08-24 18:03:52 -07:00
sk89q f6406b668c Silence messages about touching Redstone ore. 2014-08-24 17:56:15 -07:00
sk89q 7cd4a1d411 Update CHANGELOG and UPGRADE documents. 2014-08-24 17:15:36 -07:00
sk89q bd558bb527 Change .interact to .use for item use permission. 2014-08-24 17:14:34 -07:00
sk89q 8d29f6971a Allow hitting hostile mobs in protected regions. 2014-08-24 17:13:27 -07:00
sk89q 300f69597f Don't cause item loss when the hopper is destroyed. 2014-08-24 17:06:13 -07:00
sk89q 8e320b6dbe Add helper ProtectionQuery class for other plugins. 2014-08-24 17:01:52 -07:00
sk89q fa422bef32 Update UPGRADE document with more information. 2014-08-24 16:38:31 -07:00
sk89q e8cd1cc253 Block spawn eggs properly. 2014-08-24 16:26:15 -07:00
sk89q 5e9ffe9e29 Better describe issue regarding flags being evaluated together. 2014-08-24 15:58:34 -07:00
sk89q edebb0efc9 Be more lax with entity spawns. 2014-08-24 15:53:45 -07:00
sk89q 913d5d64ae Break denied hoppers. 2014-08-24 15:40:00 -07:00
sk89q 6da8fabb1f Debounce the inventory move item event better. 2014-08-24 15:36:38 -07:00
sk89q ee022d7cd7 Handle inventory move event for protection. 2014-08-24 15:24:52 -07:00
sk89q c126a0ac38 Change potion splash to damage event. 2014-08-24 14:46:55 -07:00
sk89q 4a3dac0aa4 Ignore cancelled events in event abstraction. 2014-08-24 14:39:44 -07:00
sk89q f4700ded12 Don't block self-damage if PVP is denied. 2014-08-24 14:33:29 -07:00
sk89q 8570921049 Mention incompatible plugins in the upgrading document. 2014-08-24 14:22:29 -07:00
sk89q 612b953b63 Don't use empty names when loading the YAML regions file. 2014-08-24 14:13:12 -07:00
sk89q 02777c370d Mention use on-place and water / lava buckets. 2014-08-24 14:02:38 -07:00
sk89q 7a8ab1df99 Fire a use item event on placed blocks. 2014-08-24 13:45:39 -07:00
sk89q 182c5f6a17 Clamp cuboid volume to Integer.MAX_VALUE and handle overflow. 2014-08-24 12:55:44 -07:00
sk89q 7c7673af20 Debounce entity break block events. 2014-08-24 12:36:17 -07:00
sk89q 9282fc25de Fix fire handling in the event abstraction listener. 2014-08-24 12:25:29 -07:00
sk89q f66e47c01f If the cause is unknown, use NON_MEMBER as the association. 2014-08-24 02:56:23 -07:00
sk89q f00d73d60e Cause.isKnown() now returns false if it only contains objects that do not properly constitute a cause. 2014-08-24 02:55:57 -07:00
sk89q c5b08781f7 Build the cause list order correctly. 2014-08-24 02:49:58 -07:00
sk89q 4b80c4e4e6 Clean up EventAbstactionListener. 2014-08-24 02:35:09 -07:00
sk89q 7da3cc224b Fix buckets not being checked properly. 2014-08-24 02:26:09 -07:00
sk89q 0659a5263a Fix typos in readme files. 2014-08-24 02:20:51 -07:00
sk89q 0f8614519f Fix /wg reload sometimes not applying new changes right away. 2014-08-24 02:14:15 -07:00
sk89q 541f828db4 Add optional build permission nodes. 2014-08-24 02:03:38 -07:00
sk89q 70aedb4a84 Mention the need to re-check the upgrade document. 2014-08-24 01:19:46 -07:00
sk89q 4f24f2631e Automatic invincibility / no-drowning groups have to be enabled now. 2014-08-24 01:13:59 -07:00
sk89q ddb910e2ea Update the README. 2014-08-23 22:15:10 -07:00
sk89q b5c4eb3587 Move build related files to config/. 2014-08-23 22:05:41 -07:00
sk89q a0553bfa34 Have people read CHANGELOG for the rest of the changes. 2014-08-23 22:02:46 -07:00
sk89q 241f053b8a Fix error in CHANGELOG.md. 2014-08-23 21:57:52 -07:00
sk89q 6174c9e486 Updated changelog and added upgrade information. 2014-08-23 21:55:49 -07:00
sk89q d7629acb61 Use original .jar filename in the .zip. 2014-08-23 20:25:30 -07:00
sk89q 8169b6f650 Use Markdown for changelog + distributed README. 2014-08-23 20:24:25 -07:00
sk89q 7b174683ba WorldGuard 6. See http://forum.enginehub.org/threads/15666/ 2014-08-22 20:54:59 -07:00
sk89q 88e7327af6 Merge branch 'master' into feature/region-api-update 2014-08-22 20:48:34 -07:00
sk89q b7d8562ece Use a region deny message indicating region data load failure. 2014-08-22 20:43:03 -07:00
sk89q 439826ddc6 Bump to version 6.0.0. 2014-08-22 19:52:16 -07:00
sk89q b94641f1b5 Wooden doors are interact-able. 2014-08-22 19:47:37 -07:00
sk89q 0ddf56f7f6 Add -g to /rg (re)define to create a global region. 2014-08-22 19:37:13 -07:00
sk89q 74e64d0641 Fix region bypass permission and support fake players. 2014-08-22 19:32:03 -07:00
sk89q 858b0b2c1c Update Javadocs in RegionQuery. 2014-08-22 19:19:35 -07:00
sk89q 54237c0038 Fix potential NPE in FlagValueCalculator. 2014-08-22 19:17:46 -07:00
sk89q 0edb948a40 Don't let players disembark if they can't back on. 2014-08-22 19:17:36 -07:00
sk89q f85aeecde7 Fix deny flags not applying when you are on an animal.
Fixes WORLDGUARD-2518.
2014-08-22 18:23:59 -07:00
sk89q 69a0f26a52 Handle OfflinePlayer causes. 2014-08-22 18:04:01 -07:00
sk89q 8bb28b5ef1 Update Bukkit dependency on 1.7.9-R0.2. 2014-08-22 18:03:48 -07:00
sk89q a6118c3aa4 Unify debouncing method. 2014-08-22 17:30:18 -07:00
sk89q 59494233e3 Debounce interact events. 2014-08-22 17:21:49 -07:00
sk89q d0ff1815aa Made EventDebounce more reusable. 2014-08-22 16:52:34 -07:00
sk89q 9b7970475a Fix the SLEEP flag not checking the right bed material. 2014-08-22 16:26:43 -07:00
sk89q 88c0bdfffb Better handle disabling of the regions feature. 2014-08-22 16:18:05 -07:00
sk89q b43bc4a57a Debounce events for 10 seconds. 2014-08-22 16:10:22 -07:00
sk89q bd8e1a35f6 Add block place, block break flags. 2014-08-22 16:08:31 -07:00
sk89q 722dabcf1a Add item pickup flag and implement item drop flag through event abstraction. 2014-08-22 16:02:21 -07:00
sk89q 09207367c0 Use specific messages for denied item drop / pick up. 2014-08-22 15:45:05 -07:00
sk89q 3336b73536 Don't send too many "can't do this" messages at a time. 2014-08-22 15:43:03 -07:00
sk89q 0d7e3ad2de Add friendlier region deny messages. 2014-08-22 15:36:21 -07:00
sk89q 95d1bd8ee0 Debounce item pickup event. 2014-08-22 13:54:59 -07:00
sk89q 6c97e04c7c Use event abstraction for blacklist item pickup. 2014-08-22 13:45:55 -07:00
sk89q 24f72cb07f Make liquid flow checking for regions optional. 2014-08-22 13:37:02 -07:00
sk89q ef56a32f00 Implement PVP flag through abstraction. 2014-08-22 12:47:06 -07:00
sk89q d8da89703b Handle the TNT flag better in the new system.
Now the build flag works in tandem with the TNT flag.
2014-08-22 11:27:23 -07:00
sk89q e47c563ced Handle null flag values in the flag set command correctly. 2014-08-22 11:09:09 -07:00
sk89q bd0917d34b Add deny-message flag to adjust the region "don't have permission" message.
Also add color code parsing for the flag set command.
2014-08-22 03:37:33 -07:00
sk89q 8098211d01 Add Flag.getDefault(). Breaks StateFlag.getDefault() calls. 2014-08-22 02:19:31 -07:00
sk89q 83c95bbb8c Clear dirty flag if RegionManager.save() is used. 2014-08-22 02:08:59 -07:00
sk89q 4d4e1c6c26 Handle region data load / save failure more gracefully.
Also remove use of BoneCP and reorganize the classes.
2014-08-22 02:08:37 -07:00
sk89q 3045dc0293 Better handle failure conditions for background region saving. 2014-08-21 23:36:15 -07:00
sk89q e649973318 Revert "Don't use the region chunk has table until a threshold."
This reverts commit f57afb2944.
2014-08-21 22:49:53 -07:00
sk89q 2d147bb7e1 Change PriorityRTreeIndex to use the R-tree for intersection queries. 2014-08-21 22:47:46 -07:00
sk89q f57afb2944 Don't use the region chunk has table until a threshold. 2014-08-21 22:39:32 -07:00
sk89q 95052546a5 Remove use of Bukkit logger. 2014-08-21 22:22:28 -07:00
sk89q 768532cb8b Re-implemented region data migration. 2014-08-21 22:00:27 -07:00
sk89q 6b7e1286f2 Merge pull request #326 from parryjacob/master
Remove zml-repo from pom.xml as it longer resolves.
2014-08-19 20:11:17 -07:00
parryjacob 577cfd0954 Remove zml-repo from pom.xml as it failed to resolve anymore, causing Maven builds to have to wait for extended periods of time 2014-08-19 20:54:00 -04:00
sk89q 06df4585c2 Cleanup formatting of RegionProtectionListener. 2014-08-19 00:10:40 -07:00
sk89q 416006dbde Route XP drops through the event abstraction. 2014-08-18 23:56:39 -07:00
sk89q 5ff9f5c175 Reduce the number of internal events for EXPERIENCE_ORB. 2014-08-18 23:33:45 -07:00
sk89q fa14184eb4 Move PISTONS flag to RegionFlagsListener. 2014-08-18 23:32:37 -07:00
sk89q d29f66563b Add region support check in RegionProtectionListener. 2014-08-18 23:31:52 -07:00
sk89q 53957e7b26 Add Cause.getFirstBlock(). 2014-08-18 23:31:19 -07:00
sk89q 2c81cb2f84 Add isRegionSupportEnabled(World) to AbstractListener. 2014-08-18 23:31:09 -07:00
sk89q 711fe7ad2f Add Materials.isPistonBlock(). 2014-08-18 23:30:36 -07:00
sk89q f6f94571ea Handle pistons in the event abstraction. 2014-08-18 21:37:41 -07:00
sk89q 985629c196 Create RegionFlagsListener and rename some methods. 2014-08-18 19:15:40 -07:00
sk89q bb64079d17 Raise SpawnEntityEvent for BlockExpEvent. 2014-08-18 18:56:07 -07:00
sk89q c3363f0d70 Disable sponge simulation by default.
Vanilla Minecraft will have sponges again, plus it is uses up CPU time even if players can't get sponges.
2014-08-18 12:32:28 -07:00
sk89q 937a5758f7 Don't perform spatial queries for location->location checks until needed. 2014-08-18 11:26:02 -07:00
sk89q bb1826bdb1 Cache the set made in ApplicableRegionSet. 2014-08-18 11:04:36 -07:00
sk89q 1a781fc5b0 Try last ChunkState accessed in ChunkHashTable. 2014-08-18 10:57:02 -07:00
sk89q 039d174477 Reduce the number of BlockFromTo events handled. 2014-08-18 10:40:09 -07:00
sk89q 929f9e99cd Catch FileNotFoundException in YamlFileStore. 2014-08-18 10:39:53 -07:00
sk89q ae8bf63c86 Remove use of ObjectArrays.concat() in ApplicableRegionSet. 2014-08-18 03:05:06 -07:00
sk89q 3eb5c65a3d Throw IllegalArgumentException if trackParentCause() is given a Block. 2014-08-18 02:35:41 -07:00
sk89q 095f2aa67e Don't check region group if the flag value is null. 2014-08-18 02:32:05 -07:00
sk89q 0f10e89f7c Add getConfig() to AbstractListener. 2014-08-18 02:23:33 -07:00
sk89q 3a2b453e3f Change some collections and cache player names. 2014-08-17 20:17:52 -07:00
sk89q c43a24d78f Abandon TreeSet in ApplicableRegionSet for performance reasons. 2014-08-17 19:18:21 -07:00
sk89q d43eb3bc34 Optimize the query cache a bit. 2014-08-17 19:08:20 -07:00
sk89q 3ca147e405 Don't check metadata on Blocks in Cause.
We don't track causes on Blocks. There's no need for the performance hit.
2014-08-17 15:23:34 -07:00
sk89q 41fb8a0722 Implement Associables to handle non-player region membership checks. 2014-08-17 13:16:45 -07:00
sk89q ff3fa759d1 Don't throw an internal block break event when lighting TNT. 2014-08-17 00:49:50 -07:00
sk89q cab42af53b Reimplemented the quirks of the old flag code. 2014-08-17 00:49:32 -07:00
sk89q d9d665ab14 Add some extra tests to ApplicableRegionSetTest. 2014-08-16 21:09:12 -07:00
sk89q fac6ebef40 Implement new methods for accessing flags. 2014-08-16 21:09:01 -07:00
sk89q a4fd29c30c Switch SquirrelID version to 0.1.0. 2014-08-16 21:08:18 -07:00
sk89q 59c7197229 Fix Maven accessing dead repositories. 2014-08-16 21:08:17 -07:00
sk89q e7c9703ced Fix checkstyle issues. 2014-08-16 21:08:17 -07:00
sk89q 5a63115fb2 Don't make membership always override the BUILD flag anymore. 2014-08-16 21:08:17 -07:00
sk89q 4597849466 Allow __global__ BUILD to be set to DENY. 2014-08-16 13:55:54 -07:00
sk89q a35aaf9659 Force __global__ BUILD flag to NONE.
This is due to the legacy reason of the global region having not
been previously processed as a regular region.
2014-08-16 13:54:04 -07:00
sk89q bfb3f9e840 Change state flag defaults to true. 2014-08-16 13:45:16 -07:00
sk89q 91e34601ec Add supervisor/task library in. 2014-08-16 13:42:14 -07:00
sk89q 7481acba8c Updated FlagValueCalculator to treat global regions a lowest priority region. 2014-08-16 13:30:58 -07:00
sk89q 4d43ef5305 Change flags to use ALL as their region group. 2014-08-16 13:08:09 -07:00
sk89q b1fb143fd4 Add a new (unused for now) flag value implementation.
It supports region groups and fixes inconsistency issues.
2014-08-16 02:42:02 -07:00
sk89q d07e81288a Make the state flag test use a Predicate for membership testing. 2014-08-15 14:16:05 -07:00
sk89q c0d4ba5c6c Swap the if() in the state flag test to make it more readable. 2014-08-15 13:54:33 -07:00
sk89q 8a11752253 Fix a typo in ApplicableRegionSet and improve docs. 2014-08-15 12:41:28 -07:00
sk89q 1d24be8c34 Rewrite state calculation in ApplicableRegionSet to be easier to read. 2014-08-15 12:30:37 -07:00
sk89q d3f3489c7e Fix child regions not inheriting parent flags.
This also fixes a unit test.
2014-08-15 03:48:25 -07:00
sk89q 3f16fef57e Fix and improve protection handlers. 2014-08-15 01:43:37 -07:00
sk89q 608d782321 Activate debugging listener of the property "worldguard.debug.listener" is true. 2014-08-14 22:23:47 -07:00
sk89q 5d6dad4c6d Don't remove child regions without warning.
Also add some missing files.

Fixes WORLDGUARD-2311.
2014-08-14 21:41:44 -07:00
sk89q 28c538e981 Refactor region commands and make the necessary ones run in the background. 2014-08-14 21:24:32 -07:00
sk89q a35cb9277e Handle CommandException in WorldGuardPlugin.convertThrowable(). 2014-08-14 21:24:02 -07:00
sk89q e43ce420a3 Make UUID detection in DomainInputResolver reusable. 2014-08-14 21:23:26 -07:00
sk89q 501a7aa77a Add ProtectedRegion.copyFrom(). 2014-08-14 21:22:39 -07:00
sk89q 76f7ac8d8e Remove deprecation on getRegion() in RegionManager. 2014-08-14 21:22:15 -07:00
sk89q 518d5958c9 Update some region commands to run in the background. 2014-08-14 16:21:10 -07:00
sk89q 7e25de38da Update Javadocs in RegionContainer. 2014-08-14 15:20:08 -07:00
sk89q bf8ef39871 Handle null players in shim method of GlobalRegionManager. 2014-08-14 15:17:00 -07:00
sk89q cd62af698b Change listeners to use the region query cache. 2014-08-14 14:52:11 -07:00
sk89q 709ce9eb08 Fix a typo in some Javadocs. 2014-08-14 02:46:19 -07:00
sk89q e24d7ccb10 Change "don't have permission" message for regions. 2014-08-14 02:44:42 -07:00
sk89q 98bbd900cb Rename RegionQuery.testEnabled() -> testState(). 2014-08-14 02:39:42 -07:00
sk89q 19b87b628a Remove use of GlobalRegionManager in RegionProtectionListener. 2014-08-14 02:39:12 -07:00
sk89q dc2652f87b Implement an ApplicableRegionSet cache. 2014-08-14 02:33:57 -07:00
sk89q 99660920d7 Refactor region API with new RegionContainer object. 2014-08-14 01:24:38 -07:00
sk89q ad1c10a3e9 Reorganize Bukkit portion of the region API. 2014-08-13 14:06:37 -07:00
sk89q 5b685e71d3 Add ChunkHashTable.awaitCompletion(). 2014-08-13 07:51:13 -07:00
sk89q 5ddc4b9251 Properly convert chunk coordinates in ChunkHashTable. 2014-08-13 01:02:55 -07:00
sk89q 38587a1c61 Add a hash table index for regions that hashes on chunk coordinates. 2014-08-13 00:34:36 -07:00
sk89q eb23e28c16 Handle Tameable as a cause. 2014-08-12 23:17:36 -07:00
sk89q 4379c7e989 Handle Vehicle.getPassenger() as a parent cause. 2014-08-12 23:15:47 -07:00
sk89q 989ce82c5d Merge branch 'feature/event-abstraction' into feature/region-api-update 2014-08-12 19:49:52 -07:00
sk89q f92e55e061 Simplfy Cause objects. 2014-08-12 19:48:20 -07:00
sk89q 0fc3d21b90 Add abstracted event debugging listener. 2014-08-11 20:08:56 -07:00
sk89q 26d3645f86 Improve level of event listening. 2014-08-11 20:08:38 -07:00
sk89q 110aa2e56b Clean up docs / code for utility classes. 2014-08-11 17:54:55 -07:00
sk89q 05369b69b6 Reorganize classes into different packages. 2014-08-11 17:51:00 -07:00
sk89q 4a501a49db Abstract events for regions and blacklists further. 2014-08-11 17:48:40 -07:00
sk89q 2a69d1c7c9 Merge pull request #324 from Torm/master
Fix heal command for players with more health than 20
2014-08-10 21:03:28 -07:00
Torm 573204caad Fix heal command for players with more health than 20 2014-08-11 00:02:26 +02:00
sk89q 7a01168781 Rewrite region API. Migrations need to be re-implemented.
This commit, however, adds:

* Better support for background saves and loads.
* Periodical writes of region changes rather than explicit save() calls.
* Rewrite of the MySQL region code.
* Support for partial saves when using MySQL.
* Decoupling of region index implementations and RegionManager.

What still needs to be done includes:

* Background region modification operations (addmember, etc.).
* Unit tests to verify correctness of the partial saving.
* Migration support (to be re-added).
* Better handling when regions are failing to save.
* Testing of the /rg load and /rg save commands.
* Verification of how server shutdown / world unload is handled.
* Verification that thread-unsafe concurrent saves of data is not happening.
2014-08-08 20:28:49 -07:00
sk89q b5dfed9e01 Update for dependency package rename. 2014-08-02 23:35:12 -07:00
sk89q 29f804b9f0 Save YAML regions database to a temporary file before renaming. 2014-08-02 21:22:32 -07:00
sk89q 504fceceeb Remove /wg cancelall because it doesn't entirely work yet. 2014-08-02 21:19:05 -07:00
sk89q 9a852f4cbe Fix shutdown guard not working. 2014-08-02 21:08:11 -07:00
sk89q fafd3aba6a Implement UUID migration. 2014-08-02 21:03:17 -07:00
sk89q d87a335e85 Disable Flyway validation on migration. 2014-08-02 21:00:02 -07:00
sk89q 471b4496c9 Add task management and improve threaded code. 2014-08-02 18:38:18 -07:00
sk89q 32e39f5c7c Make some dependencies optional=true. 2014-08-02 11:25:27 -07:00
sk89q bf48361b10 Switch to Odeum for executors. 2014-08-02 11:24:25 -07:00
sk89q 387431c9c7 Remove both UUID and names from domains for removal commands. 2014-08-02 10:03:41 -07:00
sk89q 9b69c07663 Show name: for legacy names in region domains. 2014-08-02 09:53:35 -07:00
sk89q a1d59373ac Re-configure how libraries are shaded. 2014-08-02 09:49:52 -07:00
sk89q 81a727fe7f Add support for UUIDs in region commands. 2014-08-02 09:32:30 -07:00
sk89q 189fd15498 Close connections properly in MySQLDatabaseImpl.chooseWorldId(). 2014-08-01 22:32:13 -07:00
sk89q 1a602f2f8a Implement UUID saving/loading support for regions.
Also fix WORLDGUARD-3117.
2014-08-01 22:31:58 -07:00
sk89q 7986238936 Add migrations for region MySQL support. 2014-08-01 21:29:40 -07:00
sk89q a2fc9c94fd Fix NPE when a manager fails to load. 2014-08-01 20:02:50 -07:00
sk89q 51f98c9eb7 Reorganize MySQL region DB and added BoneCP as a dependency. 2014-08-01 19:19:48 -07:00
sk89q 418b8ff6a7 Add support for UUIDs in domains. 2014-08-01 17:36:56 -07:00
sk89q 9cab51dac8 Merge pull request #322 from zreed/master
Use table prefix when deleting from region_poly2d_point.
2014-07-29 21:00:41 -07:00
zreed 26ac987024 Use table prefix when deleting from region_poly2d_point. 2014-07-29 21:11:44 -04:00
sk89q e44875532d Fix NPE in BlacklistEntry due to recent refactor. 2014-07-28 21:02:15 -07:00
sk89q 956d1b4248 Add support for data values in the blacklist. 2014-07-28 16:45:43 -07:00
sk89q 3aa8bbe947 Fix .gitignore ignoring too many things. 2014-07-28 16:45:24 -07:00
sk89q f46b1cb138 Change use of integer IDs to "Target" objects in blacklist code. 2014-07-28 15:58:07 -07:00
sk89q 5b5022b0b8 Change blacklist repeated event tracking to use an expiring cache and cause names as keys. 2014-07-28 15:01:01 -07:00
sk89q d93c7fa09d Add on-dispense blacklist event. 2014-07-28 14:48:30 -07:00
sk89q 2c1d1ef0a3 Remove attachment check because it doesn't really make sense. 2014-07-28 14:45:05 -07:00
sk89q bf97e41697 Rewrite blacklist code. 2014-07-28 14:38:43 -07:00
sk89q c0852d63fe Add asynchronous region load/save for YAML databases.
These changes are intentionally limited so as to maintain backwards
compatibility with existing plugins using WG's API.

Some data structures were changed to CopyOnWrite to ensure thread
safety and the map of regions was changed to a ConcurrentHashMap.

Currently, saving requires making a copy of the regions map which can
cause a delay of a few milliseconds on large data sets.
2014-07-24 18:49:40 -07:00
sk89q acc39e11b1 Handle null causes by skipping them. 2014-07-24 17:38:18 -07:00
sk89q b4880ae982 Modularize potion blocking via the configuration. 2014-07-24 16:08:30 -07:00
Wyatt Childers 1a1acae588 Slight performance optimization to the movement checks to improve performance with slow permissions plugins 2014-07-23 22:26:34 -04:00
sk89q 1581390092 Add unit test to test global command blacklist with region command whitelist. 2014-07-21 19:52:27 -07:00
sk89q cd221ea19c Refactor command filter into a unit tested class.
Also adds support for regex \s as the subcommand delimiter.
2014-07-21 19:36:25 -07:00
sk89q abeab91be4 Add messages warning about auto-god mode and auto-amphibious mode. 2014-07-18 18:39:49 -07:00
sk89q 227f54d315 Remove extraneous file. 2014-07-13 15:11:53 -07:00
sk89q ac88367f6c Handle null custom flags registered by third-party plugins.
See WORLDGUARD-3094.
2014-07-13 02:23:04 -07:00
sk89q f788f0e0d9 Add internal.check-attached-blocks option to check attached blocks.
This does not check the other way yet (i.e. check if other blocks depend
on the block in question).
2014-07-12 21:14:26 -07:00
sk89q 9a4bc70cdd Added basic abstracted events. 2014-07-12 20:59:33 -07:00
sk89q ab46fd6244 Add Guava and jsr305 to dependencies. 2014-07-12 19:38:30 -07:00
sk89q 6deafa660d Cleanup code and add checkstyle configs from WorldEdit. 2014-07-12 19:31:43 -07:00
sk89q 0d2adc5707 Add more detail error messages when parsing regions file. 2014-07-11 13:20:42 -07:00
Albert Pham b0ed119585 Merge pull request #263 from kukelekuuk00/patch-1
Add some command aliases to RegionMemberCommands
2014-07-06 15:55:43 -07:00
sk89q ff2462b084 Removed initial AUTO_INCREMENT values from region_storage.sql
The MySQL code in WG makes my eyes bleed.
2014-07-06 15:38:25 -07:00
sk89q 894a42ea13 Merge pull request #316 from zreed/sqltableprefix 2014-07-06 15:37:26 -07:00
sk89q d827e01760 Merge pull request #313 from TheCutter/master 2014-07-06 15:09:51 -07:00
sk89q 5e6de8b76d Added runtime CraftBukkit dependencies. 2014-07-06 15:03:22 -07:00
sk89q b298bedea0 Set saturation level to food level with feed flag. 2014-06-26 17:47:14 -07:00
TomyLobo fb5ae838d9 Merge pull request #315 from eswick/master
Convert region ID to lowercase when saving polygon points to MySQL database.
2014-06-23 19:14:47 +02:00
eswick 3bfcd69fd9 Convert region ID to lowercase when saving polygon points to MySQL database. Check number of points in polygonal region before registering it.
When saving the points of a polygonal region to a MySQL database, the region ID was not converted to lowercase. If a region ID contained a capital letter, upon reload no points would be found, causing an out-of-bounds exception and essentially leaving WorldGuard unuseable.
2014-06-22 14:13:45 -04:00
Wizjany c66adf0119 Removed sensitive info from reports. 2014-06-17 23:24:13 -04:00
TheCutter 2119b274fd Merge branch 'master' of https://github.com/sk89q/worldguard 2014-06-14 21:36:06 +02:00
wizjany 22f45c45ee Apply obsidian generator disabling to tripwire. 2014-05-07 13:09:06 -04:00
wizjany 0dd9729b35 Fixed logic error in blocked-cmds for real this time.
Closes WORLDGUARD-3050.
2014-04-29 12:01:38 -04:00
wizjany ff46c2cf54 Fixed logic error in blocked-cmds checkings.
Closes WORLDGUARD-3048.
2014-04-26 11:31:24 -04:00
TheCutter 1537fc879e fixed indenation 2014-04-19 15:53:15 +02:00
TheCutter f00352cde0 updates comments 2014-04-19 11:03:03 +02:00
TheCutter fdc74b1c0d fixing syntax for guideline 2014-04-18 20:21:48 +02:00
TheCutter 83a3c61b66 fixed memory leak with closing mysql resources 2014-04-18 20:10:32 +02:00
wizjany 4422d536b7 Fixed a compilation error due to a sort-of-but-not-really-breaking bukkit change. 2014-02-28 21:21:00 -05:00
wizjany 1f40908c04 [maven-release-plugin] prepare for next development iteration 2014-02-28 20:03:38 -05:00
wizjany b707289284 [maven-release-plugin] prepare release 5.9 2014-02-28 20:03:35 -05:00
wizjany 43486bda63 Fix versioning error for release 2014-02-28 20:01:37 -05:00
sk89q 7086a1d0d2 Prepared release of v5.9. 2014-02-28 16:45:09 -08:00
TomyLobo 4dd13bd925 Merge pull request #310 from jmhertlein/master
Fixed ProtectedCuboidRegion::getPoints() returning points in wrong order

Fixes com.sk89q.worldguard.protection.regions.RegionIntersectTest.testIntersection.
2014-02-28 08:19:30 +01:00
TomyLobo 4ce97bca0e Added a unit test for ProtectedRegion.intersectsEdges. 2014-02-28 00:48:40 +01:00
Joshua M Hertlein ec9712f30e Fixed ProtectedCuboidRegion::getPoints() returning points in wrong order
ProtectedPolygonRegion returns points in an order such that you could play "connect the dots" and end up with the correct polygon. ProtectedCuboidRegion returns them in an order such that playing connect the dots gives you a Z shape. This breaks the intersectsEdges() function in ProtectedRegion when comparing cuboids. This commit causes ProtectedCuboidRegion::getPoints() to return them in an order consistent with ProtectedPolygonRegion, which makes intersectsEdges() work correctly.
2014-02-25 13:51:57 -06:00
Albert Pham 0162910964 Added <distributionManagement> to pom.xml 2014-02-23 22:26:36 -08:00
TomyLobo c252a79c1a Copied some .gitignore entries from WorldEdit. 2014-02-10 08:52:29 +01:00
Luke Anderson (stuntguy3000) 89739d4efe Change Resume to Continue 2014-01-27 10:51:35 +10:30
Luke Anderson (stuntguy3000) 9c7fb6a1d3 Changed halt-activity: Added Silent (s) and Information (i) flags, Added Resume (r) flag, remove c flag. 2014-01-26 12:56:59 +10:30
wizjany 2df3290d38 Fixed snowman trails being treated as snow fall. 2014-01-11 16:08:26 -05:00
wizjany 4805df2f03 Fix being able to use bonemeal to turn tall grass into double plants. 2014-01-08 14:56:59 -05:00
wizjany 5bc670db8b Fixed CI link in readme. 2014-01-08 14:56:58 -05:00
Wizjany ffda88f193 Fix number of args for migratedb command. 2013-12-14 17:21:07 -05:00
Dark Arc 96a69aa2ef Resolved an issue where explosions of type OTHER_EXPLOSION were ignoring the world config settings 2013-12-11 00:53:49 -05:00
wizjany 2d90fddbee Check for entities and projectiles removing items from frames too. 2013-12-09 17:46:33 -05:00
wizjany bbd1a0ef10 Protect items in item frames in protected regions. 2013-12-09 08:40:28 -05:00
TomyLobo 6b16ed79b3 Merge pull request #298 from md-5/herd_u_like_ifs
Using checked exceptions for control flow is slow. Lets replace it with an isEmpty check.
2013-12-09 00:28:16 -08:00
md_5 73b9a7fb0d Using checked exceptions for control flow is slow. Lets replace it with an isEmpty check. 2013-12-09 19:22:48 +11:00
wizjany 4a0ae833f0 Revert WE dependency to 5.5.8.
WorldGuard didn't use any new API since then,
so depending on an unstable snapshot wasn't necessary.
2013-11-18 15:30:17 -05:00
wizjany 5f32ebe2de Fix compile-time error due to 23766f20 2013-11-17 21:16:51 -05:00
Albert Pham 723928d239 Merge pull request #289 from sk89q/develop
Tiny changes extracted from various branches.
2013-11-17 15:03:19 -08:00
TomyLobo d024ed7b81 typos, unused imports 2013-11-17 23:59:02 +01:00
TomyLobo ec4143d3dc Bumped WE dependency to 5.5.9-SNAPSHOT. 2013-11-17 23:48:19 +01:00
TomyLobo 071fdaabd3 Added *.iml and .idea to .gitignore. 2013-11-17 23:48:18 +01:00
TomyLobo 23766f20dd Transformed the BlockFadeEvent handler into a switch. 2013-11-16 17:35:35 +01:00
TomyLobo 31739c647b Dissolved a .* import.
Rationale: grepping for qualified class names
2013-11-16 17:35:35 +01:00
Dark Arc faa016180a Added a config option to allow explosion flags to only prevent block
damage
2013-09-22 15:39:10 -04:00
wizjany e26238e814 Added formatting codes, &k/l/m/n/o and &x (reset). 2013-08-31 10:07:46 -04:00
wizjany f8ed1a3e3e Make /rg list default to own regions if the player doesn't have permission otherwise. 2013-08-27 23:36:01 -04:00
Wizjany d47c255168 Check bypass perms for item-drop flag. 2013-08-20 17:03:00 -04:00
wizjany d1e7796f81 Added allow-tamed-spawns setting, on by default.
This will stop WorldGuard from culling tamed animals
in regions with mob-spawning deny when they log in
with their owner.
2013-08-20 14:58:46 -04:00
Wizjany 1095064c5e Update CommandBook dependency to 2.3. 2013-08-18 23:32:51 -04:00
wizjany a15c9d289b There have been bigger non-backwards-compatible changes since. 2013-08-18 18:48:31 -04:00
wizjany c0f95bebf0 Send item-use blacklist event when right-clicking entities. 2013-08-16 13:17:28 -04:00
wizjany 0a54779fc4 Added snow-fall-blocks option to config to restrict snow fall to certain blocks 2013-08-12 18:09:45 -04:00
wizjany ac525958c5 Added config option and flag to prevent soil from drying naturally. 2013-08-12 18:06:31 -04:00
wizjany 458cf64501 Fixed addowner/addmember commands adding command artifacts.
Specifically, "-w <world>" will no longer be added when using it.
This requires WorldEdit with commit cd5f832 or newer.
Additionally fixed a typo: DefaultDomain.removaAll -> removeAll.
2013-08-03 09:46:29 -04:00
wizjany 4acef77623 Fixed milking cows in protected areas.
It seems that Bukkit changed the return of the bucket/itemstack
methods in the event, causing WG to think a different bucket was used.
2013-07-30 11:14:59 -04:00
TomyLobo d38d7fc492 Changed entity report format slightly.
This makes it clearer to users what that floating point number means.
2013-07-30 12:15:28 +02:00
wizjany 2510c3eeb5 Allow players to add newlines (\n) via command, not just manually in yml. 2013-07-25 13:10:16 -04:00
wizjany 326d53fd09 Allow the console to load/save all region managers with one command. 2013-07-25 10:12:03 -04:00
sk89q 75b3082b12 [maven-release-plugin] prepare for next development iteration 2013-07-16 11:07:26 -07:00
sk89q 1f214aadee [maven-release-plugin] prepare release 5.8 2013-07-16 11:07:06 -07:00
sk89q 174b3fad15 Updated Maven release plugin to 2.4.1. 2013-07-16 10:45:44 -07:00
sk89q 07531f67d4 Updated org.bukkit:bukkit dependency to 1.6.2-R0.1-SNAPSHOT. 2013-07-16 10:35:30 -07:00
sk89q 291c45064a Bumped version to 5.8-SNAPSHOT, updated CHANGELOG.txt. 2013-07-07 12:28:57 -07:00
sk89q 6f56cb29a5 Fixed -w flag for /rg load and /rg save. 2013-07-07 12:14:41 -07:00
sk89q 977c7d2f29 Changed DoubleFlag and IntegerFlag to take java.lang.Number objects in unmarshal(). 2013-07-07 11:45:22 -07:00
sk89q ecb87efe8d Update Bukkit dependency to version 1.6.1-R0.1-SNAPSHOT. 2013-07-07 11:42:24 -07:00
sk89q a57c162cd8 Convert heal flags datatype from integer to double.
Existing data should be cast with no data loss.
2013-07-07 11:38:03 -07:00
wizjany 60c3ed4f6b Polish the fix from the last commit and straighten some other multiworld issues in the move handler. 2013-06-23 20:17:20 -04:00
wizjany 714e75eb95 Potential fix for broken multiworld states. 2013-06-23 16:35:57 -04:00
Wizjany 636819c801 Revert change to permissions node for flags.
region.flag.own/member/etc was region.flag.regions.own/member/etc
This shouldn't be changed in between, especially if we maintain compatibility with the other flag node (flag.flags).
2013-06-20 00:52:59 -03:00
wizjany 9a6c2e0685 Finish reverting changes from earlier 2013-06-10 23:12:06 -04:00
wizjany 736eecc13b Add config option to use player teleports for move events.
Additionally removed code duplication in Vehicle listener.
2013-06-08 12:04:58 -04:00
TomyLobo 4718c5dab0 Removed unused imports. 2013-06-07 14:06:07 +02:00
Albert Pham 7e9bd49da2 Added mobs.disable-snowman-trails. 2013-06-02 13:23:01 -07:00
wizjany a0d0ff0b92 Lighter changes in BlockIgnite as well 2013-06-02 11:19:12 -04:00
wizjany b41be0c319 Added a static WorldGuardPlugin instance and made the utility methods in RegionCommands static. 2013-06-01 18:14:59 -04:00
wizjany 17a466059e A few changes in the new region commands.
- Allow setting flags on the global region (bugfix)
- Don't throw permissions errors when listing available flags (bugfix)
- Info command defaults to global region if no others are present (enhancement)
- A few typo and spacing fixes (enhancement)
2013-06-01 17:39:49 -04:00
wizjany 2d9e95a63e Revert lighter changes for now. This brings back the odd behaviors between flint & steel and fire charges, but makes it more intuitive for protection. 2013-06-01 10:14:56 -04:00
Albert Pham 532a45f9e7 Offering a sacrifice to the gods of pedantry. canX() -> mayX() for permissions. 2013-05-31 22:06:37 -07:00
Albert Pham d61e32ebb5 Cleaned up RegionCommands, abstracted region permissions. 2013-05-31 21:56:32 -07:00
Albert Pham b7d38e94c8 Added -a flag to region remove owner/member commands to remove all. 2013-05-29 13:24:40 -07:00
wizjany ae158742f6 [maven-release-plugin] prepare for next development iteration 2013-05-26 17:20:00 -04:00
wizjany c35686f8d1 [maven-release-plugin] prepare release 5.7.5 2013-05-26 17:20:00 -04:00
wizjany a5b6651582 Update CHANGELOG for 5.7.4 and 5.7.5 2013-05-26 17:10:35 -04:00
wizjany 54973fdf82 Large patch with lots of changes and fixes.
- Unified movement checking. Teleporting is now handled by
  entry/exit flags. Additionally, a region movement event is
  much closer to being added.
- Fixed an issue with enderpearls and exit/entry flags conflicting.
- Fixed a null check issue in several commands.
- Fixed allowed and blocked command flags making false matches and
  improved support for blocking/allowing specific command args.
2013-05-26 17:08:51 -04:00
wizjany 0bee631385 Use getName instead of toString for displaying world name. 2013-05-15 07:56:04 -04:00
wizjany 6283382837 Fixed a few movement flag related issues.
WG no longer prefixes greeting/farewell flags with '**', allowing people to customize the message.
(Adding &c** to the beginning of the message will give previous behavior)
Removed the "game mode locked" message since it returns false gamemodes when being called inside a player move event.
2013-05-05 10:57:46 -04:00
Silthus 39bb522051 Fixes heal flag bugs when player.maxHealth > 20
With the new Bukkit Changes the Player Health can be above 20, this fixes the magic number by using the now built in Bukkit functionality.

Examples of this bug were Health jumping to 1/20 hearts when having a heal-amount: -1
2013-05-04 11:47:43 +03:00
wizjany bf80d57abe Add fishing to xp blocker. 2013-04-21 08:59:24 -04:00
wizjany 865b94006a Apply other-explosion flag to entity damage as well. 2013-04-09 17:23:56 -04:00
wizjany 874248f8b5 Fix other explosion flag only clearing blocklist 2013-04-09 12:25:05 -04:00
steffen cef7d5bb12 Fix explosion check order
If the explosion is blocked and the block damage is also blocked, it's necessary to block the explosion (which includes the damage) instead of just the block damage.
2013-04-01 18:34:11 -04:00
wizjany 2a8131780f Don't ignore canceled air right click events.
Apparently Bukkit pre-cancels them even if they would do something.
2013-03-31 19:13:05 -04:00
Wizjany 7094f70f4a Remove duplicate check. (derp) 2013-03-31 19:13:04 -04:00
wizjany df5af6129c Improved lighter handling. 2013-03-23 21:10:30 -04:00
wizjany a6888c3767 Respect LIGHTER flag for ignition build checks 2013-03-23 15:19:56 -04:00
wizjany 1bd367ddde Fix one last witherskull/fireball conflict 2013-03-22 19:28:18 -04:00
wizjany 0cf87ae561 Allow cow milking in no-build areas 2013-03-22 15:35:30 -04:00
wizjany fa80f5f67f Fix infinite durability.
For whatever reason, the Bukkit API thinks that 'Durability" and "Damage"
are synonymous.
2013-03-18 13:25:11 -04:00
sk89q 7f080f920d [maven-release-plugin] prepare for next development iteration 2013-03-16 22:17:14 -07:00
sk89q 13658323b4 [maven-release-plugin] prepare release 5.7.3 2013-03-16 22:16:51 -07:00
sk89q 2d440ab5ba Cleaned up pom.xml. 2013-03-16 22:01:14 -07:00
sk89q dc55673691 Updated changelog for 5.7.3. 2013-03-16 21:12:26 -07:00
wizjany 92bb3948a6 Fix for minecart naming 2013-03-16 21:47:31 -04:00
wizjany f67ad6478c [maven-release-plugin] prepare for next development iteration 2013-03-15 16:01:09 -04:00
wizjany 1d984198ce [maven-release-plugin] prepare release 5.7.2 2013-03-15 16:01:02 -04:00
wizjany f2ca980771 Update changelog to 5.7.2 2013-03-15 15:44:48 -04:00
wizjany b826697aea Add flag check to smelting/mining xp handling 2013-03-15 15:44:34 -04:00
wizjany 89430c13ec Handle TNT Minecarts with tnt flag/settings. 2013-03-15 15:32:57 -04:00
Wizjany f07acea3e1 Updated to MC 1.5 2013-03-15 14:42:20 -04:00
wizjany e9402c55e6 Fixed a bunch of small bugs 2013-03-14 18:45:05 -04:00
wizjany 2eb6c76da8 Fix stack issue. 2013-03-13 14:38:28 -04:00
Wizjany a34e48a145 Added unit test for entry and exit flags to put the matter to rest.
Also cleaned up a few other things regarding tests.
2013-03-01 22:20:16 -05:00
Wizjany 2d50659b48 Apply exp flag and config setting to xp bottles.
"Workaround" for not being able to blacklist exp bottles at the moment.
Although I supposed I could have just fixed that instead, this allows more flexibility.
2013-02-21 10:20:47 -05:00
Wizjany 327ae2b807 Apply crop trampling setting to all entities. 2013-02-21 10:13:17 -05:00
Luuk Jacobs e831b7facc Add some command aliases to RegionMemberCommands 2013-02-19 10:24:35 +01:00
Wizjany dfb6114584 Fix a few wolf issues 2013-01-31 08:23:38 -05:00
Wizjany 5085841d9d [maven-release-plugin] prepare for next development iteration 2013-01-30 16:26:26 -05:00
Wizjany 7a98944469 [maven-release-plugin] prepare release 5.7.1 2013-01-30 16:26:20 -05:00
Wizjany 3d2b455cda Update changelog for 5.7.1 2013-01-30 16:21:55 -05:00
Wizjany 460d5d0691 Made wolves respect pvp stuff. Removed some extraneous code. 2013-01-30 15:27:52 -05:00
Wizjany b5f80351ec Allow a lot of commands to be sent from the console.
Examples:
 /rg addmem <id> <player> -w <worldname>
 /rg flag <id> <flag> -w <worldname> <flagvalue>
 /rg remove <id> -w <worldname>
Command blocks are currently untested.
List of commands: flag, priority, parent, remove,
 addmember, removemember, addowner, removeowner
2013-01-30 14:45:29 -05:00
Wizjany 72a9472a57 Add vine growth flag and config option. 2013-01-30 14:02:45 -05:00
Wizjany 7eb820c688 Fixed bug where players could place beds on the borders of regions without permissions 2013-01-30 13:47:48 -05:00
Wizjany 886b279da6 Bugfixes for bonemeal and minecarts. 2013-01-27 22:43:29 -05:00
Wizjany f2d7135fc5 Check shooter of projectile when one hits a hanging entity 2013-01-25 21:07:11 -05:00
Wizjany d214a859c3 Check the block that the item frame will end in, not the block the player clicked. 2013-01-21 04:08:17 -05:00
Wizjany d1e221c2b7 Don't cancel explosion if we only want to clear blocklist. May potentially cause issues with multiple settings overlapping. 2013-01-19 08:46:51 -05:00
Dark Arc e0e4207a4d Apply a cap to the health and hunger flags to prevent possible exceptions
If a player's health or hunger is set to higher than its respective maximum CraftBukkit will throw exceptions.
2013-01-16 14:48:39 -05:00
Wizjany 4398c781c5 Wither skulls should be handled separately from fireballs 2013-01-15 18:23:53 -05:00
Wizjany 3e06000fd9 Workaround for CraftBukkit bug with slab placement 2013-01-15 16:06:42 -05:00
Wizjany 833795ebe1 Add enderchest and anvil to blacklist inventories. 2013-01-14 13:31:54 -05:00
Wizjany 6e270d5ec3 Setting summary-on-start to false reduces much more clutter now 2013-01-13 17:21:51 -05:00
Wizjany 09a9bea3a7 Move enderchest to use flag 2013-01-13 16:10:06 -05:00
Wizjany 035ccee2a6 Fixed placing stuff in flower pots. (derp) 2013-01-13 13:44:54 -05:00
Wizjany 17aa2a4153 Fix region teleport permission 2013-01-13 06:13:41 -05:00
Wizjany f5bc5c0b47 That was not in there 2013-01-13 03:48:11 -05:00
Wizjany e7a4afde7d [maven-release-plugin] prepare for next development iteration 2013-01-13 03:08:17 -05:00
Wizjany 8758c9b940 [maven-release-plugin] prepare release 5.7 2013-01-13 03:08:13 -05:00
Wizjany a569d20779 Remove max players flag for now.
There are currently too many unhandled circumstances
which can easily break this flag such as players
entering region in weird ways (teleporting, falling,
logging in) and states changing. It is also horribly
inefficient at the moment.
2013-01-13 02:34:34 -05:00
Wizjany 88e01fa083 Fix enderpearl flag properly 2013-01-12 11:39:59 -05:00
Wizjany 7b435f9283 Added changelog for 5.7. Incremented version in pom.xml. 2013-01-12 00:25:55 -05:00
Wizjany a240e5d128 Added config option to block zombies from breaking down doors 2013-01-12 00:25:55 -05:00
Wizjany 0d0ba31d3a Fixes for tripwire, flower pots, wooden buttons, ender chests, and sneaking 2013-01-12 00:25:54 -05:00
Wizjany e79bb3533d Fireball flag should block blaze fireball ignition too now 2013-01-12 00:25:54 -05:00
Wizjany f94c4ec831 Mob damage setting/flag blocks poison DoT 2013-01-12 00:25:54 -05:00
Wizjany d5afb76105 Added config setting and flag to block explosions by plugins. 2013-01-12 00:25:53 -05:00
Wizjany dd7e9ba05e Add enderpearl flag to prevent players from teleporting to/from regions with enderpearls 2013-01-11 18:21:20 -05:00
Wizjany ee54698fdb Fix players being able to plant cocoa beans in protected areas 2013-01-11 17:54:29 -05:00
Wizjany 955b0e991c Added MAX_PLAYER and MAX_PLAYER_MESSAGE flags
Allows setting maximum number of players in a region
and sends a message if a region is at capacity.
2013-01-11 17:09:15 -05:00
Dilandau c1b98b9e40 Decrease call to PluginManager in WGBukkit
If WorldGuard is already found we bypass the call to
the PluginManager and use a cached version.
2013-01-11 16:16:49 -05:00
Dark Arc d6939b7916 Allow EnderPearls to damage the player who threw them in no-pvp areas 2013-01-02 19:46:41 -05:00
Dark Arc 5f0ca37879 Add support for blocking sub commands 2013-01-02 19:03:22 -05:00
Wizjany 548bdb7eb5 Attempt to fix item frame issues 2012-12-31 17:03:14 -05:00
Wizjany 5c85f39228 Block snowballs in pvp regions again. Reverts 671fd58568 2012-12-30 15:11:19 -05:00
Wizjany 85b2cbc03a Null check for entity explosions without an entity. 2012-12-29 11:46:24 -05:00
Wizjany cc78011da6 Build on latest Bukkit snapshot. Closes WORLDGUARD-2381
Fixes EntityChangeBlockEvent errors. Note that 1.4.5-R0.3-SNAPSHOT means build 2505+ and that there ARE 0.3 snapshots below 2505. Thus, this should be treated as temporary and changed on the next Bukkit Beta.
2012-12-29 11:46:14 -05:00
Dark Arc d016da1895 Resolves WORLDGUARD-2316 TNT still lethal when its damage is disabled 2012-11-24 02:42:28 -05:00
Dark Arc 8593f1c80a Resolves WORLDGUARD-2352 Anvils usable despite the use flag 2012-11-24 02:25:59 -05:00
Dark Arc 0b3c40dc3e Implements WORLDGUARD-2315 Enderdragon portal blocking 2012-11-24 02:17:34 -05:00
sk89q 2e7ecc59c0 Fixed typo where BEACON was COMMAND_BLOCK instead. 2012-11-11 19:08:31 -08:00
sk89q 942ce95dbf Fixed #WORLDGUARD-2297, Beacons are not protected in regions. 2012-11-11 18:45:55 -08:00
sk89q 03f77d5ab7 Fixed #WORLDGUARD-2296, Recent fix for dragon eggs in regions not working for left click. 2012-11-11 18:43:34 -08:00
sk89q 8dec32fa6a Added workaround for #WORLDGUARD-2299, java.lang.IllegalArgumentException: Instant potions cannot be extended. 2012-11-11 18:41:18 -08:00
sk89q 8f409d47d9 Fixed #WORLDGUARD-2289, FlagStateManager is not thread synced with the main thread. 2012-11-11 18:36:08 -08:00
sk89q 93f062d4e3 Hey, we have a mailing list now! Subscribe! https://groups.google.com/d/forum/sk-dev-discuss 2012-11-07 13:00:44 -08:00
Dark Arc b8f9ceafbb Resolves comma issue relating to flag listing
This stops commas from being added when a player types in an invalid flag and the player does not have permission to use one or more of the flag that are listed.
2012-11-07 14:20:44 -05:00
sk89q 75d07b6dad [maven-release-plugin] prepare for next development iteration 2012-11-07 09:19:50 -08:00
391 changed files with 38953 additions and 14028 deletions

No files matched your search

+11 -4
View File
@@ -1,6 +1,13 @@
.classpath
.project
.settings
target
/.classpath
/.project
/.settings
/target
.DS_Store
/*.iml
/.idea
/bin
/dependency-reduced-pom.xml
*-private.sh
+818
View File
@@ -0,0 +1,818 @@
# Changelog
## 6.1
* Added `exit-via-teleport` flag (default allow) to control exiting an exit=deny region via teleportation.
* Added a `fall-damage` flag to control player damage caused by falling.
* Added a `time-lock` flag to lock players' time of day. Valid values are from 0 to 24000 for absolute time, or +- any number for relative time.
* Added a `weather-lock` flag to lock players' weather. Valid values are "clear" or "downfall". Unset to restore to normal world weather.
* Added `-s` to the event debugging commands to show a stack trace rather than attempt to detect the causing plugin.
* Added support for using the `-e` argument (sets an empty value for the flag) in the flag set command when the type of flag is of the 'set' type.
* Added NPCs from the Citizens plugin to a whitelist so they are not protected.
* Added support for Spigot's BlockExplodeEvent.
* Changed tripwire to fall under the `use` flag.
* Changed enderchests to fall under the `use` flag.
* Changed vehicles and animals so they are not included in the `interact` flag.
* Changed the display of custom blacklist messages to no longer include a period at the end.
* Changed protection logic to consider connected chests.
* Changed the heal and feed flags to increase values for players who are invincible (or in creative mode) but not decrease them.
* Changed PvP protection to consider both attacker and defender locations.
* Fixed missing protection data for some 1.8-added blocks.
* Fixed compatibility issues with MC 1.7.
* Fixed inverted daylight detectors not being protected.
* Fixed spawn eggs not being included in protection.
* Fixed piston blocking not working due to a bug in Spigot.
* Fixed the blocking of certain invalid entity damage events.
* Fixed creeper explosions not being blocked in certain situations with explosion related flags set.
* Fixed "stickiness" with some position-related flags, sometimes resulting in rubber banding in the exit flags.
* Fixed armor stands so that they are treated more like item frames than mobs.
* Fixed blocks (e.g. sugar canes) adjacent to physics blocks (e.g. sand) not updating.
* Fixed a NullPointerException that occurred sometimes when generating the scheduler section of the report function (`/wg report`).
* Fixed the "no XP drops" configuration not functioning following a previous release.
* Fixed changes to region ownership sometimes not triggering a region database save.
* Fixed bucket protection displaying the "deny effect" even if bucket use was not prevented.
* Fixed CommandFilter matching emoticons and other unwanted characters.
* Fixed an exception occurring sometimes during game mode changes.
* Fixed primed TNT being checked twice for TNT flags.
## 6.0 beta 5
MC 1.7.9, 1.7.10 and 1.8 (Spigot only) are supported.
* Added a feature to detect when another plugin (incorrectly) includes WorldGuard's files, causing errors.
* Added a new `exit-override` flag that can be used on an entry=allow region that players can walk into from an entry=deny region.
* Added a new `entry-deny-message` to change the "entry denied" message.
* Added a new `exit-deny-message` to change the "exit denied" message.
* Changed entry/exit blocking to disembark players from their vehicles.
* Changed the PvP flag to no longer apply to self-attack.
* Fixed [#3220](http://youtrack.sk89q.com/issue/WORLDGUARD-3220): Polygon regions sharing points
* Fixed [#3216](http://youtrack.sk89q.com/issue/WORLDGUARD-3216): Polygon regions 'disappearing' or not working correctly
* Fixed [#3315](http://youtrack.sk89q.com/issue/WORLDGUARD-3315): Invincibility flag and mode not blocking knockback from snowballs, etc.
* Fixed [#3314](http://youtrack.sk89q.com/issue/WORLDGUARD-3314): Protection bypassable by getting a skeleton or creeper to target a player
* Fixed [#3326](http://youtrack.sk89q.com/issue/WORLDGUARD-3326): Enderchests cannot be protected with the use flag
* Fixed [#3327](http://youtrack.sk89q.com/issue/WORLDGUARD-3327): Fake players from some Forge mods are not being detected properly
* Fixed [#3328](http://youtrack.sk89q.com/issue/WORLDGUARD-3328): TypeToken error with CraftBukkit 1.7 in `/wg report`
* Fixed [#3086](http://youtrack.sk89q.com/issue/WORLDGUARD-3086): Region entry / exit messages overlap between seprate worlds
* Fixed [#2542](http://youtrack.sk89q.com/issue/WORLDGUARD-2542): Exit deny regions don't handle respawn / logout consistently
* Fixed [#2731](http://youtrack.sk89q.com/issue/WORLDGUARD-2731): Greeting / farewell messages don't understand region inheritance
* Fixed [#3308](http://youtrack.sk89q.com/issue/WORLDGUARD-3308): Enderchest interaction block not functioning with blacklist.txt
* Fixed [#3312](http://youtrack.sk89q.com/issue/WORLDGUARD-3312): PVP flag blocking enderpearl teleport fall damage
* Fixed [#3309](http://youtrack.sk89q.com/issue/WORLDGUARD-3309): Inventory view commands being blocked in protected regions
* Fixed [#3310](http://youtrack.sk89q.com/issue/WORLDGUARD-3310): USE flag is not allowing workbench usage
* Fixed [#3330](http://youtrack.sk89q.com/issue/WORLDGUARD-3330): Build permissions preventing block placement
* API: Added `BukkitUtil.toRegion(Chunk)`
## 6.0 beta 4
MC 1.7.9, 1.7.10 and 1.8 (Spigot only) are supported.
* Added better support for MC 1.8 blocks (regarding the use flag, etc.).
* Added an an experimental "lite" version of WarmRoast to CPU profile your server (try it: `/wg profile -p`)
* Added permissions for individual flag values (i.e. `worldguard.region.flag.flags.use.allow`).
* Added support for slightly older versions of Bukkit 1.7.9.
* Improved `/wg report`'s output (try it: `/wg report -p`)
* Fixed armor stands not being protected properly.
* Fixed lack of wood plate support with the `USE` flag.
* Fixed left click also being blocked when only right click needed to be blocked.
* Fixed items and paintings/item frames not decaying under some versions of Spigot.
* Fixed parent-child inheritance so the child will always inherit the parent.
* Fixed inheritance issues with a flag is set with a region group on a parent region.
* Fixed high CPU usage when Citizens is also installed.
* Fixed `on-acquire` in the blacklist so it also handles item transfers between inventories.
* Fixed the blacklist not supporting color codes.
* Changed the PvP flag so it applies to self-attack like in WG 5 (this change *may* be reverted).
## 6.0 beta 3
MC 1.7.10 and 1.8 (Spigot only) are supported.
* Support both MC 1.7.10 and 1.8.
* Don't apply the region override permission to PvP.
* Fix incorrect detection of hostile and ambient creatures when protecting against PvE.
* Fix the splash potion flag not working with the other flags.
* Fix potion blocking.
* Fix inability to blacklist the enchantment table and the workbench.
* Make PASSTHROUGH=DENY useful on ``__global__``.
* Fix issues (pistons broken, etc.) caused by adding members to ``__global__``.
* Make the EXP_DROPS flag a build-compat flag and set its deny message.
* Give the player back his/her XP bottle if it was blocked.
* Expand the interaction whitelist configuration to "physical" events.
* Catch command prefixes in the command flags.
* Add a RIDE flag for vehicles.
* Check for names in addition to UUIDs with /rg list.
* Whitelist hoppers and let them cross regions regardless of region protection.
* Revert USE flag's functionality to 5.x, add new INTERACT flag.
* Fix spawn egg blocking.
* Fix failed detection of incorrect blacklist block and item names.
* Fix command prefix bypass with the op command blocking configuration.
* Rewrite and update report generation (wg report).
* Add event cancellation debug commands.
* Fix location flags causing NullPointerExceptions.
* Show more details in error log which world the error belongs to.
* Add missing color codes when parsing input.
* Let players use NPCs always.
* Fix [WorldGuard] in log messages stacking on reloads.
* Better handle empty group / player names due to bad region data.
* Fix players being invincible with BUILD=deny.
* Fix certain entities not being damaged in protected regions.
* Improve entity detection in Entities utility class, add Entities.isNonPlayerCreature().
* Add missing SQL table prefix in statement selecting world names.
## 6.0 beta 2
* Added an `-e` parameter to `/rg flag` that sets the flag to an empty value. You can use this to, for example, make it so the `deny-message` flag is empty, meaning that players won't get a message at all.
* Added a visual smoke effect when an action on a block has been denied.
* Added `event-handling.interaction-whitelist`, a list of items or blocks that should never be protected. For example, adding `wooden_door` to the list would make it so that doors could be used by anyone regardless if they have permission or not. You may still protect the blocks via other means.
* Added `event-handling.emit-block-use-at-feet`, a list of items that, when used, will also be considered as the player using that item on the block at the player's feet. The purpose of this setting is, for example, to allow you to (sort of) prevent the use of a mod-added item that does not emit events.
* Added `-s` to silently turn toggle `/stoplag` and `-i` to show the current state of the setting. (Thanks, [stuntguy3000](https://github.com/stuntguy3000)).
* Added support for Bukkit [Material](http://jd.bukkit.org/rb/apidocs/org/bukkit/Material.html) names in the blacklist.
* Fixed [#3167](http://youtrack.sk89q.com/issue/WORLDGUARD-3167): Saplings can be used without permission although it won't place blocks inside the region
* Fixed [#3168](http://youtrack.sk89q.com/issue/WORLDGUARD-3168): Grown saplings that are partially prevented from placing all of its leaves may not remove the sapling
* Fixed [#3169](http://youtrack.sk89q.com/issue/WORLDGUARD-3169): Bonemeal usage falls under the USE flag when it should really fall under building
* Fixed [#3174](http://youtrack.sk89q.com/issue/WORLDGUARD-3174): Boat placement is not properly prevented in a protected region
* Fixed [#3130](http://youtrack.sk89q.com/issue/WORLDGUARD-3130): Polygonal selections allow unlimited claim volumes with /rg claim
* Fixed [#3137](http://youtrack.sk89q.com/issue/WORLDGUARD-3137): Claiming infinite regions is possible due to integer overflow
* Fixed [#3171](http://youtrack.sk89q.com/issue/WORLDGUARD-3171): Can't pickup XP in protected regions without permission
* Fixed [#3170](http://youtrack.sk89q.com/issue/WORLDGUARD-3170): Boats without a driver can be used to break lily pads
* Fixed [#3172](http://youtrack.sk89q.com/issue/WORLDGUARD-3172): Players cannot be damaged by mobs in protected regions unless they have permission
* Fixed [#3152](http://youtrack.sk89q.com/issue/WORLDGUARD-3152): BUILD overrides all other flags, unlike in WG 5
* Fixed [#3154](http://youtrack.sk89q.com/issue/WORLDGUARD-3154): notify-enterflag doesn't work with horses and other vehicles
* Fixed [#3166](http://youtrack.sk89q.com/issue/WORLDGUARD-3166): Trees do not grow naturally within protected regions
## 6.0 beta 1
### UUID support
Regions now fully support the use of UUIDs rather than names for storing the owners and members of a region. Commands still accept names, but they are translated into UUIDs in the background. For users who already have existing region data, names will be automatically converted to UUIDs on the first run of WorldGuard.
It is still possible to specify names rather than a UUID by using the `-n` flag with the region membership commands.
### 'Deny by default'
Previously, a pre-determined list of blocks and entities was used to determine whether an action by the player should be blocked. However, this has been reversed so that every action on a block or entity is denied (in a protected region) unless it has been deemed safe (such as, for example, right clicking with steak). Mods are now supported as a result.
The `USE` flag has been repurposed as a general "interaction" flag and covers every left click or right click of a block or entity. It also covers interaction that falls outside clicking.
### Exhaustive protection
More events are now handled in the protection code. For example,
* It is no longer possible to drop sand or gravel into a protected region from outside.
* It is no longer possible to grief a region by growing a tree into it.
* The entry and exit flags now handle players sitting on vehicles properly.
* Piston-moved blocks cannot be pushed into a different protected region.
* Owners of tamable animals are now considered in protection code.
Even water and lava flow can also be checked, although this requires that it be explicitly enabled in the configuration (flow events are very frequent, so they incur extra CPU cost).
The goal is to provide extremely exhaustive protection.
### Large performance boost for spatial queries
The performance of spatial queries for regions has been substantially increased at least an order of magnitude. Spatial queries are a necessity for the region code to query the list of regions that apply to a location in the world. There should be a negligible difference between 4, 40, and 4000 regions as long as too many regions are not overlapping.
### Background region operations
Region commands are now executed in the background. Notably, saves and loads will not lock up your server while they complete. Additionally, changes to regions are now saved periodically rather than immediately after every change.
### Updated MySQL region support
MySQL support has been completely overhauled. It should now be faster, no longer crash on foreign key index errors, use transactions, and support automatic creation and migration of tables (including support for table prefixes).
### Partial region data saving
For users of MySQL, WorldGuard now only saves changed and deleted regions when saving region data. No longer does WorldGuard have to rewrite the entire region database on each save.
### Improved handling of related flags
Multiple flags that apply to an event are now evaluated together if they are similar. For example, if a player right clicks a bed to sleep in it, both the `USE` and `SLEEP` flag are checked since they are both interaction-related. If one of them is `DENY`, then sleeping is denied (remember, `DENY` overrides `ALLOW`). If one of them is `ALLOW` and the other is not `DENY`, then sleeping is permitted.
Only one "category" of flags needs to evaluate to true to permit an action. `DENY` will not cross categories. For example, if `BUILD` is deny, it will not override `SLEEP`, so if `SLEEP` is set to `ALLOW`, sleeping will be permitted. This is fairly similar to how it worked on WorldGuard 5.
### Flag groups now work properly
While you could always set a group to a flag's value, the functionality was incomplete and did not work most of the time.
Now that groups are supported, you can change a flag so it only applies to a certain group of players. For example, `/rg flag example sleep deny -g members` would deny sleeping for only members of the `example` region.
### Inheritance now works as expected
Previously, a region only inherited flags and other details from its parents if the parent and the child overlapped at the location queried. This is no longer the case and inheritance is now always applied.
In addition, a new `-g` flag for `/rg define` lets you create a region with no physical area so that you can assign flags and use this region as a "template region."
### Settable deny message
It is now possible to change the message that users get when they are prevented from interacting with blocks or entities. This message is defined as a region flag, so you can set it on the `__global__` region or override it in a specific region. In addition, the tone and color of the default message has been softened, but you are free to change it entirely.
### Blacklist support for data values (and later, variants)
The blacklist was rewritten to support more than just block and item IDs. The immediate result is that you can now use data values, but as those are in the process of being deprecated by Mojang, it also allows support for Minecraft's new block variants in the future.
### Debounced events
Events that tend to reoccur very frequently (such as the ones that occur when you stand on a pressure plate continuously) have been "debounced" to reduce the number of checks that WorldGuard has to perform, reducing the amount of wasted CPU. In addition, the "you don't have permission" message is rate limited so players are not flooded with the message.
### New block place and break flags
A long requested feature was the availability of block place and break flags. These newly added flags work in tandem with the `BUILD` flag but can override `BUILD`. At the moment, it is not possible to allow explicit types of blocks to be placed or broken yet.
### Build permission nodes
A new optional (disabled by default in the configuration) feature is the checking of build permission nodes. For every block, entity, and item, the following permission nodes are checked:
* Block place: `worldguard.build.block.place.<material>`
* Block break: `worldguard.build.block.remove.<material>`
* Block interact: `worldguard.build.block.interact.<material>`
* Entity spawn: `worldguard.build.entity.place.<type>`
* Entity destroy: `worldguard.build.entity.remove.<type>`
* Entity interact: `worldguard.build.entity.interact.<type>`
* Entity damage: `worldguard.build.entity.damage.<type>`
* Item use: `worldguard.build.item.use.<material>`
In addition, the permissions are also checked in the style of `worldguard.build.block.<material>.<action>`, so `worldguard.build.block.<material>.place` would work too.
The list of usable material names comes from the [Material enumeration in Bukkit](http://jd.bukkit.org/rb/apidocs/org/bukkit/Material.html). For example, the permission for placing the bed block would be `worldguard.build.build.place.bed_block`. Be aware that _Material_ contains both item and block names.
For entity names, see [EntityType](http://jd.bukkit.org/rb/apidocs/org/bukkit/entity/EntityType.html).
### Other changes
* Added a setting to permit "fake players" to bypass protection. Fake players are used by some servers and some mods to allow events to be thrown for mod blocks. WorldGuard considers a player to be a fake player if the name starts with `[` and ends with `]`.
* Added a check so players can no longer disembark in a region from their tamed animal if they don't have permission to get back on.
* Added an item pickup flag to go along with the item drop flag.
* Added a new `//running` command was added to show currently running background tasks.
* Added a blacklist `on-dispense` event.
* Added more detailed error messages when parsing the YAML regions file.
* Added the `-Dworldguard.debug.listener=true` option that can be set on your server's command line to see how WorldGuard processes events, although this will result in a lot of log messages.
* Added log messages that occur on player join when a player had auto-god mode or auto-amphibious mode.
* Fixed the heal command so that it now sets a player's health to the maximum rather than 20.
* Fixed `ProtectedCuboidRegion.getPoints()` returning points in wrong order.
* Fixed the obsidian generator disable option to also apply to tripwire.
* Fixed an error with the blocked commands flag.
* Fixed a connection leak with the MySQL region code.
* Fixed `/wg reload` sometimes not applying new changes right away.
* Changed the region removal command so that child regions are no longer removed without warning when removing the parent region.
* Changed the YAML region data save code to first write the data to a temporary file before replacing the final file.
* Changed how region data is handled when region support is disabled: it is no longer loaded.
* Changed sponges to now be disabled by default. However, if you had previously installed WorldGuard, sponges will still be enabled. Sponges are being added in Minecraft and they work differently than in Minecraft Classic (which WorldGuard emulates). In addition, enabling sponge support in WorldGuard incurs extra CPU cost even if no sponges exist in the world.
* Changed how region data is loaded and saved so failures are now more graceful. If the region data fails to load for a world, then the entire world will be protected by default. In addition, periodic attempts will be made to load the region data in the background.
* Changed the `FEED` flag to maximize the player's saturation level if the hunger level is raised.
* Changed the `wg-invincible` and `wg-amphibious` groups feature so that it now must be enabled in the configuration.
* Removed the ability for WorldGuard to upgrade from a version for Minecraft Alpha.
### API changes
* You can use a new `WorldGuardPlugin.createProtectionQuery()` method to easily check build permissions.
* The listener classes were moved. Consider them internal -- if you want to make use of the listener somehow, please put in a ticket in our issue tracker.
* Much of the protection-related handling was previously scattered throughout the code. Now WorldGuard funnels events into an internal event system and then processes protection queries in a more consistent matter. These events are for internal use so it is strongly recommended that you do not use them (they may change without notice drastically). A lot of the protection-related flag handling was moved there.
* A significant portion of classes under the package of `com.sk89q.worldguard.protection` were changed or removed. However, the basic calls (testing the value of a flag, etc.) should still work, but they may be deprecated. Some of the utility `Domain`-related classes were removed.
* The old region database (load/save) API was removed and replaced with a new one. The new one no longer needs to pointless store a collection of regions on itself -- it has `collection = load()` and `save(collection)` methods.
* Previously, there were subclasses of `RegionManager` that implemented different spatial indices. However, now `RegionManager` is a final class and the spatial indices are separate (see the `RegionIndex` interface).
* A hash table was implemented that caches a list of regions within each loaded chunk. This increases performance of spatial queries substantially.
* A cache of recent spatial queries now exists (a cache of `ApplicableRegionSets`), but you need to make use of `RegionQuery` to make use of this cache. However, if you need to do a spatial query to modify region data, then the old method is better (get a `RegionManager`, etc.).
* `ApplicableRegionSet` was converted into an interface. In addition, there are now "virtual" `ApplicableRegionSet` instances that are returned by `RegionQuery` for certain special cases (such as, for example, region support being disabled by the user or region data being unavailable for a world due to an error). A new `isVirtual()` method is available. This is not an issue if you are getting `ApplicableRegionSet` instances from a `RegionManager`.
* `ApplicableRegionSet` now can accept a pre-sorted collection and its use of a `TreeSet` was removed for performance reasons.
* `FileNotFoundException` is now properly handled in the YAML region file class. It creates the new file and continues on.
* Player names are deprecated by Mojang and so they need to be converted into UUIDs. As this will take some time, you should do this conversion in a background task. To check whether a region contains a player, it recommended that `contains(LocalPlayer)` be used because it's possible that the user may be still using names. A new `WorldGuardPlugin.wrapOfflinePlayer()` method was added for this specific purposes.
* All flags now use `RegionGroup.ALL` as the default region group.
* `StateFlag.getDefault()` now returns a `State` rather than a `boolean`.
* The priority R-tree index now uses the R-tree for region intersection queries. Previously, it was only used for single point containment queries.
* Regions now keep a "dirty" flag and changes it whenever data within the region is changed. When WorldGuard decides to periodically save region data, it may only save changed regions. Calling `save()` on the `RegionManager` is no longer needed as periodical saves happen automatically.
* The old region data migration API was removed in favor of region store drivers. There is no longer a need to have an implementation for every possible conversion (i.e. YAML -> MySQL, MySQL -> YAML, etc.).
* `ProtectedRegion.copyFrom()` was added to copy region settings from another region.
* `@Nullable` annotations were added throughout the code. If you use IntelliJ IDEA, you may notice that it now warns you when a return value may be `null`.
## 5.9
* Added a config option to allow explosion flags to only prevent block damage
* Added allow-tamed-spawns setting, on by default. This will stop WorldGuard from culling tamed animals.
* Added config option and flag to prevent soil from drying naturally.
* Added formatting codes, &k/l/m/n/o and &x (reset).
* Added snow-fall-blocks option to config to restrict snow fall to certain blocks
* Allow players to add newlines (\n) via command, not just manually in yml.
* Allow the console to load/save all region managers with one command.
* Changed entity report format slightly.
* Check bypass perms for item-drop flag.
* Check for entities and projectiles removing items from frames too.
* Fix being able to use bonemeal to turn tall grass into double plants.
* Fix number of arguments for migratedb command.
* Fixed addowner/addmember commands adding command artifacts. Specifically, "-w <world>" will no longer be added when using it.
* Fixed milking cows in protected areas due to changes in Bukkit.
* Fixed ProtectedCuboidRegion::getPoints() returning points in wrong order.
* Fixed snowman trails being treated as snow fall.
* Make /rg list default to own regions if the player doesn't have permission otherwise.
* Protected items in item frames in protected regions.
* Resolved an issue where explosions of type OTHER_EXPLOSION were ignoring the world configuration settings.
* Send item-use blacklist event when right-clicking entities.
* Transformed the BlockFadeEvent handler into a switch.
## 5.8
* BREAKING CHANGE: This version has been built for versions of Bukkit for MC 1.6.1 and newer. Do not try to use this version of WG on an older Bukkit version.
* Added support for Minecraft 1.6+. Actual support of new 1.6 additions is dependant on Bukkit. Please use a newer build of Bukkit if, for example, you seem to be unable to add "Horses" to your lists of entities.
* Added mobs.disable-snowman-trails to disable the trails left by walking snowmen.
* Added -a flag to /region removeowner and /region removemember to remove all objects.
* Teleporting is now handled by entry/exit flags. If this is causing people to get entirely stuck inside entry/exit deny regions, set the new setting 'use-player-teleports' to 'false' in your configuration.
* Updated formatting for region commands, especially /region info.
* Changed permissions checking for /region commands to be more consistent, checking for region IDs as a sub-node. This means that if some permissions for some region commands no longer work, add '.*' to the end of permission lines for WG in your permission plugin.
## 5.7.5
* Refixed a few issues from 5.7.4.
## 5.7.4
* BREAKING CHANGE: Removed the cyan "**" in front of greeting and farewell messages to allow more customizability. You can re-add them by adding "&c**" to the flag.
* Fixed an issue enderpearling inside exit/entry deny regions.
* Added checks to players teleporting in and out of exit/entry regions.
* Fix bad matching in blocked and allowed command flags.
* Fixed heal flag bugs when player max health was increased.
* Add fishing to xp blocker.
* Applied other-explosion flag to entity damage as well.
* Fixed an issue with interaction that should allow blacklisting item use actions with no block involved (eg fishing rods, potions)
* Fix witherskull/fireball settings not being differentiated in one case
* Allow cow milking in no-build areas
* Fix infinite durability breaking items instantly.
## 5.7.3
* Fixed the error caused by Bukkit's change of the TNT minecart API.
## 5.7.2
* Updated to MineCraft 1.5.
* Added TNT Minecart support. They are handled with the same flags/settings as TNT.
* Added mining and smelting xp handling to the xp drops flag and setting.
* Fixed a few edge cases for placing items on region borders.
* Legacy: Fixed issue with //stack not respecting item metadata.
## 5.7.1
* Added a vine growth config option and flag.
* Added support for many commands to be used from console. Usage is with -w flag and a world name e.g. /rg addmem <id> <player> -w <worldname> /rg flag <id> <flag> -w <worldname> <flagvalue>
* Fixed bug that blocks placing plants in flower pots.
* Fixed permissions check for /rg tp
* Fixed enderchests not being accessible (they are now part of the USE flag)
* Fixed an issue with slabs being placable in protected regions. This was also fixed in CraftBukkit but has been left in for users running other versions.
* Fixed wither skulls being handled with other fireballs, despite having their own settings.
* Fixed item frames being placable on region borders.
* Fixed a bug that made explosions more ineffective than they should have been.
* Fixed bonemeal usage in protected regions.
* Fixed special minecarts being placable in protected regions.
* Fixed bugs being placable on region borders.
* Fixed wolves bypassing pvp flags.
## 5.7
* Fixed thread sync issue with FlagStateManager.
* Fixed dragon egg region protection not working in certain cases.
* Added beacon and anvil usage protection in regions.
* Add mobs.block-enderdragon-portal-creation to stop enderdragons from making portals on death.
* Fix TNT being lethal in some case when damage was disabled.
* Fix snowballs and enderpearls being able to knock players back in pvp deny regions.
* Add subcommand support for allowed and blocked command flags.
* Add max-players-allowed and max-players-reject-message flags to limit the numbers of players in a region.
* Fix players being able to plant cocoa beans in protected areas.
* Add an enderpearl flag to prevent players from teleporting to and from regions.
* Added mobs.block-other-explosions config setting and other-explosion flag to block explosions caused by uncovered things, such as other plugins. (It doesn't actually have to be a mob)
* Fix mob damage setting and flag not blocking the DoT wither effect.
* Ghast fireball flag will not block blaze fireballs from lighting things on fire.
* Fixed players without region permissions being able to trigger tripwires, use enderchests, use wooden buttons, and put plants in flower pots.
* Added mobs.block-zombie-door-destruction setting to stop zombies from breaking down doors while difficulty is set to hard.
Thank you to thvortex, Dilandau, tophathacker, and Dark_arc for their contributions this release.
## 5.6.5
* Fixed a regression that caused paintings and item frames to no longer be properly protected.
## 5.6.4
* Added mobs.block-above-ground-slimes to block slimes spawning naturally above ground.
* Added security.deop-everyone-on-join to de-op all players when they join.
* Added security.block-in-game-op-command to prevent usage of /op from in-game.
* Fixed a NullPointerException in PlayerInteract involving water potions and potion blocking.
* Fixed an issue with snowballs being blocked in regions.
* Changed dragon eggs to be checked like it is a broken block in regions.
* Moved developer's WGBukkit class to package com.sk89q.worldguard.bukkit.
## 5.6.3
* Added helper WGBukkit class to get references to WorldGuard from other plugins.
* Added physics.vine-like-rope-ladders to make ladders work like vines. As long as the top ladder block is present, ladder blocks will hold even if they have no block behind them, like a rope ladder.
* Fixed NullPointerException in PlayerInteractEvent caused by potion blocking.
* Fixed mobs.block-{item-frame,painting}-destroy not working.
Thank you to def for testing the above fixes and features.
## 5.6.2
* Fixed potion blocking not working well for splash potions.
## 5.6.1
* Added a mycelium-spread region flag.
* Added a dynamics.disable-mycelium-spread configuration setting.
* Added new gameplay.block-potions option. For example: gameplay: block-potions: [invisibility, speed]
* Fixed a bug in the entity explosion event handler that caused a NullPointerException.
Thank you for gabizou for his contribution in this release.
## 5.6
* Added official support for Minecraft 1.4. Support for 1.3.2 (and below) is still provided in this release.
* Added support for new and existing explosion types.
* Added support for blocking withers with the following settings: mobs: block-wither-explosions: false block-wither-block-damage: false block-wither-skull-explosions: false block-wither-skull-block-damage: true
* Added support for blocking item frames (and their use) in protected regions.
* Added item frame destruction region flags (if you wish to disable item frame destruction completely).
* (Re-)added support for priority R-tree region indexes. This means quicker region lookup, and better support for servers with thousands of regions.
* Improved /region info output for -g group flags.
* Allowed removing of -g group flags with /region flag.
* Allowed /region flag to set group and value at once.
* Deleting a region flag now also deletes group flag.
* Fixed detection of attack by projectiles to be more accurate.
* Fixed support for saving non-string flags in the MySQL region support.
* Fixed spurious comma in "Flags:" /region info output.
* Fixed players who are not in god mode not receiving damage in PVP areas from enderpearls.
* Players will now be told that they are in a no-PvP area if they are in one and attempting to attack someone, or that the player they are attacking is in a no-PvP area, if that is the case instead.
* Fixed an issue where region.getId() was lowercase'd each pass of a for loop in MySQLDatabase.updatePoly2dPoints().
* Fixed mob damage from projectiles not being properly blocked in regions where applicable.
* Changed default region wand to leather (#334).
Thank you to the following individuals for their contribution:
thvortex, Rutr, Glitchfinder, and DarthAndroid.
## 5.5.4
* Minecraft 1.3 support.
* Fixed /stack dupe bugs.
* Added regions.use-creature-spawn-event.
* Update for Async chat issue.
* Add use flag to cakes.
* Report number of plugins loaded in report writer.
* Updated fireblal item blocking.
* Fixed permissions for /region reload.
## 5.5.3
* Added game mode flag.
* Added item drop pickup flag to regions.
* Added support for fireball item blocking (385).
* Added configuration option to allow creature spawns from plugins.
* Added host key check.
* Added a new line split feature to region greetings.
* Prevented commands in the allow commands list from being blocked and vice versa.
## 5.5.2
* Added potion-splash flag to block splash potions
* Add entity-painting-destroy which can be used to prevent entities from destroying paintings (skeletons firing arrows)
* Added send-chat and receive-chat flags
* Fixed having regions in multiple worlds with the same name not working with MySQL
* A cancellable event is now fired if WorldGuard disallows PvP. (for developers!)
* Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
* Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
* Fixed an error that occured when clearing a non-existant region's parent.
* Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region.
* Added region/role-based permissions to /region teleport.
* BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
* /region info -s now selects the region being queried.
* Added /region teleport <id>.
* Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z.
* Made /region info show the region you're in if you don't specify an id explicitly.
* Prevent block ignition from lightning strikes if lightning is blocked in region. Fixes #1175
* Correctly check both WEPIF and superperms in WorldGurdPlugin.broadcastNotification()
* Destroy fire blocks when fire-spread is disallowed
* Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles.
* Added FallingSand to list of intensive entities to be removed with /halt-activiy.
* Replaced all usage of CreatureType by EntityType.
* Updated to support Bukkit 1.2-R0.3 and newer
* Made auto-god-mode disabled by default again.
* Added sign protection check disable.
* Cleaned up javadoc, deprecated duplicate methods, other cleanup
* Added a RegionGroupFlag to evey region flag Using the /region flag command with -g, the region group that the region flag applies to can be set.
## 5.5.1
* Fixed attacking with arrows from non-PVP to PVP areas
* Compatibility with Bukkit 1.1-R5
* Removed broken suppress-tick-sync-warnings config option. See bukkit.yml's setings.warn-on-overload option instead.
* Add region and 'can build' information to CommandBook's /whois
Contributions thanks to: NolanSyKinsley
## 5.5
* Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
* Now using Bukkit's tagged logging
* Updated to new event system
* Flush player flag state cache on world change
* Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0
* Added MySQL region storage method.
* Made explosions display their animations even when the event was blocked.
* Added fallback support for those who don't have a version of CommandBook with GodComponent
* Added LIGHTNING flag to DefaultFlag's flagsList Fixes #1026
* Removed /god, /heal, /locate, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded.
* Removed remaining usages of org.bukkit.util.config.Configuration
* Removed some unused configuration options
* Added permission worldguard.region.wand to the region wand
* Fixed ProtectedRegion.compareTo.
* Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
* Added exp-drops flag to disable experience drops per-region.
* Fixed some warnings.
* Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
* Added support for fireballs shot by players being blocked by the PVP flag.
* Now using dynamic command registration
* Split off ender dragon block damage from creeper block damage.
Contributions thanks to: narthollis, DarkArc, Wolvereness, and skeight
## 5.4
* Fixed configuration generation on Windows
* Fixed intersection calculation for regions
* Fixed timer and feeding delay for food flags
* Fixed region managers not being created properly (This caused errors related to CREATURE_SPAWN)
* Added support for Minecraft 1.0.1 blocks
* Added support for enchantments and tool damage (worldguard.stack.damaged is the node) with /stack
* Made being in the wg-invincible group respect the configuration's auto-invincible setting
* Added per-group region claim limit maximum
* Added worldguard.region.addowner.unclaimed.* permission for non-economy region 'buying'
* Checking allowed/blocked commands now occurs earlier to override more plugins
* Made PVP flag check whether either player is in a pvp deny region for blocking
Contributions thanks to: epuidokas, wizjany, Turtle9598, and DerFlash
## 5.3
* Added new config options and flags to better handle explosions of all types
* Added config options and flags for snow, ice, mushroom spread, grass spread, and leaf decay
* Added min and max health flags to clamp the values for the existing healing flags
* Added hunger flags similar to the existing healing flags
* Added an option to disable the use of the move event. This can boost performance on large servers but will disable the greeting/farewell and entry/exit flags
* Added flag to prevent pistons (including those that are outside the region, but would affect blocks inside the region)
* Added a /wg flushstates [player] command to free players stuck in a region that was exit-deny but no longer exists or the flag was removed
* Added a config option to disable xp orb dropping
* Added config option to disable redstone wire obsidian generators
* Added a vehicle-destroy flag
* Added enderman protection config and flag
* Allowed and blocked command flags will now fall back to the global region
* The worldguard.region.flag.own/member permissions are now worldguard.region.flag.regions.own/member! Please change your permissions accordingly.
* Made //stack respect max stack sizes unless the player has the worldguard.stack.illegitimate permission
* Setting invincibility flag to deny will override god mode unless the player has worldguard.god.override-regions
* The sleep flag will now prevent beds in the nether from exploding if set to deny
* Existing regions can no longer be accidentally overwritten. Use /region redefine to move an existing region.
* The info command will now sort players alphabetically
* Priming TNT by punching it with flint and steal should throw a blacklist event (consistent with old Minecraft versions)
* The /stoplag command will now remove xp orbs
* Permissions system will use per-world permissions if the provider supports it
* Players in vehicles are now subject to entry/exit and greeting/farewell flags
* Fixed interact blacklist event not logging correctly
* Fixed heal flag taking effect half a block northeast of the region
* Fixed a infinite sign dropping bug
* Fixed players being able to douse fire by punching it in regions they couldn't build it
* Fixed players being able to eat protected cake
* Fence gate usage can be blocked with the use flag
* Fixed chests being unprotected when they should be in 1.8
* Fixed weather config settings not applying when a world was loaded
* Fixed explosion handling in certain cases
* Fixed arrows working in non-pvp zones
* Fixed buckets working on the border of protected regions in certain cases
Contributions thanks to:
wizjany, zml2008, imjake9, Droolio, epuidokas,
EduardBaer, TomyLobo, and halvors
## 5.2.2
* Changed configuration saving so empty lists will be added to the configuration files.
## 5.2.1
* Add region bounds to /region info
* Added the ability to add owners/members to the global region for handling guest groups. Now if there's owners or members on the global region, then those that are not on the list cannot build.
* Fixed some flag algorithm issues.
* API: Fixed DefaultDomain.size() not counting players.
* API: Undeprecated ApplicableRegionSet.allows(StateFlag).
## 5.2
* Gave the ability to use color colors and macros in greeting and farewell messages.
* Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread, disable-snow-melting, disable-ice-formation.
* Added paintings to blacklist support.
* Added default.disable-health-regain.
* Added auto-invincible-permission setting, which lets you use the permission 'worldguard.auto-invincible' to become invincible on join automatically.
* Flames won't appear if you are /god'ed now.
* Added blocked-cmds region flag to block commands.
* Added allowed-cmds region flag to whitelist commands.
* Added entry region flag to block entry. Use entry-group to determine who this affects.
* Added exit region flag to block exit. Use exit-group to determine who this affects.
* Made negative healing possible via the healing flag.
* Changed the configuration header messages to be more helpful to new users.
* Added a warning about modifying region files by hand.
* Improved the API for plugin developers.
## 5.1
* A lot of changes.
## 4.0-alpha1
* This release is only to fix WorldGuard for Bukkit. Ignore the 4.0 label. Just move along. Nothing to see.
## 3.2.2
* Changed disable-water-damage to disable-drowning-damage.
* Fixed suffocation disable option.
* Fixed fire spread blocking.
* stopfire and allowfire now work in server console, just like in hMod.
## 3.2.1
* Updated for recent Bukkit ItemStack change.
## 3.2
* Added regions.default.pvp to control default PvP setting.
* Updated WorldGuard for the newer builds of Bukkit.
* Fixed creeper explosion blocking.
* Added redstone support to sponges, removed classic water.
* Fixed item durability disable for hoes.
## 3.1.2
* Increased the priority of WorldGuard's event handling.
## 3.1.1
* Fixed creeper and chest flag conflicting.
## 3.1
* Added ability to disable chest protection. New configuration setting (regions.build.chest-access) and new chest flag.
* Possibly fixed projectile blocking in no-PvP zones.
* Added /regionmembership permission that lets people only change the owners and members of regions they own.
## 3.0b2
* Fixed issue where built-in permissions were not (re)loaded.
* Fixed /god not working for others.
## 3.0b1
* Added parent-child relationships to regions.
* Added global build flag.
* Improved flag support.
* Fixed no-PvP zone messages being sent to the wrong person.
* Fixed commands so that they work in a recent version of Bukkit.
* Fixed NullPointerException in explode hook.
## 2.3.1
* Fixed various cast exceptions with the blacklist loggers.
* Added checks for unchecked exceptions when resolving permissions.
* Fixed the item durability disable setting changing the damage value on an empty hand.
## 2.3
* /god now works very well.
* Item (TNT, flint and steel, etc.) blocking should now work.
* The TNT blocking configuration variable should now work.
* Re-added /heal (not sure where that went), added /slay.
* Implemented contact damage disable toggle.
* Made all player damage disabling configuration parameters work.
* Fixed teleport-on-suffocation setting.
* Added /locate <name>, /locate <x> <y> <z>, and /locate that lets you program/change your compass bearing to point to a player's position (not yet live), a position, or back to spawn.
* Fixed CSVDatabase spitting an error if the owners list was empty.
## 2.2
* Now supports GroupUsers.
* Added support for blocking creeper explosions.
* Fixed a bug where a player's groups were not being loaded correctly, causing the blacklist group ignore option to not work.
## 2.1.1
* Fixed fire spread disable preventing flint and steel too.
* Fixed NullPointerException related to the player item event.
* Made setup simpler.
## 2.1
* Improved Bukkit support.
## 2.0beta3
* Fixed NullPointerException inside the ignite hook.
## 2.0beta2
* Fixed a NullPointerException in the damage hook.
## 2.0beta1
* Added area protection. Use /region or /rg to define regions.
## 1.8.1
* Fixed NullPointerException.
## 1.8
* Updated for Minecraft beta.
* Blacklist hooks have CHANGED. The new hooks are work better. on-create has been replaced with on-place (for block placement) and on-use (for item usage, light buckets and lighters). The old on-use is now on-right-click although it currently does nothing.
* Added coordinates to blacklist file logger.
* Added suffocation damage prevention.
## 1.7.1
* Updated for v0.2.8.
## 1.7
* Updated for v0.2.6_02 and hMod b129.
* Added option to prevent water from damaging particular blocks (Redstone wire, Minecart tracks, etc.). See disable-water-damage-blocks.
* /reload WorldGuard should now reload WorldGuard's configuration.
* Added wg-invincible and wg-amphibious groups that let you give certain players invincibility or underwater breathing.
* Added the ability to disable fall, water, lava, and/or fire damage.
* Water/lava bucket blocking should now be more reliable.
* Added /stack (alias /;) commands to stack items in your inventory into piles up to 64 items in size. Even unstackable items like signs can be stacked.
* /god mode should now let you gain health.
* /god mode should now work more reliably.
* Caught an error message for when the configuration file does not exist.
## 1.6
* Added spawn protection that prevents damage when a player spawns.
* Added login protection that prevents damage when a player joins.
* Added /god. /god can be used on others, provided that the /godother permission is set for the command's user.
## 1.5.1
* Removed the 'java.lang.NoSuchMethodError: Item.setDamage(I)V' error generated.
## 1.5
* Removed the block lag fix.
* WorldGuard now conditionally loads features so you can use any up-to-date build of hMod and the unsupported features won't break the entire plugin. When WG loads, check the server console for a report of features that are not supported by your version of hMod.
* Changed some configuration defaults: disable-lava-fire=true simulate-sponge=true item-durability=false
## 1.4.1
* Fixed issue with the block lag fix dropping item stacks of 0 quantity.
## 1.4
* New on-acquire hook. This does both a total inventory check on inventory change and item pick up denial. The item pick up denial is largely thanks to Dinnerbone for fulfilling my request to add a particular hook.
* Item durability can now be toggled with item-durability. Thanks to Dinnerbone for figuring this out while filfilling my request. The default setting is to fix item durability.
* New no-physics-gravel and no-physics-sand options allow you to prevent gravel and sand from falling.
* New allow-portal-anywhere option allows you to create portal blocks anywhere.
## 1.3
* UPGRADE WARNING: If you are using database logging, you must add a NULL 'comment' VARCHAR field to the table. The line of SQL that you can run for MySQL can be found in blacklist_table.sql.
* Improved plugin compatibility with the block lag fix. For maximum compatibility, you must now list WorldGuard as the first plugin in server.properties and you cannot reload or enable the plugin while the server is up. This is for bad plugins that unnecessarily use the "critical" priority for its hooks like the LWC. Most plugins don't do that though, so this won't apply for most people.
* Fixed signs being blank if they were denied via the blacklist.
* Added on-break event to the blacklist.
* Added comments and messages. Comments are only for your own use and they are printed with the log and notify actions of the blacklist. The message replaces the message that is shown the user and it is optional.
* The blacklist notification messages are now more compact and are light grey instead of light purple.
* The notify, log, and tell actions will now trigger every time for the on-break, on-create, on-drop events rather than wait 3 seconds between events for the same item or block for a player.
## 1.2
* /stopfire and /allowfire disable and enable fire spreading globally.
* Block lag fix slightly improved in accuracy for item drops.
* Sponge updated to remove water when the sponge block is set. Sponge radius can now be controlled using the 'sponge-radius' parameter and the default is now set to simulate Classic.
* Updated for a newer build of "b126," meaning that lava spread control now works well!
* A new summary of the status of some core protections is now printed on start. Disable this with 'summary-on-start'.
* Blacklist system has been overhauled. Check README.txt for changed configuration settings!
* The blacklist's method of preventing notification repeats is now better, instead waiting 3 seconds before notifying again (before it didn't notify again at all unless the user started using another blocked action).
* To give users the ability to receive notifications, the command to give permission to has been changed to /worldguardnotify, although the old one (that was never mentioned anywhere) still works.
* Water and lava buckets are now psuedo-blocked using an unreliable method that risks the stability of your server (no other plugin does it better though). Use it as your own risk.
* Added on item drop and on item use (i.e. chest) events.
* Chests, signs, and furnaces can now be blocked better with the blacklist system.
* The event names in the blacklist configuration have changed but the old event names should still work. The new names should make "more sense."
* A new "ban" action has been added to the blacklist.
* Action messages have been improved, now longer saying "destroyed" for everything.
* Logging to file has been completely changed, allowing you to use the date and time and the player's username in the log filename. It no longer rotates log files based on size, however.
* Logging to database is now supported.
* Tools can now be destroyed on drop to alleviate the durability cheat. You can do this with either with the blacklist or with the 'item-drop-blacklist' configuration option. The configuration option prints more friendly messages than the 'tell' action of blacklists.
## 1.1.2
* Block lag fix: Snow and glass should no longer drop items.
* Block lag fix: Block object now reset after hook call.
## 1.1.1
* Fixed redstone wire dropping wood blocks with the block lag fix.
* The block lag fix now consults other plugins so that ALL protection mechanisms and plugins should work.
## 1.1
* Added block lag fix.
## 1.0
* Initial release.
-496
View File
@@ -1,496 +0,0 @@
5.6.5:
- Fixed a regression that caused paintings and item frames to no longer be properly
protected.
5.6.4:
- Added mobs.block-above-ground-slimes to block slimes spawning naturally above ground.
- Added security.deop-everyone-on-join to de-op all players when they join.
- Added security.block-in-game-op-command to prevent usage of /op from in-game.
- Fixed a NullPointerException in PlayerInteract involving water potions and
potion blocking.
- Fixed an issue with snowballs being blocked in regions.
- Changed dragon eggs to be checked like it is a broken block in regions.
- Moved developer's WGBukkit class to package com.sk89q.worldguard.bukkit.
5.6.3:
- Added helper WGBukkit class to get references to WorldGuard from other plugins.
- Added physics.vine-like-rope-ladders to make ladders work like vines. As long as the
top ladder block is present, ladder blocks will hold even if they have no block
behind them, like a rope ladder.
- Fixed NullPointerException in PlayerInteractEvent caused by potion blocking.
- Fixed mobs.block-{item-frame,painting}-destroy not working.
Thank you to def for testing the above fixes and features.
5.6.2:
- Fixed potion blocking not working well for splash potions.
5.6.1:
- Added a mycelium-spread region flag.
- Added a dynamics.disable-mycelium-spread configuration setting.
- Added new gameplay.block-potions option. For example:
gameplay:
block-potions: [invisibility, speed]
- Fixed a bug in the entity explosion event handler that caused a NullPointerException.
Thank you for gabizou for his contribution in this release.
5.6:
- Added official support for Minecraft 1.4. Support for 1.3.2 (and below) is still
provided in this release.
- Added support for new and existing explosion types.
- Added support for blocking withers with the following settings:
mobs:
block-wither-explosions: false
block-wither-block-damage: false
block-wither-skull-explosions: false
block-wither-skull-block-damage: true
- Added support for blocking item frames (and their use) in protected regions.
- Added item frame destruction region flags (if you wish to disable item frame
destruction completely).
- (Re-)added support for priority R-tree region indexes. This means quicker region lookup,
and better support for servers with thousands of regions.
- Improved /region info output for -g group flags.
- Allowed removing of -g group flags with /region flag.
- Allowed /region flag to set group and value at once.
- Deleting a region flag now also deletes group flag.
- Fixed detection of attack by projectiles to be more accurate.
- Fixed support for saving non-string flags in the MySQL region support.
- Fixed spurious comma in "Flags:" /region info output.
- Fixed players who are not in god mode not receiving damage in PVP areas from
enderpearls.
- Players will now be told that they are in a no-PvP area if they are in one and
attempting to attack someone, or that the player they are attacking is in a
no-PvP area, if that is the case instead.
- Fixed an issue where region.getId() was lowercase'd each pass of a for loop in
MySQLDatabase.updatePoly2dPoints().
- Fixed mob damage from projectiles not being properly blocked in regions where
applicable.
- Changed default region wand to leather (#334).
Thank you to the following individuals for their contribution:
thvortex, Rutr, Glitchfinder, and DarthAndroid.
5.5.4:
- Minecraft 1.3 support.
- Fixed /stack dupe bugs.
- Added regions.use-creature-spawn-event.
- Update for Async chat issue.
- Add use flag to cakes.
- Report number of plugins loaded in report writer.
- Updated fireblal item blocking.
- Fixed permissions for /region reload.
5.5.3:
- Added game mode flag.
- Added item drop pickup flag to regions.
- Added support for fireball item blocking (385).
- Added configuration option to allow creature spawns from plugins.
- Added host key check.
- Added a new line split feature to region greetings.
- Prevented commands in the allow commands list from being blocked and
vice versa.
5.5.2:
- Added potion-splash flag to block splash potions
- Add entity-painting-destroy which can be used to prevent entities from destroying
paintings (skeletons firing arrows)
- Added send-chat and receive-chat flags
- Fixed having regions in multiple worlds with the same name not working with MySQL
- A cancellable event is now fired if WorldGuard disallows PvP. (for developers!)
- Made /region setparent check worldguard.region.setparent.own/member.<parent> instead
of worldguard.region.setparent.own/member.<child>.
- Allowed passing #<index> in place of a region ID, where <index> is the index as
displayed by /region list.
- Fixed an error that occured when clearing a non-existant region's parent.
- Added a -s flag to /region teleport, which sends you to the spawn point instead of the
teleport point of a region.
- Added region/role-based permissions to /region teleport.
- BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags
use it.
- /region info -s now selects the region being queried.
- Added /region teleport <id>.
- Vector flags can now be set to the current location with the value "here" and to a
specific position with x,y,z.
- Made /region info show the region you're in if you don't specify an id explicitly.
- Prevent block ignition from lightning strikes if lightning is blocked in region. Fixes
#1175
- Correctly check both WEPIF and superperms in WorldGurdPlugin.broadcastNotification()
- Destroy fire blocks when fire-spread is disallowed
- Added a construct flag that can be used to restrict block placing/destroying in zones
to certain roles.
- Added FallingSand to list of intensive entities to be removed with /halt-activiy.
- Replaced all usage of CreatureType by EntityType.
- Updated to support Bukkit 1.2-R0.3 and newer
- Made auto-god-mode disabled by default again.
- Added sign protection check disable.
- Cleaned up javadoc, deprecated duplicate methods, other cleanup
- Added a RegionGroupFlag to evey region flag Using the /region flag command with -g,
the region group that the region flag applies to can be set.
5.5.1:
- Fixed attacking with arrows from non-PVP to PVP areas
- Compatibility with Bukkit 1.1-R5
- Removed broken suppress-tick-sync-warnings config option. See bukkit.yml's setings.warn-on-overload option instead.
- Add region and 'can build' information to CommandBook's /whois
Contributions thanks to: NolanSyKinsley
5.5:
- Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
- Now using Bukkit's tagged logging
- Updated to new event system
- Flush player flag state cache on world change
- Improved compatibility with versions of CommandBook without GodComponent and updated pom dep for 2.0
- Added MySQL region storage method.
- Made explosions display their animations even when the event was blocked.
- Added fallback support for those who don't have a version of CommandBook with GodComponent
- Added LIGHTNING flag to DefaultFlag's flagsList Fixes #1026
- Removed /god, /heal, /locate, and /stack from WorldGuard to CommandBook. CommandBook is now checked to see whether a player is godded.
- Removed remaining usages of org.bukkit.util.config.Configuration
- Removed some unused configuration options
- Added permission worldguard.region.wand to the region wand
- Fixed ProtectedRegion.compareTo.
- Fixed FlatRegionManager.getApplicableRegions to return parent regions as well.
- Added exp-drops flag to disable experience drops per-region.
- Fixed some warnings.
- Updated dependency version for WorldGuard from 5.0 to 5.1-SNAPSHOT.
- Added support for fireballs shot by players being blocked by the PVP flag.
- Now using dynamic command registration
- Split off ender dragon block damage from creeper block damage.
Contributions thanks to: narthollis, DarkArc, Wolvereness, and skeight
5.4:
- Fixed configuration generation on Windows
- Fixed intersection calculation for regions
- Fixed timer and feeding delay for food flags
- Fixed region managers not being created properly (This caused errors related to CREATURE_SPAWN)
- Added support for Minecraft 1.0.1 blocks
- Added support for enchantments and tool damage (worldguard.stack.damaged is the node) with /stack
- Made being in the wg-invincible group respect the configuration's auto-invincible setting
- Added per-group region claim limit maximum
- Added worldguard.region.addowner.unclaimed.* permission for non-economy region 'buying'
- Checking allowed/blocked commands now occurs earlier to override more plugins
- Made PVP flag check whether either player is in a pvp deny region for blocking
Contributions thanks to: epuidokas, wizjany, Turtle9598, and DerFlash
5.3:
- Added new config options and flags to better handle explosions of all types
- Added config options and flags for snow, ice, mushroom spread, grass spread,
and leaf decay
- Added min and max health flags to clamp the values for the existing healing
flags
- Added hunger flags similar to the existing healing flags
- Added an option to disable the use of the move event. This can boost
performance on large servers but will disable the greeting/farewell
and entry/exit flags
- Added flag to prevent pistons (including those that are outside the
region, but would affect blocks inside the region)
- Added a /wg flushstates [player] command to free players stuck in a
region that was exit-deny but no longer exists or the flag was removed
- Added a config option to disable xp orb dropping
- Added config option to disable redstone wire obsidian generators
- Added a vehicle-destroy flag
- Added enderman protection config and flag
- Allowed and blocked command flags will now fall back to the global region
- The worldguard.region.flag.own/member permissions are now
worldguard.region.flag.regions.own/member! Please change your permissions
accordingly.
- Made //stack respect max stack sizes unless the player has the
worldguard.stack.illegitimate permission
- Setting invincibility flag to deny will override god mode unless the player
has worldguard.god.override-regions
- The sleep flag will now prevent beds in the nether from
exploding if set to deny
- Existing regions can no longer be accidentally overwritten.
Use /region redefine to move an existing region.
- The info command will now sort players alphabetically
- Priming TNT by punching it with flint and steal should throw a blacklist
event (consistent with old Minecraft versions)
- The /stoplag command will now remove xp orbs
- Permissions system will use per-world permissions if the provider supports it
- Players in vehicles are now subject to entry/exit and greeting/farewell flags
- Fixed interact blacklist event not logging correctly
- Fixed heal flag taking effect half a block northeast of the region
- Fixed a infinite sign dropping bug
- Fixed players being able to douse fire by punching it in regions they
couldn't build it
- Fixed players being able to eat protected cake
- Fence gate usage can be blocked with the use flag
- Fixed chests being unprotected when they should be in 1.8
- Fixed weather config settings not applying when a world was loaded
- Fixed explosion handling in certain cases
- Fixed arrows working in non-pvp zones
- Fixed buckets working on the border of protected regions in certain cases
Contributions thanks to:
wizjany, zml2008, imjake9, Droolio, epuidokas,
EduardBaer, TomyLobo, and halvors
5.2.2:
- Changed configuration saving so empty lists will be added to
the configuration files.
5.2.1:
- Add region bounds to /region info
- Added the ability to add owners/members to the global region for
handling guest groups. Now if there's owners or members on the global
region, then those that are not on the list cannot build.
- Fixed some flag algorithm issues.
- API: Fixed DefaultDomain.size() not counting players.
- API: Undeprecated ApplicableRegionSet.allows(StateFlag).
5.2:
- Gave the ability to use color colors and macros in greeting
and farewell messages.
- Added disable-ice-melting, disable-snow-formation, disable-mushroom-spread,
disable-snow-melting, disable-ice-formation.
- Added paintings to blacklist support.
- Added default.disable-health-regain.
- Added auto-invincible-permission setting, which lets you use the permission
'worldguard.auto-invincible' to become invincible on join automatically.
- Flames won't appear if you are /god'ed now.
- Added blocked-cmds region flag to block commands.
- Added allowed-cmds region flag to whitelist commands.
- Added entry region flag to block entry. Use entry-group to determine who
this affects.
- Added exit region flag to block exit. Use exit-group to determine who
this affects.
- Made negative healing possible via the healing flag.
- Changed the configuration header messages to be more helpful to new users.
- Added a warning about modifying region files by hand.
- Improved the API for plugin developers.
5.1:
- A lot of changes.
4.0-alpha1:
- This release is only to fix WorldGuard for Bukkit. Ignore the 4.0
label. Just move along. Nothing to see.
3.2.2:
- Changed disable-water-damage to disable-drowning-damage.
- Fixed suffocation disable option.
- Fixed fire spread blocking.
- stopfire and allowfire now work in server console, just like in hMod.
3.2.1:
- Updated for recent Bukkit ItemStack change.
3.2:
- Added regions.default.pvp to control default PvP setting.
- Updated WorldGuard for the newer builds of Bukkit.
- Fixed creeper explosion blocking.
- Added redstone support to sponges, removed classic water.
- Fixed item durability disable for hoes.
3.1.2:
- Increased the priority of WorldGuard's event handling.
3.1.1:
- Fixed creeper and chest flag conflicting.
3.1:
- Added ability to disable chest protection. New configuration setting
(regions.build.chest-access) and new chest flag.
- Possibly fixed projectile blocking in no-PvP zones.
- Added /regionmembership permission that lets people only change
the owners and members of regions they own.
3.0b2:
- Fixed issue where built-in permissions were not (re)loaded.
- Fixed /god not working for others.
3.0b1:
- Added parent-child relationships to regions.
- Added global build flag.
- Improved flag support.
- Fixed no-PvP zone messages being sent to the wrong person.
- Fixed commands so that they work in a recent version of Bukkit.
- Fixed NullPointerException in explode hook.
2.3.1:
- Fixed various cast exceptions with the blacklist loggers.
- Added checks for unchecked exceptions when resolving permissions.
- Fixed the item durability disable setting changing the damage value on
an empty hand.
2.3:
- /god now works very well.
- Item (TNT, flint and steel, etc.) blocking should now work.
- The TNT blocking configuration variable should now work.
- Re-added /heal (not sure where that went), added /slay.
- Implemented contact damage disable toggle.
- Made all player damage disabling configuration parameters work.
- Fixed teleport-on-suffocation setting.
- Added /locate <name>, /locate <x> <y> <z>, and /locate that lets you
program/change your compass bearing to point to a player's position
(not yet live), a position, or back to spawn.
- Fixed CSVDatabase spitting an error if the owners list was empty.
2.2:
- Now supports GroupUsers.
- Added support for blocking creeper explosions.
- Fixed a bug where a player's groups were not being loaded correctly,
causing the blacklist group ignore option to not work.
2.1.1:
- Fixed fire spread disable preventing flint and steel too.
- Fixed NullPointerException related to the player item event.
- Made setup simpler.
2.1:
- Improved Bukkit support.
2.0beta3:
- Fixed NullPointerException inside the ignite hook.
2.0beta2:
- Fixed a NullPointerException in the damage hook.
2.0beta1:
- Added area protection. Use /region or /rg to define regions.
1.8.1
- Fixed NullPointerException.
1.8
- Updated for Minecraft beta.
- Blacklist hooks have CHANGED. The new hooks are work better. on-create has
been replaced with on-place (for block placement) and on-use
(for item usage, light buckets and lighters). The old on-use is now
on-right-click although it currently does nothing.
- Added coordinates to blacklist file logger.
- Added suffocation damage prevention.
1.7.1
- Updated for v0.2.8.
1.7
- Updated for v0.2.6_02 and hMod b129.
- Added option to prevent water from damaging particular blocks
(Redstone wire, Minecart tracks, etc.). See disable-water-damage-blocks.
- /reload WorldGuard should now reload WorldGuard's configuration.
- Added wg-invincible and wg-amphibious groups that let you give certain
players invincibility or underwater breathing.
- Added the ability to disable fall, water, lava, and/or fire damage.
- Water/lava bucket blocking should now be more reliable.
- Added /stack (alias /;) commands to stack items in your inventory into
piles up to 64 items in size. Even unstackable items like signs can be
stacked.
- /god mode should now let you gain health.
- /god mode should now work more reliably.
- Caught an error message for when the configuration file does not exist.
1.6
- Added spawn protection that prevents damage when a player spawns.
- Added login protection that prevents damage when a player joins.
- Added /god. /god can be used on others, provided that the /godother
permission is set for the command's user.
1.5.1
- Removed the 'java.lang.NoSuchMethodError: Item.setDamage(I)V' error
generated.
1.5
- Removed the block lag fix.
- WorldGuard now conditionally loads features so you can use any up-to-date
build of hMod and the unsupported features won't break the entire
plugin. When WG loads, check the server console for a report of
features that are not supported by your version of hMod.
- Changed some configuration defaults:
disable-lava-fire=true
simulate-sponge=true
item-durability=false
1.4.1
- Fixed issue with the block lag fix dropping item stacks of 0 quantity.
1.4
- New on-acquire hook. This does both a total inventory check on inventory
change and item pick up denial. The item pick up denial is largely
thanks to Dinnerbone for fulfilling my request to add a particular hook.
- Item durability can now be toggled with item-durability. Thanks to
Dinnerbone for figuring this out while filfilling my request. The
default setting is to fix item durability.
- New no-physics-gravel and no-physics-sand options allow you to
prevent gravel and sand from falling.
- New allow-portal-anywhere option allows you to create portal blocks
anywhere.
1.3
- UPGRADE WARNING: If you are using database logging, you must add a
NULL 'comment' VARCHAR field to the table. The line of SQL that you
can run for MySQL can be found in blacklist_table.sql.
- Improved plugin compatibility with the block lag fix. For maximum
compatibility, you must now list WorldGuard as the first plugin in
server.properties and you cannot reload or enable the plugin
while the server is up. This is for bad plugins that unnecessarily
use the "critical" priority for its hooks like the LWC. Most plugins
don't do that though, so this won't apply for most people.
- Fixed signs being blank if they were denied via the blacklist.
- Added on-break event to the blacklist.
- Added comments and messages. Comments are only for your own use and they
are printed with the log and notify actions of the blacklist. The
message replaces the message that is shown the user and it is optional.
- The blacklist notification messages are now more compact and are
light grey instead of light purple.
- The notify, log, and tell actions will now trigger every time for the
on-break, on-create, on-drop events rather than wait 3 seconds between
events for the same item or block for a player.
1.2
- /stopfire and /allowfire disable and enable fire spreading globally.
- Block lag fix slightly improved in accuracy for item drops.
- Sponge updated to remove water when the sponge block is set. Sponge radius
can now be controlled using the 'sponge-radius' parameter and the
default is now set to simulate Classic.
- Updated for a newer build of "b126," meaning that lava spread control
now works well!
- A new summary of the status of some core protections is now printed
on start. Disable this with 'summary-on-start'.
- Blacklist system has been overhauled. Check README.txt for changed
configuration settings!
- The blacklist's method of preventing notification repeats is now better,
instead waiting 3 seconds before notifying again (before it didn't
notify again at all unless the user started using another blocked
action).
- To give users the ability to receive notifications, the command to give
permission to has been changed to /worldguardnotify, although the
old one (that was never mentioned anywhere) still works.
- Water and lava buckets are now psuedo-blocked using an unreliable
method that risks the stability of your server (no other plugin
does it better though). Use it as your own risk.
- Added on item drop and on item use (i.e. chest) events.
- Chests, signs, and furnaces can now be blocked better with the
blacklist system.
- The event names in the blacklist configuration have changed but the old
event names should still work. The new names should make "more sense."
- A new "ban" action has been added to the blacklist.
- Action messages have been improved, now longer saying "destroyed"
for everything.
- Logging to file has been completely changed, allowing you to use
the date and time and the player's username in the log filename. It
no longer rotates log files based on size, however.
- Logging to database is now supported.
- Tools can now be destroyed on drop to alleviate the durability cheat.
You can do this with either with the blacklist or with the
'item-drop-blacklist' configuration option. The configuration option
prints more friendly messages than the 'tell' action of blacklists.
1.1.2
- Block lag fix: Snow and glass should no longer drop items.
- Block lag fix: Block object now reset after hook call.
1.1.1
- Fixed redstone wire dropping wood blocks with the block lag fix.
- The block lag fix now consults other plugins so that ALL protection
mechanisms and plugins should work.
1.1
- Added block lag fix.
1.0
- Initial release.
+1 -2
View File
@@ -1,5 +1,4 @@
Contributing
============
# 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
+52
View File
@@ -0,0 +1,52 @@
# New User Guide
Thank you for installing WorldGuard! By default, when you first install WorldGuard, most features will be disabled until you enable the ones that you want to use.
## Requirements
You will need to be using [Bukkit](http://dl.bukkit.org/) for your server or one of its derivatives (such as Spigot or Cauldron). If you are using Minecraft Forge, you will have to use Cauldron in order to use WorldGuard.
It is not possible to use WorldGuard with the plain vanilla server from Mojang.
## Installation
Installation is simple!
1. Extract the `WorldGuard.jar` file and put it into your server's `plugins` folder. If the folder does not exist yet, you can create it yourself.
2. Run the Bukkit server.
3. Look inside `plugins/WorldGuard` and configure the plugin as necessary. There are also in-game commands.
By default, only "ops" can use WorldGuard commands. If you install a permissions plugin, then you can assign fine grained permissions to your server's trusted users.
## Documentation
To learn how to use WorldGuard, check out [the wiki](http://wiki.sk89q.com/wiki/WorldGuard).
## Frequently Asked Questions
### How do I protect my spawn?
Check out the [region protection tutorial](http://wiki.sk89q.com/wiki/$%7Bproject.name%7D/Regions/Tutorial) on the wiki.
### Players can't do anything!
WorldGuard will typically not block something without also telling the user that he or she does not have permission. Please make sure that it's not another plugin that is preventing players from interacting with the world.
Also, be aware that spawn protection is a feature of vanilla Minecraft and you must disable that in `bukkit.yml`. It only allows ops to do anything in a specified radius around the world's spawn point.
### I made a region but anyone can build in it!
1. If players get a "you can't do that here" message but they are still able to build, it's because another plugin is likely undoing the protection offered by WorldGuard.
2. If no message is being sent, make sure that there is a region where you think one is.
### Where can I ask questions?
You can [ask questions on our forum](http://forum.sk89q.com) or visit us on IRC (irc.esper.net #sk89q).
### Where can I file a bug report or request a feature?
Visit our [issue tracker](http://youtrack.sk89q.com/dashboard). It's also used for WorldEdit and our other projects.
### Is WorldGuard open source?
Yes! [View the source code on GitHub](https://github.com/sk89q/worldguard).
+3 -5
View File
@@ -1,6 +1,3 @@
----------------------------------------------------------------------------
WorldGuard License
----------------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
@@ -169,8 +166,9 @@ permanent authorization for you to choose that version for the
Library.
----------------------------------------------------------------------------
PRTree License
----------------------------------------------------------------------------
This work includes Robert Olofsson's Priority R-Tree implementation, for which
its license is reproduced below.
Copyright (c) 2008-2010 Robert Olofsson.
All rights reserved.
-232
View File
@@ -1,232 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>${project.name} ${version}</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Ropa+Sans" rel="stylesheet" type="text/css">
<style>
body {
margin: 0;
padding: 3em 1em;
background: #efefef;
color: #333;
line-height: 1.5;
}
#wrapper {
width: 600px;
margin: auto;
}
body, th, td, input {
font: 14px 'Source Sans Pro', Arial, sans-serifsans-serif;
}
.section {
background: #fff;
position: relative;
padding: 2em 2.4em;
margin: 3em auto 4em auto;
width: 80%;
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
.section:before, .section:after {
content: "";
position: absolute;
z-index: -2;
}
.section {
-moz-border-radius: 4px;
border-radius: 4px;
}
.section:before, .section:after {
bottom: 15px;
left: 10px;
width: 50%;
height: 20%;
max-width: 300px;
max-height: 100px;
-webkit-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
box-shadow: 0 15px 10px rgba(0, 0, 0, 0.5);
-webkit-transform: rotate(-1deg);
-moz-transform: rotate(-1deg);
-ms-transform: rotate(-1deg);
-o-transform: rotate(-1deg);
transform: rotate(-1deg);
}
.section:after {
right: 10px;
left: auto;
-webkit-transform: rotate(1deg);
-moz-transform: rotate(1deg);
-ms-transform: rotate(1deg);
-o-transform: rotate(1deg);
transform: rotate(1deg);
}
a:link, a:visited {
color: #0004b2;
text-decoration: none;
}
a:hover {
color: #ac0000;
text-decoration: none;
border-bottom: 1px solid #999;
}
h1 {
font: 2.7em 'Ropa Sans', 'Trebuchet MS', Helvetica, Arial, sans-serif;
color: #000;
margin: 0 0;
padding: 0 0 0.2em 0;
font-weight: normal;
text-align: center;
text-shadow: 2px 2px #FFF;
}
h2 {
font-size: 1.3em;
color: #FFF;
margin: -2.5em 0 0.8em 0;
float: left;
background: #0049FF;
padding: 0.4em 0.8em;
border-radius: 0.2em;
font-weight: normal;
text-align: center;
}
h3 {
text-transform: uppercase;
font-weight: bold;
}
h2 + * {
clear: both;
}
@media (max-width: 650px) {
#wrapper {
width: 100%;
}
}
</style>
</head>
<body>
<div id="wrapper">
<h1>${project.name} ${version}</h1>
<div class="section">
<h2>Getting Started</h2>
<p>
Thanks for choosing ${project.name}! When you first install ${project.name},
nothing will be enabled, so you will need to switch on the features
that you need to use, whenever it is convenient for you.
</p>
<ul>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Installation">How do I install ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Upgrading">How do I update ${project.name}?</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}#Usage">How do I use ${project.name}?</a></li>
</ul>
<p>
Need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Common Issues</h2>
<h3>What are the other files that come with the download?</h3>
<p>
Inside the folder "contrib" of the download are the following files:
</p>
<ul>
<li>blacklist_table.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Blacklist">blacklist feature</a>.</li>
<li>region_storage.sql is for using a database with the
<a href="http://wiki.sk89q.com/wiki/${project.name}/Regions">region protection feature</a>.</li>
<li>region_storage_update_20110325.sql is for updating your region protection
database (if you're using it) if your database was made before March 25, 2011.</li>
</ul>
<h3>${project.name} doesn't seem to work.</h3>
<p>
Two common mistakes include forgetting to install WorldEdit
(${project.name} needs it), or making
a syntax error in one of ${project.name}'s configuration files (this is very
fatal unfortunately, and can be caused by a single character typed in the wrong place). Try
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">asking in IRC</a>
to see whether anyone can help you.
</p>
<h3>How do I protect my spawn, or another area?</h3>
<p>
Read the <a href="http://wiki.sk89q.com/wiki/${project.name}/Regions/Tutorial">area protection tutorial</a>
on our wiki. For more detailed information, be sure to read about
<a href="http://wiki.sk89q.com/wiki/WorldGuard/Regions">region protection on the wiki</a>. Note
that if you can't build in spawn, don't forget that Minecraft comes with its own
limited spawn protection that you have to disable (see below).
</p>
<h3>I or others don't have permission to build.</h3>
<p>
Unless you copied configuration files from an older installation of
${project.name}, your problem is either caused by another plugin, or by not
disabling the built-in spawn protection of the Minecraft server.
</p>
<h3>No one can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'deny' means that
no one can modify the things inside the region.</li>
<li>That you added the player as an owner or member of the region. If you are using
a group (g:groupName), you may have to give the group the permission of
group.groupName for ${project.name} to recognize it.</li>
<li>That you disabled spawn protection. The Minecraft server has an automatic
spawn protection feature where only 'ops' can build in a definable
radius around spawn (by default, it is 16 blocks). If you are on Minecraft
1.4 or newer, edit "spawn-protection" in server.properties; otherwise, modify bukkit.yml
and change the spawn-radius setting.</li>
<li>That it's not another plugin causing you trouble. The error messages of ${project.name} are of
a dark red shade. If the color of the "no permission" message is not
that color, it is not ${project.name}.</li>
</ul>
<h3>Everyone can build in a region I made!</h3>
<p>
Make sure that:
</p>
<ul>
<li>You didn't change the 'build' flag, because protection is on by default
when a new region is made. Setting the build flag to 'allow' means that
anyone can modify the things inside the region.</li>
<li>That it's not caused by another plugin. If players are getting a dark red
permission denied message, but they can still build, another plugin
is likely causing the conflict.</li>
</ul>
<h3>Where do I report bugs or suggest ideas?</h3>
<p>
Make sure you are using the latest version of ${project.name}, try asking in
IRC first (see "Need help?" above) if it's a problem, and if you think you've
found a bug or have a great suggestion to provide, please
report it to <a href="http://youtrack.sk89q.com/issues/WORLDGUARD">our issue tracker</a>.
</p>
<p>
Still need help?
<a href="http://wiki.sk89q.com/wiki/${project.name}/Support">See the ways that you can get assistance</a>.
</p>
</div>
<div class="section">
<h2>Contributing</h2>
<p>
Did you know that ${project.name} is open source? That means that you can
read the code and learn from it, as well as modify it and submit back
changes to help the community!
</p>
<ul>
<li><a href="https://github.com/sk89q/worldguard">View the source code</a></li>
<li><a href="http://wiki.sk89q.com/wiki/${project.name}/Development">More information</a></li>
</ul>
</div>
</div>
</body>
</html>
+25 -14
View File
@@ -1,35 +1,46 @@
![WorldGuard](http://static.sk89q.com/readme/worldguard.png)
==========
# ![WorldGuard](http://static.sk89q.com/readme/worldguard-new.png)
WorldGuard is a toolbox of various functions, useful for multiplayer servers, that lets you:
WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
* 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.
* Block creeper and wither block damage, falling damage, etc.;
* Disable fire spread, lava fire spread, ice formation, Endermen picking up blocks, etc.;
* Blacklist certain items and blocks so they can't be used;
* Warn moderators when certain items and blocks are used;
* Protect areas of your world so only certain people can build in them;
* Set areas where PVP, TNT, mob damage, and other features are disabled;
* Protect your server from various 'exploits' like magical obsidian creation machines;
* Disable, or enable, various Minecraft features, like sponges from classic;
* Add useful commands like an immediate "STOP ALL FIRE SPREAD" command.
* Enable only features you want! Everything is off by default.
WorldGuard is open source and is available under the GNU General Public License v3.
WorldGuard is open source and is available under the GNU Lesser
General Public License v3.
Currently, Bukkit is required to use WorldGuard. You can get a release copy of WorldGuard from the [BukkitDev site](http://dev.bukkit.org/bukkit-plugins/worldguard/).
Compiling
---------
The project is written for Java 6 and our build process makes use of [Maven](http://maven.apache.org). Detailed compilation information [can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
The project is written for Java 6 and our build process makes use of
[Maven](http://maven.apache.org). Detailed compilation information
[can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
Dependencies are automatically handled by Maven.
Contributing
------------
We happily accept contributions, especially through pull requests on GitHub. Submissions
must be licensed under the GNU General Public License v3.
We happily accept contributions, especially through pull requests on GitHub.
Please read CONTRIBUTING.md for important guidelines to follow.
Submissions must be licensed under the GNU Lesser General Public License v3.
Links
-----
* [Homepage](http://enginehub.org/worldguard)
* [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)
* [Continuous integration](http://builds.enginehub.org)
* [End-user documentation](http://wiki.sk89q.com/wiki/WorldGuard)
+55
View File
@@ -0,0 +1,55 @@
# Upgrading to WorldGuard 6
This is a **major upgrade**. However, it is relatively well-tested because many people have *accidentally* updated to version 6 when the Spigot team updated WorldGuard for 1.8 but did not update v5.9.
The version that you downloaded supports Minecraft 1.7.10 and 1.8.
**NEW DOCUMENTATION:** There is [new work-in-progress documentation](http://docs.enginehub.org/manual/worldguard/latest/). However, refer to the [older wiki](http://wiki.sk89q.com/wiki/WorldGuard) for missing pages.
## Downgrading to 5.9
When updating to v6, your region data will be updated to use player UUIDs rather than their names. That means that you **cannot downgrade** to WG 5.9 because it does not understand UUIDs and will remove all ownership data. However, you can use [Six2Five](https://github.com/sk89q/Six2Five/releases/tag/release-1.0) to downgrade region data stored as YAML.
Remember to make backups.
If you do not use region protection, then downgrading requires no extra steps.
## What's Changed?
There have been many changes, but the most important (and breaking ones) are listed below.
### Region Protection
The region protection has been optimized and aggressive caching has been added. That means that the impact of region protection when hundreds or thousands of regions exist has been minimized.
* UUID support was added. On first server start, your region data will be converted to use UUIDs. Names that lack a UUID (i.e. they refer to accounts that don't exist) will remain, but can be removed by re-running the conversion (see the config) after changing the configuration to remove unconverted names.
* Build protection for regions is now much more complete, and WorldGuard protects against entities and blocks making changes as if they were players. For example, TNT cannot be flung into a protected region and piston machines cannot push into a protected region. Liquid flow (lava and water) can also be checked, although this is disabled by default.
* Setting the `build` flag to `deny` will break pistons and Redstone. When you set the `build` flag to `deny`, you are essentially saying that *no one* can build at all. Now that blocks and entities are considered the same as players, they get blocked in that case. What's the solution? First of all, you probably do **not** want to set the build flag: remember, when you create a region, only members can build in it, so there's no need to change the `build` flag.
* If you want to deny building "in the wilderness," use `/rg flag __global__ passthrough deny`. Unset the `build` flag if you had set it to `deny`. As you may know, when you create a region, protection is automatically turned on (only members can build). If you don't want that, you can set a region's `passthrough` flag to `allow`. In the case of the global region, it *defaults* to `allow`, so you have to set it to `deny` to turn that off.
* Earlier versions of WorldGuard 6 changed the ``use`` flag to be much more encompassing, but this is **no longer the case**. The ``use`` flag now works like it did before in 5.x, only applying to things like doors, pressure plates, and levers. A new ``interact`` flag was added instead that controls all right clicks of blocks and entities.
* By default, the ``use`` flag is now set so only members of a region can use levers and doors within a region. If you want to disable this type of protection in all protected regions, use `/rg flag __global__ use allow`.
* Region groups for flags now work properly. You can set a certain flag to apply to only a certain group (owners, members, nonmembers, nonowners, all). Before, it only worked correctly for some flags. Region groups can be set like this: `/rg flag spawn pvp -g nonmembers deny`.
* In WG 5.9, some flags had a default region group of "non-members." That means that if you did `/rg flag spawn chest-access deny`, only non-members would be unable to open chests. In WG 6, you have to explicitly specify this: `/rg flag spawn chest-access -g nonmembers deny`.
* It is now possible to change the message that users get when they are prevented from interacting with blocks or entities. This message is defined as a region flag, so you can set it on the `__global__` region or override it in a specific region. In addition, the tone and color of the default message has been softened, but you are free to change it entirely.
* The MySQL code was substantially rewritten to be faster and more efficient. Some changes are needed to the table structure, but WorldGuard is now capable of performing those automatically. However, those who use table prefixes *may* run into trouble.
### Blacklist
* If you want to blacklist only water and lava blocks and not buckets, you can no longer apply `on-place` to water or lava blocks because it will also deny the use of buckets. If you wish to deny the use of just the liquid blocks, use `on-use`. This is because WorldGuard now considers the use of a bucket also the placement of a liquid block.
### Miscellaneous
* In the rare situation that you are user of the "auto-invincibility" and "auto-no-drowning" groups (`wg-invincible` and `wg-amphibious`), you now have to enable these features in the config (`auto-invincible-group: true` and `auto-no-drowning-group: true`). This is because some permission plugins have been causing severe hang ups whenever it is queried for a player's groups, which, in this case, happens to include when the player joins.
## Known Incompatibilities
Plugins that utilize WorldGuard's API may not work anymore. They may crash with errors. The API has changed somewhat.
* Spigot:
* `settings.global-api-cache`, if enabled, will crash WG UUID lookups (fixed in Spigot build #1625)
## Other Changes
The rest of the changes can be found in the CHANGELOG file.
In addition, there is [new work-in-progress documentation](http://docs.enginehub.org/manual/worldguard/latest/) that describes some of the new features.
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ WorldGuard, a suite of tools for Minecraft
~ Copyright (C) sk89q <http://www.sk89q.com>
~ Copyright (C) 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 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 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/>.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}-${project.version}.jar</source>
<outputDirectory>/</outputDirectory>
<filtered>false</filtered>
</file>
<file>
<source>${project.build.directory}/CHANGELOG.html</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>${project.build.directory}/INSTALL.html</source>
<destName>README.html</destName>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>${project.build.directory}/UPGRADE.html</source>
<destName>READ_BEFORE_UPGRADING_FROM_V5.html</destName>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
</files>
<fileSets>
<fileSet>
<includes>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_manual_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
</assembly>
+18
View File
@@ -0,0 +1,18 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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/>.
*/
+41
View File
@@ -0,0 +1,41 @@
<!--
~ WorldGuard, a suite of tools for Minecraft
~ Copyright (C) sk89q <http://www.sk89q.com>
~ Copyright (C) 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 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 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/>.
-->
<!DOCTYPE import-control PUBLIC
"-//Puppy Crawl//DTD Import Control 1.1//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
<import-control pkg="com.sk89q">
<allow pkg="java"/>
<allow pkg="javax"/>
<allow pkg="org.junit"/>
<allow pkg="junit"/>
<allow pkg="org.mockito"/>
<allow pkg="org.hamcrest"/>
<allow pkg="com.sk89q"/>
<allow pkg="org.enginehub"/>
<allow pkg="org.bukkit"/>
<allow pkg="org.yaml.snakeyaml"/>
<allow pkg="au.com.bytecode.opencsv"/>
<allow pkg="org.khelekore.prtree"/>
<allow pkg="com.google.common"/>
<allow pkg="com.jolbox.bonecp"/>
<allow pkg="org.flywaydb.core"/>
<allow pkg="org.json.simple"/>
</import-control>
+3
View File
@@ -0,0 +1,3 @@
</div>
</body>
</html>
+368
View File
@@ -0,0 +1,368 @@
<!DOCTYPE html>
<html>
<head>
<title>WorldGuard - titleToken</title>
<style>
body {
margin: 0;
padding: 2em 2em 3em 2em;
color: #333;
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif;
font-size: 15px;
line-height: 1.5;
word-wrap: break-word;
}
.wrapper {
margin: auto;
max-width: 750px;
}
a {
background: transparent;
}
a:active,
a:hover {
outline: 0;
}
strong {
font-weight: bold;
}
h1 {
font-size: 2em;
margin: 0 0 0.67em 0;
}
img {
border: 0;
}
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
pre {
font-family: monospace, monospace;
font-size: 1em;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
* {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
a {
color: #4183c4;
text-decoration: none;
}
a:hover,
a:focus,
a:active {
text-decoration: underline;
}
hr {
height: 0;
margin: 15px 0;
overflow: hidden;
background: transparent;
border: 0;
border-bottom: 1px solid #ddd;
}
hr:before,
hr:after {
display: table;
content: " ";
}
hr:after {
clear: both;
}
blockquote {
margin: 0;
}
ul,
ol {
padding: 0;
margin-top: 0;
margin-bottom: 0;
}
ol ol {
list-style-type: lower-roman;
}
dd {
margin-left: 0;
}
code,
pre {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 12px;
}
pre {
margin-top: 0;
margin-bottom: 0;
}
*:first-child {
margin-top: 0 !important;
}
*:last-child {
margin-bottom: 0 !important;
}
.anchor {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: block;
padding-right: 6px;
padding-left: 30px;
margin-left: -30px;
}
.anchor:focus {
outline: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
position: relative;
margin-top: 1.5em;
margin-bottom: 16px;
font-weight: bold;
line-height: 1.4;
}
h1 {
padding-bottom: 0.3em;
font-size: 2.1em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}
h2 {
padding-bottom: 0.3em;
font-size: 1.65em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}
h3 {
font-size: 1.2em;
line-height: 1.43;
}
h4 {
font-size: 1.1em;
}
h5 {
font-size: 1em;
}
h6 {
font-size: 1em;
color: #777;
}
p,
blockquote,
ul,
ol,
dl,
table,
pre {
margin-top: 0;
margin-bottom: 16px;
}
hr {
height: 4px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
}
ul,
ol {
padding-left: 2em;
}
ol ol,
ol ul {
margin-top: 0;
margin-bottom: 0;
}
li>p {
margin-top: 16px;
}
dl {
padding: 0;
}
dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: bold;
}
dl dd {
padding: 0 16px;
margin-bottom: 16px;
}
blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
blockquote>:first-child {
margin-top: 0;
}
blockquote>:last-child {
margin-bottom: 0;
}
table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all;
}
table th {
font-weight: bold;
}
table th,
table td {
padding: 6px 13px;
border: 1px solid #ddd;
}
table tr {
background-color: #fff;
border-top: 1px solid #ccc;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
img {
max-width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
code {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
}
code:before,
code:after {
letter-spacing: -0.2em;
content: "\00a0";
}
pre>code {
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}
.highlight {
margin-bottom: 16px;
}
.highlight pre,
pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border-radius: 3px;
}
.highlight pre {
margin-bottom: 0;
word-break: normal;
}
pre {
word-wrap: normal;
}
pre code {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}
pre code:before,
pre code:after {
content: normal;
}
</style>
</head>
<body>
<div class="wrapper">
@@ -1,3 +1,11 @@
--
-- This file only needs to be run if you are using a very old version
-- of the region database (before 2011/03/25).
--
-- Otherwise, WG knows how to update your tables automatically, as well
-- as set them up initially.
--
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
+320 -35
View File
@@ -2,7 +2,10 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.6.5</version>
<version>6.1</version>
<packaging>jar</packaging>
<!-- Project information -->
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
@@ -13,47 +16,101 @@
<comments>License on all contributions</comments>
</license>
</licenses>
<issueManagement>
<system>YouTrack</system>
<url>http://youtrack.sk89q.com</url>
</issueManagement>
<ciManagement>
<system>Jenkins</system>
<url>http://build.sk89q.com</url>
</ciManagement>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<properties>
<mailingLists>
<mailingList>
<name>Developer Discussion</name>
<archive>https://groups.google.com/d/forum/sk-dev-discuss</archive>
</mailingList>
</mailingLists>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
<repository>
<id>maven.sk89q.com</id>
<url>http://maven.sk89q.com/artifactory/libs-release-local</url>
</repository>
<snapshotRepository>
<id>maven.sk89q.com-snapshot</id>
<url>http://maven.sk89q.com/artifactory/libs-snapshot-local</url>
</snapshotRepository>
</distributionManagement>
<properties> <!-- Fix encoding warnings -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4.4</version>
<version>5.5.8</version>
<scope>compile</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sk89q.spigot</groupId>
<artifactId>bukkit-classloader-check</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.2-R0.2</version>
<version>1.8.6-R0.1-SNAPSHOT</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.1</version>
<version>2.3</version>
<scope>compile</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
@@ -63,44 +120,109 @@
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<!-- Contains parts of Guava that are not compatible
between Bukkit 10.0.1 and 17+ -->
<groupId>com.sk89q</groupId>
<artifactId>guavabackport</artifactId>
<version>1.1</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>1.3.9</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>3.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>squirrelid</artifactId>
<version>0.1.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<version>4.11</version>
<scope>test</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.2.1</version>
<scope>test</scope>
<optional>true</optional>
</dependency>
</dependencies>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
</distributionManagement>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions>
<extensions> <!-- Used for uploading the docs -->
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
@@ -127,9 +249,98 @@
<include>blacklist.txt</include>
</includes>
</resource>
<resource>
<targetPath>migrations/</targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources/migrations/</directory>
</resource>
</resources>
<plugins>
<!-- Check style -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.12</version>
<executions>
<execution>
<id>verify-style</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirectory>${basedir}/src</sourceDirectory>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<logViolationsToConsole>true</logViolationsToConsole>
<checkstyleRules>
<module name="Checker">
<!-- Tabs are strictly banned -->
<module name="FileTabCharacter"/>
<module name="TreeWalker">
<!-- Important basics -->
<!-- <module name="PackageDeclaration"/> Unlikely that we would miss this in a PR -->
<module name="OuterTypeFilename"/> <!-- TypeName -> TypeName.java -->
<!--
Control package usage, so people don't insert Bukkit into WE where it shouldn't belong, etc.
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="${basedir}/config/checkstyle/import-control.xml"/>
</module>
<!-- Code -->
<module name="HideUtilityClassConstructor"/> <!-- Utility classes should not have a constructor -->
<module name="CovariantEquals"/>
<module name="EqualsHashCode"/> <!-- equals() and hashCode() go together -->
<module name="NestedTryDepth"> <!-- SHOULD not need to adjust this -->
<property name="max" value="2"/>
</module>
<module name="SuperFinalize"/> <!-- We don't actually use this -->
<module name="JUnitTestCase"/> <!-- Checks tearDown(), setUp() etc. -->
<!-- Style -->
<module name="LeftCurly"> <!-- Left brace never goes on another line -->
<property name="option" value="eol"/>
</module> <!-- We don't check right brance -->
<module name="DefaultComesLast"/> <!-- default case in switch should be last -->
<module name="GenericWhitespace"/>
<!-- Naming -->
<module name="ClassTypeParameterName">
<property name="format" value="^[A-Z][a-zA-Z0-9]*$"/>
</module>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<!-- <module name="PackageName"/> Unlikely that we would miss this in a PR -->
<module name="ParameterName"/>
<!-- <module name="TypeName"/> Unlikely that we would miss this in a PR -->
</module>
<!-- Require the header, something that many people forget and we hate to fix -->
<!-- You should configure the header in your IDE -->
<module name="Header">
<property name="headerFile" value="${basedir}/config/checkstyle/header.txt"/>
<property name="fileExtensions" value="java"/>
</module>
</module>
</checkstyleRules>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -173,18 +384,60 @@
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
<include>org.flywaydb:flyway-core</include>
<include>com.sk89q:squirrelid</include>
<include>com.sk89q:guavabackport</include>
<include>com.googlecode.json-simple:json-simple</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.sk89q.guavabackport</pattern>
<shadedPattern>com.sk89q.worldguard.internal.guava</shadedPattern>
</relocation>
<relocation>
<pattern>org.flywaydb</pattern>
<shadedPattern>com.sk89q.worldguard.internal.flywaydb</shadedPattern>
</relocation>
<relocation>
<pattern>com.sk89q.squirrelid</pattern>
<shadedPattern>com.sk89q.worldguard.util.profile</shadedPattern>
</relocation>
<relocation>
<pattern>org.json.simple</pattern>
<shadedPattern>com.sk89q.worldguard.util.jsonsimple</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.ruleoftech</groupId>
<artifactId>markdown-page-generator-plugin</artifactId>
<version>0.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<inputDirectory>${basedir}</inputDirectory>
<outputDirectory>${project.build.directory}</outputDirectory>
<headerHtmlFile>${project.basedir}/config/markdown/header.html</headerHtmlFile>
<footerHtmlFile>${project.basedir}/config/markdown/footer.html</footerHtmlFile>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
<descriptor>${basedir}/config/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
@@ -200,7 +453,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<version>2.4.1</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
@@ -208,25 +461,57 @@
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
-37
View File
@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}-${project.version}.jar</source>
<destName>WorldGuard.jar</destName>
<outputDirectory>/</outputDirectory>
<filtered>false</filtered>
</file>
<file>
<source>README.html</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
</files>
<fileSets>
<fileSet>
<includes>
<include>LICENSE.txt</include>
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_storage.sql</include>
<include>contrib/region_storage_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
</assembly>
@@ -1,36 +1,50 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.List;
import java.util.UUID;
public abstract class LocalPlayer implements RegionAssociable {
public abstract class LocalPlayer {
/**
* Get a player's name.
* Get this player's name.
*
* @return The player's name
*/
public abstract String getName();
/**
* Get this player's unique ID.
*
* @return a UUID
*/
public abstract UUID getUniqueId();
/**
* Returns true if the player is inside a group.
* Returns true if this player is inside a group.
*
* @param group The group to check
* @return Whether this player is in {@code group}
@@ -38,57 +52,71 @@ public abstract class LocalPlayer {
public abstract boolean hasGroup(String group);
/**
* Get the player's position.
* Get this player's position.
*
* @return The player's position
*/
public abstract Vector getPosition();
/**
* Kick the player.
* Kick this player.
*
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban the player.
* Ban this player.
*
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
/**
* Send the player a message;
* Send this player a message.
*
* @param msg The message to send to the player
*/
public abstract void printRaw(String msg);
/**
* Get the player's list of groups.
* Get this player's list of groups.
*
* @return The groups this player is in
*/
public abstract String[] getGroups();
/**
* Returns whether a player has permission.
* Returns whether this player has permission.
*
* @param perm The permission to check
* @return Whether this player has {@code perm}
*/
public abstract boolean hasPermission(String perm);
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
boolean member = false;
for (ProtectedRegion region : regions) {
if (region.isOwner(this)) {
return Association.OWNER;
} else if (!member && region.isMember(this)) {
member = true;
}
}
return member ? Association.MEMBER : Association.NON_MEMBER;
}
@Override
public boolean equals(Object obj) {
return obj instanceof LocalPlayer && ((LocalPlayer) obj).getName().equals(getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
}
@@ -1,73 +1,67 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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.blacklist;
import com.sk89q.worldguard.blacklist.action.Action;
import com.sk89q.worldguard.blacklist.action.ActionType;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.event.EventType;
import com.sk89q.worldguard.blacklist.target.TargetMatcher;
import com.sk89q.worldguard.blacklist.target.TargetMatcherParseException;
import com.sk89q.worldguard.blacklist.target.TargetMatcherParser;
import com.sk89q.guavabackport.cache.CacheBuilder;
import com.sk89q.guavabackport.cache.CacheLoader;
import com.sk89q.guavabackport.cache.LoadingCache;
import com.sk89q.worldguard.bukkit.commands.CommandUtils;
import org.bukkit.ChatColor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public abstract class Blacklist {
/**
* List of entries by block ID.
*/
private Map<Integer,List<BlacklistEntry>> blacklist
= new HashMap<Integer,List<BlacklistEntry>>();
/**
* Logger.
*/
private BlacklistLogger blacklistLogger = new BlacklistLogger();
/**
* Last event.
*/
private static final Logger log = Logger.getLogger(Blacklist.class.getCanonicalName());
private MatcherIndex index = MatcherIndex.getEmptyInstance();
private final BlacklistLoggerHandler blacklistLogger = new BlacklistLoggerHandler();
private BlacklistEvent lastEvent;
/**
* Used to prevent flooding.
*/
Map<String,BlacklistTrackedEvent> lastAffected =
new HashMap<String,BlacklistTrackedEvent>();
private boolean useAsWhitelist;
private LoadingCache<String, TrackedEvent> repeatingEventCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(30, TimeUnit.SECONDS)
.build(new CacheLoader<String, TrackedEvent>() {
@Override
public TrackedEvent load(String s) throws Exception {
return new TrackedEvent();
}
});
private final Logger logger;
public Blacklist(Boolean useAsWhitelist, Logger logger) {
public Blacklist(boolean useAsWhitelist) {
this.useAsWhitelist = useAsWhitelist;
this.logger = logger;
}
/**
@@ -76,17 +70,7 @@ public abstract class Blacklist {
* @return whether the blacklist is empty
*/
public boolean isEmpty() {
return blacklist.isEmpty();
}
/**
* Get the entries for an item or list.
*
* @param id The item id to get blacklist information for
* @return The blacklist entries for {@code id}
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
return index.isEmpty();
}
/**
@@ -95,7 +79,7 @@ public abstract class Blacklist {
* @return The number of items in the blacklist
*/
public int getItemCount() {
return blacklist.size();
return index.size();
}
/**
@@ -108,11 +92,11 @@ public abstract class Blacklist {
}
/**
* Get the logger.
* Get the log.
*
* @return The logger used in this blacklist
*/
public BlacklistLogger getLogger() {
public BlacklistLoggerHandler getLogger() {
return blacklistLogger;
}
@@ -125,16 +109,20 @@ public abstract class Blacklist {
* @return Whether the event is allowed
*/
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
List<BlacklistEntry> entries = getEntries(event.getType());
List<BlacklistEntry> entries = index.getEntries(event.getTarget());
if (entries == null) {
return true;
}
boolean ret = true;
for (BlacklistEntry entry : entries) {
if (!entry.check(useAsWhitelist, event, forceRepeat, silent)) {
ret = false;
}
}
return ret;
}
@@ -146,8 +134,8 @@ public abstract class Blacklist {
*/
public void load(File file) throws IOException {
FileReader input = null;
Map<Integer,List<BlacklistEntry>> blacklist =
new HashMap<Integer,List<BlacklistEntry>>();
MatcherIndex.Builder builder = new MatcherIndex.Builder();
TargetMatcherParser targetMatcherParser = new TargetMatcherParser();
try {
input = new FileReader(file);
@@ -159,7 +147,7 @@ public abstract class Blacklist {
line = line.trim();
// Blank line
if (line.length() == 0) {
if (line.isEmpty()) {
continue;
} else if (line.charAt(0) == ';' || line.charAt(0) == '#') {
continue;
@@ -170,35 +158,20 @@ public abstract class Blacklist {
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id;
try {
id = Integer.parseInt(item.trim());
} catch (NumberFormatException e) {
id = getItemID(item.trim());
if (id == 0) {
logger.log(Level.WARNING, "Unknown block name: "
+ item);
break;
}
TargetMatcher matcher = targetMatcherParser.fromInput(item.trim());
BlacklistEntry entry = new BlacklistEntry(this);
builder.add(matcher, entry);
currentEntries.add(entry);
} catch (TargetMatcherParseException e) {
log.log(Level.WARNING, "Could not parse a block/item heading: " + e.getMessage());
}
BlacklistEntry entry = new BlacklistEntry(this);
if (blacklist.containsKey(id)) {
blacklist.get(id).add(entry);
} else {
List<BlacklistEntry> entries = new ArrayList<BlacklistEntry>();
entries.add(entry);
blacklist.put(id, entries);
}
currentEntries.add(entry);
}
} else if (currentEntries != null) {
String[] parts = line.split("=");
if (parts.length == 1) {
logger.log(Level.WARNING, "Found option with no value "
+ file.getName() + " for '" + line + "'");
log.log(Level.WARNING, "Found option with no value " + file.getName() + " for '" + line + "'");
continue;
}
@@ -207,42 +180,43 @@ public abstract class Blacklist {
for (BlacklistEntry entry : currentEntries) {
if (parts[0].equalsIgnoreCase("ignore-groups")) {
entry.setIgnoreGroups(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("ignore-perms")) {
entry.setIgnorePermissions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-break")) {
entry.setBreakActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-destroy-with")) {
entry.setDestroyWithActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-place")) {
entry.setPlaceActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-interact")) {
entry.setInteractActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-use")) {
entry.setUseActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-drop")) {
entry.setDropActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("on-acquire")) {
entry.setAcquireActions(parts[1].split(","));
} else if (parts[0].equalsIgnoreCase("message")) {
entry.setMessage(parts[1].trim());
entry.setMessage(CommandUtils.replaceColorMacros(parts[1].trim()));
} else if (parts[0].equalsIgnoreCase("comment")) {
entry.setComment(parts[1].trim());
entry.setComment(CommandUtils.replaceColorMacros(parts[1].trim()));
} else {
unknownOption = true;
boolean found = false;
for (EventType type : EventType.values()) {
if (type.getRuleName().equalsIgnoreCase(parts[0])) {
entry.getActions(type.getEventClass()).addAll(parseActions(entry, parts[1]));
found = true;
break;
}
}
if (!found) {
unknownOption = true;
}
}
}
if (unknownOption) {
logger.log(Level.WARNING, "Unknown option '" + parts[0]
+ "' in " + file.getName() + " for '" + line + "'");
log.log(Level.WARNING, "Unknown option '" + parts[0] + "' in " + file.getName() + " for '" + line + "'");
}
} else {
logger.log(Level.WARNING, "Found option with no heading "
log.log(Level.WARNING, "Found option with no heading "
+ file.getName() + " for '" + line + "'");
}
}
this.blacklist = blacklist;
this.index = builder.build();
} finally {
try {
if (input != null) {
@@ -253,6 +227,31 @@ public abstract class Blacklist {
}
}
private List<Action> parseActions(BlacklistEntry entry, String raw) {
String[] split = raw.split(",");
List<Action> actions = new ArrayList<Action>();
for (String name : split) {
name = name.trim();
boolean found = false;
for (ActionType type : ActionType.values()) {
if (type.getActionName().equalsIgnoreCase(name)) {
actions.add(type.parseInput(this, entry));
found = true;
break;
}
}
if (!found) {
log.log(Level.WARNING, "Unknown blacklist action: " + name);
}
}
return actions;
}
/**
* Get the last event.
*
@@ -272,10 +271,10 @@ public abstract class Blacklist {
lastEvent = event;
broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + event.getPlayer().getName()
+ ChatColor.LIGHT_PURPLE + event.getCauseName()
+ ChatColor.GOLD + " (" + event.getDescription() + ") "
+ ChatColor.WHITE
+ getFriendlyItemName(event.getType())
+ event.getTarget().getFriendlyName()
+ (comment != null ? " (" + comment + ")" : "") + ".");
}
@@ -286,49 +285,8 @@ public abstract class Blacklist {
*/
public abstract void broadcastNotification(String msg);
/**
* Forget a player.
*
* @param player The player to forget
*/
public void forgetPlayer(LocalPlayer player) {
lastAffected.remove(player.getName());
public LoadingCache<String, TrackedEvent> getRepeatingEventCache() {
return repeatingEventCache;
}
/**
* Forget all players.
*/
public void forgetAllPlayers() {
lastAffected.clear();
}
/**
* Get an item's ID from its name.
*
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
if (type != null) {
return type.getID();
} else {
return -1;
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id The id to look up
* @return The item's friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -1,68 +1,39 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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.blacklist;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.ChatColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.blacklist.action.Action;
import com.sk89q.worldguard.blacklist.action.ActionResult;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.guavabackport.cache.LoadingCache;
import javax.annotation.Nullable;
import java.util.*;
/**
*
* @author sk89q
*/
public class BlacklistEntry {
/**
* Parent blacklist entry.
*/
private Blacklist blacklist;
/**
* List of groups to not affect.
*/
private Set<String> ignoreGroups;
/**
* List of permissions to not affect.
*/
private Set<String> ignorePermissions;
private String[] breakActions;
private String[] destroyWithActions;
private String[] placeActions;
private String[] interactActions;
private String[] useActions;
private String[] dropActions;
private String[] acquireActions;
private Map<Class<? extends BlacklistEvent>, List<Action>> actions = new HashMap<Class<? extends BlacklistEvent>, List<Action>>();
private String message;
private String comment;
@@ -110,104 +81,6 @@ public class BlacklistEntry {
this.ignorePermissions = ignorePermissionsSet;
}
/**
* @return The actions that occur when breaking
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions The actions to occur when breaking
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return The actions that occur when destroying with a specific item
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param actions The actions to occur when destroying with an item
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return The actions that will occur when placing
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions The actions to occur when placing
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return The actions that will occur when interacting
*/
public String[] getInteractActions() {
return interactActions;
}
/**
* @param actions The actions to occur when interacting
*/
public void setInteractActions(String[] actions) {
this.interactActions = actions;
}
/**
* @return The actions that will occur when using
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions The actions to occur when using
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return The actions that will occur when dropping
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions The actions to occur when dropping
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return The actions that will occur when acquiring
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions The actions to occur when acquiring
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
}
/**
* @return the message
*/
@@ -242,7 +115,11 @@ public class BlacklistEntry {
* @param player The player to check
* @return whether this player should be ignored for blacklist blocking
*/
public boolean shouldIgnore(LocalPlayer player) {
public boolean shouldIgnore(@Nullable LocalPlayer player) {
if (player == null) {
return false; // This is the case if the cause is a dispenser, for example
}
if (ignoreGroups != null) {
for (String group : player.getGroups()) {
if (ignoreGroups.contains(group.toLowerCase())) {
@@ -265,40 +142,22 @@ public class BlacklistEntry {
/**
* Get the associated actions with an event.
*
* @param event The event to check
* @param eventCls The event's class
* @return The actions for the given event
*/
private String[] getActions(BlacklistEvent event) {
if (event instanceof BlockBreakBlacklistEvent) {
return breakActions;
} else if (event instanceof BlockPlaceBlacklistEvent) {
return placeActions;
} else if (event instanceof BlockInteractBlacklistEvent) {
return interactActions;
} else if (event instanceof DestroyWithBlacklistEvent) {
return destroyWithActions;
} else if (event instanceof ItemAcquireBlacklistEvent) {
return acquireActions;
} else if (event instanceof ItemDropBlacklistEvent) {
return dropActions;
} else if (event instanceof ItemUseBlacklistEvent) {
return useActions;
} else {
return null;
public List<Action> getActions(Class<? extends BlacklistEvent> eventCls) {
List<Action> ret = actions.get(eventCls);
if (ret == null) {
ret = new ArrayList<Action>();
actions.put(eventCls, ret);
}
return ret;
}
/**
* Method to handle the event.
*
* @param useAsWhitelist Whether this entry is buing used in a whitelist
* @param useAsWhitelist Whether this entry is being used in a whitelist
* @param event The event to check
* @param forceRepeat Whether to force repeating notifications even within the delay limit
* @param silent Whether to prevent notifications from happening
@@ -311,22 +170,20 @@ public class BlacklistEntry {
return true;
}
String name = player.getName();
long now = System.currentTimeMillis();
boolean repeating = false;
String eventCacheKey = event.getCauseName();
LoadingCache<String, TrackedEvent> repeatingEventCache = blacklist.getRepeatingEventCache();
// Check to see whether this event is being repeated
BlacklistTrackedEvent tracked = blacklist.lastAffected.get(name);
if (tracked != null) {
if (tracked.matches(event, now)) {
repeating = true;
}
TrackedEvent tracked = repeatingEventCache.getUnchecked(eventCacheKey);
if (tracked.matches(event)) {
repeating = true;
} else {
blacklist.lastAffected.put(name, new BlacklistTrackedEvent(event, now));
tracked.setLastEvent(event);
tracked.resetTimer();
}
String actions[] = getActions(event);
List<Action> actions = getActions(event.getClass());
boolean ret = !useAsWhitelist;
@@ -335,90 +192,25 @@ public class BlacklistEntry {
return ret;
}
for (String action : actions) {
// Deny
if (action.equalsIgnoreCase("deny")) {
if (silent) {
return false;
}
ret = false;
// Allow
} else if (action.equalsIgnoreCase("allow")) {
if (silent) {
for (Action action : actions) {
ActionResult result = action.apply(event, silent, repeating, forceRepeat);
switch (result) {
case INHERIT:
continue;
case ALLOW:
ret = true;
break;
case DENY:
ret = false;
break;
case ALLOW_OVERRIDE:
return true;
}
ret = true;
// Kick
} else if (action.equalsIgnoreCase("kick")) {
if (silent) {
continue;
}
if (this.message != null) {
player.kick(String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.kick("You can't " + event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
// Ban
} else if (action.equalsIgnoreCase("ban")) {
if (silent) {
continue;
}
if (this.message != null) {
player.ban("Banned: " + String.format(this.message,
getFriendlyItemName(event.getType())));
} else {
player.ban("Banned: You can't "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()));
}
} else if (!silent && (!repeating || forceRepeat)) {
// Notify
if (action.equalsIgnoreCase("notify")) {
blacklist.notify(event, comment);
// Log
} else if (action.equalsIgnoreCase("log")) {
blacklist.getLogger().logEvent(event, comment);
// Tell
} else if (action.equalsIgnoreCase("tell")) {
if (this.message != null) {
player.printRaw(ChatColor.YELLOW +
String.format(message, getFriendlyItemName(event.getType()))
+ ".");
} else {
player.printRaw(ChatColor.YELLOW + "You're not allowed to "
+ event.getDescription() + " "
+ getFriendlyItemName(event.getType()) + ".");
}
}
case DENY_OVERRIDE:
return false;
}
}
return ret;
}
/**
* Get an item's friendly name with its ID.
*
* @param id The id to get a name for
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
}
}
}
@@ -1,47 +1,44 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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.blacklist;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.logger.LoggerHandler;
import java.util.HashSet;
import java.util.Set;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.loggers.BlacklistLoggerHandler;
public class BlacklistLoggerHandler implements LoggerHandler {
/**
*
* @author sk89q
*/
public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* List of logger handlers.
*/
private Set<BlacklistLoggerHandler> handlers
= new HashSet<BlacklistLoggerHandler>();
private Set<LoggerHandler> handlers
= new HashSet<LoggerHandler>();
/**
* Add a handler.
*
* @param handler The handler to add
*/
public void addHandler(BlacklistLoggerHandler handler) {
public void addHandler(LoggerHandler handler) {
handlers.add(handler);
}
@@ -50,7 +47,7 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
*
* @param handler The handler to remove
*/
public void removeHandler(BlacklistLoggerHandler handler) {
public void removeHandler(LoggerHandler handler) {
handlers.remove(handler);
}
@@ -66,8 +63,9 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
*
* @param event The event to log
*/
@Override
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
for (LoggerHandler handler : handlers) {
handler.logEvent(event, comment);
}
}
@@ -75,9 +73,11 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Close the connection.
*/
@Override
public void close() {
for (BlacklistLoggerHandler handler : handlers) {
for (LoggerHandler handler : handlers) {
handler.close();
}
}
}
@@ -1,48 +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.blacklist;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
*
* @author sk89q
*/
public class BlacklistTrackedEvent {
private BlacklistEvent event;
private long time;
/**
* Construct the object.
*
* @param event The event tracked
* @param time The time at which the event occurred
*/
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
this.time = time;
}
public boolean matches(BlacklistEvent other, long now) {
return other.getType() == event.getType()
&& time > now - 3000
&& other.getClass() == event.getClass();
}
}
@@ -0,0 +1,80 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.sk89q.worldguard.blacklist.target.Target;
import com.sk89q.worldguard.blacklist.target.TargetMatcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import static com.google.common.base.Preconditions.checkNotNull;
class MatcherIndex {
private static final MatcherIndex EMPTY_INSTANCE = new MatcherIndex(HashBasedTable.<Integer, TargetMatcher, BlacklistEntry>create());
private final Table<Integer, TargetMatcher, BlacklistEntry> entries;
private MatcherIndex(Table<Integer, TargetMatcher, BlacklistEntry> entries) {
checkNotNull(entries);
this.entries = entries;
}
public List<BlacklistEntry> getEntries(Target target) {
List<BlacklistEntry> found = new ArrayList<BlacklistEntry>();
for (Entry<TargetMatcher, BlacklistEntry> entry : entries.row(target.getTypeId()).entrySet()) {
if (entry.getKey().test(target)) {
found.add(entry.getValue());
}
}
return found;
}
public int size() {
return entries.size();
}
public boolean isEmpty() {
return entries.isEmpty();
}
public static MatcherIndex getEmptyInstance() {
return EMPTY_INSTANCE;
}
public static class Builder {
private final Table<Integer, TargetMatcher, BlacklistEntry> entries = HashBasedTable.create();
public Builder add(TargetMatcher matcher, BlacklistEntry entry) {
checkNotNull(matcher);
checkNotNull(entries);
entries.put(matcher.getMatchedTypeId(), matcher, entry);
return this;
}
public MatcherIndex build() {
return new MatcherIndex(entries);
}
}
}
@@ -0,0 +1,47 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import javax.annotation.Nullable;
class TrackedEvent {
@Nullable
private BlacklistEvent lastEvent;
private long time = 0;
public boolean matches(BlacklistEvent other) {
if (lastEvent == null) {
return false;
}
long now = System.currentTimeMillis();
return other.getEventType() == lastEvent.getEventType() && time > now - 3000;
}
public void resetTimer() {
time = System.currentTimeMillis();
}
public void setLastEvent(@Nullable BlacklistEvent lastEvent) {
this.lastEvent = lastEvent;
}
}
@@ -0,0 +1,28 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
public interface Action {
ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat);
}
@@ -0,0 +1,30 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
public enum ActionResult {
INHERIT,
DENY,
ALLOW,
DENY_OVERRIDE,
ALLOW_OVERRIDE
}
@@ -0,0 +1,81 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
public enum ActionType {
ALLOW("allow") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return AllowAction.getInstance();
}
},
DENY("deny") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return DenyAction.getInstance();
}
},
BAN("ban") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return new BanAction(entry);
}
},
KICK("kick") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return new KickAction(entry);
}
},
LOG("log") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return new LogAction(blacklist, entry);
}
},
NOTIFY("notify") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return new NotifyAction(blacklist, entry);
}
},
TELL("tell") {
@Override
public Action parseInput(Blacklist blacklist, BlacklistEntry entry) {
return new TellAction(entry);
}
};
private final String actionName;
ActionType(String actionName) {
this.actionName = actionName;
}
public abstract Action parseInput(Blacklist blacklist, BlacklistEntry entry);
public String getActionName() {
return actionName;
}
}
@@ -0,0 +1,44 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
public final class AllowAction implements Action {
private static final AllowAction INSTANCE = new AllowAction();
private AllowAction() {
}
@Override
public ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat) {
if (silent) {
return ActionResult.ALLOW_OVERRIDE;
}
return ActionResult.ALLOW;
}
public static AllowAction getInstance() {
return INSTANCE;
}
}
@@ -0,0 +1,55 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import static com.google.common.base.Preconditions.checkNotNull;
public class BanAction implements Action {
private final BlacklistEntry entry;
public BanAction(BlacklistEntry entry) {
checkNotNull(entry);
this.entry = entry;
}
@Override
public ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat) {
if (silent) {
return ActionResult.INHERIT;
}
if (event.getPlayer() != null) {
String message = entry.getMessage();
if (message != null) {
event.getPlayer().ban("Banned: " + String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().ban("Banned: You can't " + event.getDescription() + " " + event.getTarget().getFriendlyName());
}
}
return ActionResult.INHERIT;
}
}
@@ -0,0 +1,44 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
public final class DenyAction implements Action {
private static final DenyAction INSTANCE = new DenyAction();
private DenyAction() {
}
@Override
public ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat) {
if (silent) {
return ActionResult.DENY_OVERRIDE;
}
return ActionResult.DENY;
}
public static DenyAction getInstance() {
return INSTANCE;
}
}
@@ -0,0 +1,55 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import static com.google.common.base.Preconditions.checkNotNull;
public class KickAction implements Action {
private final BlacklistEntry entry;
public KickAction(BlacklistEntry entry) {
checkNotNull(entry);
this.entry = entry;
}
@Override
public ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat) {
if (silent) {
return ActionResult.INHERIT;
}
if (event.getPlayer() != null) {
String message = entry.getMessage();
if (message != null) {
event.getPlayer().kick(String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().kick("You can't " + event.getDescription() + " " + event.getTarget().getFriendlyName());
}
}
return ActionResult.INHERIT;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import static com.google.common.base.Preconditions.checkNotNull;
public class LogAction extends RepeatGuardedAction {
private final Blacklist blacklist;
private final BlacklistEntry entry;
public LogAction(Blacklist blacklist, BlacklistEntry entry) {
checkNotNull(blacklist);
checkNotNull(entry);
this.blacklist = blacklist;
this.entry = entry;
}
@Override
protected ActionResult applyNonRepeated(BlacklistEvent event, boolean silent) {
if (silent) {
return ActionResult.INHERIT;
}
blacklist.getLogger().logEvent(event, entry.getComment());
return ActionResult.INHERIT;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import static com.google.common.base.Preconditions.checkNotNull;
public class NotifyAction extends RepeatGuardedAction {
private final Blacklist blacklist;
private final BlacklistEntry entry;
public NotifyAction(Blacklist blacklist, BlacklistEntry entry) {
checkNotNull(blacklist);
checkNotNull(entry);
this.blacklist = blacklist;
this.entry = entry;
}
@Override
protected ActionResult applyNonRepeated(BlacklistEvent event, boolean silent) {
if (silent) {
return ActionResult.INHERIT;
}
blacklist.notify(event, entry.getComment());
return ActionResult.INHERIT;
}
}
@@ -0,0 +1,37 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
public abstract class RepeatGuardedAction implements Action {
@Override
public final ActionResult apply(BlacklistEvent event, boolean silent, boolean repeating, boolean forceRepeat) {
if (!repeating || forceRepeat) {
return applyNonRepeated(event, silent);
}
return ActionResult.INHERIT;
}
protected abstract ActionResult applyNonRepeated(BlacklistEvent event, boolean silent);
}
@@ -0,0 +1,57 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.action;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import org.bukkit.ChatColor;
import static com.google.common.base.Preconditions.checkNotNull;
public class TellAction extends RepeatGuardedAction {
private final BlacklistEntry entry;
public TellAction(BlacklistEntry entry) {
checkNotNull(entry);
this.entry = entry;
}
@Override
protected ActionResult applyNonRepeated(BlacklistEvent event, boolean silent) {
if (silent) {
return ActionResult.INHERIT;
}
String message = entry.getMessage();
if (event.getPlayer() != null) {
if (message != null) {
event.getPlayer().printRaw(ChatColor.YELLOW + String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().printRaw(ChatColor.YELLOW + "You're not allowed to " + event.getDescription() + " " +
event.getTarget().getFriendlyName() + ".");
}
}
return ActionResult.INHERIT;
}
}
@@ -0,0 +1,77 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
abstract class AbstractBlacklistEvent implements BlacklistEvent {
@Nullable
private final LocalPlayer player;
private final Vector position;
private final Target target;
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
AbstractBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
checkNotNull(position);
checkNotNull(target);
this.player = player;
this.position = position;
this.target = target;
}
@Nullable
@Override
public LocalPlayer getPlayer() {
return player;
}
@Override
public String getCauseName() {
return player != null ? player.getName() : position.toString();
}
@Override
public Vector getPosition() {
return position;
}
@Override
public Target getTarget() {
return target;
}
protected String getPlayerName() {
return player == null ? "(unknown)" : player.getName();
}
}
@@ -0,0 +1,87 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public interface BlacklistEvent {
/**
* Get the player.
*
* @return The player associated with this event
*/
@Nullable
LocalPlayer getPlayer();
/**
* Get the cause name, which is usually the player name.
*
* @return the cause name
*/
String getCauseName();
/**
* Get the position.
*
* @return The position of this event
*/
Vector getPosition();
/**
* Get the position that should be logged.
*
* @return The position that be logged.
*/
Vector getLoggedPosition();
/**
* Get the item type.
*
* @return The type associated with this event
*/
Target getTarget();
/**
* Get a short description such as "break" or "destroy with."
*
* @return The event description
*/
String getDescription();
/**
* Get a message for logger outputs.
*
* @return A logging message
*/
String getLoggerMessage();
/**
* Get the event type.
*
* @return the type
*/
EventType getEventType();
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
abstract class BlockBlacklistEvent extends AbstractBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
BlockBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getLoggerMessage() {
return getPlayerName() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
public Vector getLoggedPosition() {
return getPosition();
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public BlockBreakBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "break";
}
@Override
public EventType getEventType() {
return EventType.BREAK;
}
}
@@ -0,0 +1,56 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class BlockDispenseBlacklistEvent extends BlockBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public BlockDispenseBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "dispense";
}
@Override
public String getLoggerMessage() {
return getPosition() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
public EventType getEventType() {
return EventType.DISPENSE;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public BlockInteractBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "interact with";
}
@Override
public EventType getEventType() {
return EventType.INTERACT;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public BlockPlaceBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "place";
}
@Override
public EventType getEventType() {
return EventType.PLACE;
}
}
@@ -0,0 +1,49 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
public enum EventType {
BREAK(BlockBreakBlacklistEvent.class, "on-break"),
PLACE(BlockPlaceBlacklistEvent.class, "on-place"),
INTERACT(BlockInteractBlacklistEvent.class, "on-interact"),
DISPENSE(BlockDispenseBlacklistEvent.class, "on-dispense"),
DESTROY_WITH(ItemDestroyWithBlacklistEvent.class, "on-destroy-with"),
ACQUIRE(ItemAcquireBlacklistEvent.class, "on-acquire"),
DROP(ItemDropBlacklistEvent.class, "on-drop"),
USE(ItemUseBlacklistEvent.class, "on-use");
private final Class<? extends BlacklistEvent> eventClass;
private final String ruleName;
private EventType(Class<? extends BlacklistEvent> eventClass, String ruleName) {
this.eventClass = eventClass;
this.ruleName = ruleName;
}
public Class<? extends BlacklistEvent> getEventClass() {
return eventClass;
}
public String getRuleName() {
return ruleName;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public ItemAcquireBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "acquire";
}
@Override
public EventType getEventType() {
return EventType.ACQUIRE;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
abstract class ItemBlacklistEvent extends AbstractBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
ItemBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getLoggerMessage() {
return getPlayerName() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
public Vector getLoggedPosition() {
return getPlayer() != null ? getPlayer().getPosition() : getPosition();
}
}
@@ -0,0 +1,57 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class ItemDestroyWithBlacklistEvent extends ItemBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public ItemDestroyWithBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "destroy with";
}
@Override
public EventType getEventType() {
return EventType.DESTROY_WITH;
}
@Override
public Vector getLoggedPosition() {
// Use the block position instead
return getPosition();
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class ItemDropBlacklistEvent extends ItemBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public ItemDropBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "drop";
}
@Override
public EventType getEventType() {
return EventType.DROP;
}
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
public final class ItemUseBlacklistEvent extends ItemBlacklistEvent {
/**
* Construct the object.
*
* @param player The player associated with this event
* @param position The position the event occurred at
* @param target The target of the event
*/
public ItemUseBlacklistEvent(@Nullable LocalPlayer player, Vector position, Target target) {
super(player, position, target);
}
@Override
public String getDescription() {
return "use";
}
@Override
public EventType getEventType() {
return EventType.USE;
}
}
@@ -1,85 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
/**
* Represents a blacklist event.
*
* @author sk89q
*/
public abstract class BlacklistEvent {
private Vector pos;
private int type;
/**
* Holds the player that triggered the event.
*/
private LocalPlayer player;
/**
* Construct the object.
*
* @param player The player associated with this event
* @param pos The position the event occurred at
* @param type The type of item used
*/
public BlacklistEvent(LocalPlayer player, Vector pos, int type) {
this.player = player;
this.pos = pos;
this.type = type;
}
/**
* Get the player.
*
* @return The player associated with this event
*/
public LocalPlayer getPlayer() {
return player;
}
/**
* Get the position.
*
* @return The position of this event
*/
public Vector getPosition() {
return pos;
}
/**
* Get the item type.
*
* @return The type associated with this event
*/
public int getType() {
return type;
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return The event description
*/
public abstract String getDescription();
}
@@ -1,29 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public abstract class BlockBlacklistEvent extends BlacklistEvent {
public BlockBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
public BlockBreakBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "break";
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
public BlockInteractBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "interact with";
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
public BlockPlaceBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "place";
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class DestroyWithBlacklistEvent extends BlacklistEvent {
public DestroyWithBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "destroy with";
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
public ItemAcquireBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "acquire";
}
}
@@ -1,29 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public abstract class ItemBlacklistEvent extends BlacklistEvent {
public ItemBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemDropBlacklistEvent extends ItemBlacklistEvent {
public ItemDropBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "drop";
}
}
@@ -1,34 +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.blacklist.events;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
public class ItemUseBlacklistEvent extends ItemBlacklistEvent {
public ItemUseBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
@Override
public String getDescription() {
return "use";
}
}
@@ -0,0 +1,63 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.logger;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConsoleHandler implements LoggerHandler {
private String worldName;
private final Logger logger;
public ConsoleHandler(String worldName, Logger logger) {
this.worldName = worldName;
this.logger = logger;
}
@Override
public void logEvent(BlacklistEvent event, String comment) {
logger.log(Level.INFO, "[" + worldName + "] " + event.getLoggerMessage() +
(comment != null ? " (" + comment + ")" : ""));
}
/**
* Get an item's friendly name with its ID.
*
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id;
}
}
@Override
public void close() {
}
}
@@ -0,0 +1,125 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.event.EventType;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseHandler implements LoggerHandler {
private final String dsn;
private final String user;
private final String pass;
private final String table;
private final String worldName;
private Connection conn;
private final Logger logger;
/**
* Construct the object.
*
* @param dsn The DSN for the connection
* @param user The username to connect with
* @param pass The password to connect with
* @param table The table to log to
* @param worldName The name of the world to log
* @param logger The logger to log errors to
*/
public DatabaseHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
this.logger = logger;
}
/**
* Gets the database connection.
*
* @return The database connection
* @throws SQLException when the connection cannot be created
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(dsn, user, pass);
}
return conn;
}
/**
* Log an event to the database.
*
* @param eventType The event type to log
* @param player The player associated with the event
* @param pos The location of the event
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(EventType eventType, @Nullable LocalPlayer player, Vector pos, int item, String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, world, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, eventType.name());
stmt.setString(2, worldName);
stmt.setString(3, player != null ? player.getName() : "");
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setInt(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: " + e.getMessage());
}
}
@Override
public void logEvent(BlacklistEvent event, String comment) {
logEvent(event.getEventType(), event.getPlayer(), event.getLoggedPosition(), event.getTarget().getTypeId(), comment);
}
@Override
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ignore) {
}
}
}
@@ -1,23 +1,29 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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.blacklist.loggers;
package com.sk89q.worldguard.blacklist.logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.target.Target;
import java.io.BufferedWriter;
import java.io.File;
@@ -35,54 +41,26 @@ import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
public class FileHandler implements LoggerHandler {
/**
*
* @author sk89q
*/
public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Regex for patterns in the path.
*/
private static Pattern pattern = Pattern.compile("%.");
/**
* Date format.
*/
private static SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Number of files to keep open at a time.
*/
private int cacheSize = 10;
/**
* Path pattern.
*/
private String pathPattern;
/**
* World name.
*/
private String worldName;
/**
* Cache of writers.
*/
private TreeMap<String,FileLoggerWriter> writers =
new TreeMap<String,FileLoggerWriter>();
private TreeMap<String,LogFileWriter> writers = new TreeMap<String,LogFileWriter>();
private final Logger logger;
/**
* Construct the object.
*
* @param pathPattern The pattern for the logflie path
* @param pathPattern The pattern for the log file path
* @param worldName The name of the world
* @param logger The logger used to log errors
*/
public FileLoggerHandler(String pathPattern, String worldName, Logger logger) {
public FileHandler(String pathPattern, String worldName, Logger logger) {
this.pathPattern = pathPattern;
this.worldName = worldName;
this.logger = logger;
@@ -96,7 +74,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
* @param worldName The name of the associated world
* @param logger The logger to log errors with
*/
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
public FileHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
if (cacheSize < 1) {
throw new IllegalArgumentException("Cache size cannot be less than 1");
}
@@ -109,7 +87,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Build the path.
*
* @param playerName The name of the playername
* @param playerName The name of the player
* @return The path for the logfile
*/
private String buildPath(String playerName) {
@@ -178,7 +156,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
String line = "[" + date + "] " + player.getName() + ": " + message
+ (comment != null ? " (" + comment + ")" : "") + "\r\n";
FileLoggerWriter writer = writers.get(path);
LogFileWriter writer = writers.get(path);
// Writer already exists!
if (writer != null) {
@@ -204,17 +182,17 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
BufferedWriter out = new BufferedWriter(stream);
out.write(line);
out.flush();
writer = new FileLoggerWriter(path, out);
writer = new LogFileWriter(path, out);
writers.put(path, writer);
// Check to make sure our cache doesn't get too big!
if (writers.size() > cacheSize) {
Iterator<Map.Entry<String,FileLoggerWriter>> it =
Iterator<Map.Entry<String,LogFileWriter>> it =
writers.entrySet().iterator();
// Remove some entries
for (; it.hasNext(); ) {
Map.Entry<String,FileLoggerWriter> entry = it.next();
Map.Entry<String,LogFileWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
} catch (IOException ignore) {
@@ -244,18 +222,13 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
private void logEvent(BlacklistEvent event, String text, int id, Vector pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + getFriendlyItemName(id)
+ " " + getCoordinates(pos), comment);
private void logEvent(BlacklistEvent event, String text, Target target, Vector pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + target.getFriendlyName() + " " + getCoordinates(pos), comment);
}
/**
* Log an event.
*
* @param event The event to log
*/
@Override
public void logEvent(BlacklistEvent event, String comment) {
logEvent(event, event.getDescription(), event.getType(), event.getPosition(), comment);
logEvent(event, event.getDescription(), event.getTarget(), event.getPosition(), comment);
}
/**
@@ -273,11 +246,9 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
}
}
/**
* Close handles.
*/
@Override
public void close() {
for (Map.Entry<String,FileLoggerWriter> entry : writers.entrySet()) {
for (Map.Entry<String,LogFileWriter> entry : writers.entrySet()) {
try {
entry.getValue().getWriter().close();
} catch (IOException ignore) {
@@ -286,4 +257,5 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
writers.clear();
}
}
@@ -1,42 +1,31 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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.blacklist.loggers;
package com.sk89q.worldguard.blacklist.logger;
import javax.annotation.Nullable;
import java.io.BufferedWriter;
/**
*
* @author sk89q
*/
public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Path.
*/
public class LogFileWriter implements Comparable<LogFileWriter> {
public String path;
/**
* Writer.
*/
private BufferedWriter writer;
/**
* Last use.
*/
private long lastUse;
/**
@@ -45,7 +34,7 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
* @param path The path to write to
* @param writer The writer for the file
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
public LogFileWriter(String path, BufferedWriter writer) {
this.path = path;
this.writer = writer;
lastUse = System.currentTimeMillis();
@@ -81,8 +70,11 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
lastUse = System.currentTimeMillis();
}
public int compareTo(FileLoggerWriter other) {
if (lastUse > other.lastUse) {
@Override
public int compareTo(@Nullable LogFileWriter other) {
if (other == null) {
return 1;
} else if (lastUse > other.lastUse) {
return 1;
} else if (lastUse < other.lastUse) {
return -1;
@@ -90,4 +82,5 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
return 0;
}
}
}
@@ -0,0 +1,42 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.logger;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
/**
* Interface for loggers for the blacklist.
*/
public interface LoggerHandler {
/**
* Log an event.
*
* @param event The event
* @param comment The comment to log with the event
*/
public void logEvent(BlacklistEvent event, String comment);
/**
* Close the logger.
*/
public void close();
}
@@ -1,42 +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.blacklist.loggers;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
/**
* Interface for loggers for the blacklist.
*
* @author sk89q
*/
public interface BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param comment
*/
public void logEvent(BlacklistEvent event, String comment);
/**
* Close the logger.
*/
public void close();
}
@@ -1,128 +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.blacklist.loggers;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
private String worldName;
private final Logger logger;
public ConsoleLoggerHandler(String worldName, Logger logger) {
this.worldName = worldName;
this.logger = logger;
}
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to break " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to place " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to interact with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to destroy with " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to acquire " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to drop " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " tried to use " + getFriendlyItemName(evt.getType())
+ (comment != null ? " (" + comment + ")" : ""));
// Unknown
} else {
logger.log(Level.INFO, "[" + worldName + "] " + event.getPlayer().getName()
+ " caught unknown event: " + event.getClass().getCanonicalName());
}
}
/**
* Get an item's friendly name with its ID.
*
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id;
}
}
/**
* Close the connection.
*/
public void close() {
}
}
@@ -1,205 +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.blacklist.loggers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
* @author sk89q
*/
public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* DSN.
*/
private final String dsn;
/**
* Username.
*/
private final String user;
/**
* Password.
*/
private final String pass;
/**
* Table.
*/
private final String table;
/**
* World name.
*/
private final String worldName;
/**
* Database connection.
*/
private Connection conn;
private final Logger logger;
/**
* Construct the object.
*
* @param dsn The DSN for the connection
* @param user The username to connect with
* @param pass The password to connect with
* @param table The table to log to
* @param worldName The name of the world to log
* @param logger The logger to log errors to
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
this.user = user;
this.pass = pass;
this.table = table;
this.worldName = worldName;
this.logger = logger;
}
/**
* Gets the database connection.
*
* @return The database connection
* @throws SQLException when the connection cannot be created
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(dsn, user, pass);
}
return conn;
}
/**
* Log an event to the database.
*
* @param event The event to log
* @param player The player associated with the event
* @param pos The location of the event
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(String event, LocalPlayer player, Vector pos, int item,
String comment) {
try {
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO " + table
+ "(event, world, player, x, y, z, item, time, comment) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, event);
stmt.setString(2, worldName);
stmt.setString(3, player.getName());
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setInt(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
stmt.executeUpdate();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to log blacklist event to database: "
+ e.getMessage());
}
}
/**
* Log an event.
*
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent("BREAK", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent("PLACE", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent("INTERACT", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent("DESTROY_WITH", evt.getPlayer(), evt.getPosition(),
evt.getType(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent("ACQUIRE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent("DROP", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent("USE", evt.getPlayer(), evt.getPlayer().getPosition(),
evt.getType(), comment);
// Unknown
} else {
logEvent("UNKNOWN", event.getPlayer(), event.getPlayer().getPosition(),
-1, comment);
}
}
/**
* Close the connection.
*/
public void close() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ignore) {
}
}
}
@@ -0,0 +1,28 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import com.google.common.base.Predicate;
/**
* Tests a data value.
*/
public interface DataMask extends Predicate<Short> {
}
@@ -0,0 +1,51 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import com.google.common.base.Predicate;
import static com.google.common.base.Preconditions.checkNotNull;
public class DataValueRangeMatcher implements TargetMatcher {
private final int typeId;
private final Predicate<Short> dataMatcher;
public DataValueRangeMatcher(int typeId, Predicate<Short> dataMatcher) {
checkNotNull(dataMatcher);
this.typeId = typeId;
this.dataMatcher = dataMatcher;
}
@Override
public int getMatchedTypeId() {
return typeId;
}
@Override
public boolean test(Target target) {
return typeId == target.getTypeId() && isDataInRange(target.getData());
}
private boolean isDataInRange(short data) {
return dataMatcher.apply(data);
}
}
@@ -0,0 +1,54 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import com.sk89q.worldedit.blocks.ItemType;
public class MaterialTarget implements Target {
private int id;
private short data;
public MaterialTarget(int id, short data) {
this.id = id;
this.data = data;
}
@Override
public int getTypeId() {
return id;
}
@Override
public short getData() {
return data;
}
@Override
public String getFriendlyName() {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ":" + data + ")";
} else {
return "#" + id + ":" + data;
}
}
}
@@ -0,0 +1,40 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import com.google.common.collect.Range;
import static com.google.common.base.Preconditions.checkNotNull;
public class RangeMask implements DataMask {
private final Range<Short> range;
public RangeMask(Range<Short> range) {
checkNotNull(range);
this.range = range;
}
@Override
public boolean apply(Short data) {
return range.contains(data);
}
}
@@ -0,0 +1,48 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
/**
* A target is something that can have events attached to it.
*/
public interface Target {
/**
* Get the type ID.
*
* @return the type ID
*/
int getTypeId();
/**
* Get the data value.
*
* @return the data value
*/
short getData();
/**
* Get a friendly name to be printed.
*
* @return a friendly name
*/
String getFriendlyName();
}
@@ -0,0 +1,42 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
/**
* Matches a {@link Target}.
*/
public interface TargetMatcher {
/**
* Get the matched type ID, which is merely used for indexing.
*
* @return the type ID
*/
int getMatchedTypeId();
/**
* Return whether the given target is matched by this matcher.
*
* @param target the target
* @return true if matched
*/
boolean test(Target target);
}
@@ -0,0 +1,30 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import static com.google.common.base.Preconditions.checkNotNull;
public class TargetMatcherParseException extends Exception {
public TargetMatcherParseException(String message) {
super(checkNotNull(message));
}
}
@@ -0,0 +1,123 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.sk89q.guavabackport.collect.Range;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.util.Enums;
import org.bukkit.Material;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TargetMatcherParser {
private static final Pattern DATA_VALUE_PATTERN = Pattern.compile("^([^:]+):([^:]+)$");
private static final Pattern LESS_THAN_PATTERN = Pattern.compile("^<=\\s*([0-9]+)$");
private static final Pattern GREATER_THAN_PATTERN = Pattern.compile("^>=\\s*([0-9]+)$");
private static final Pattern RANGE_PATTERN = Pattern.compile("^([0-9]+)\\s*-\\s*([0-9]+)$");
public TargetMatcher fromInput(String input) throws TargetMatcherParseException {
Matcher matcher = DATA_VALUE_PATTERN.matcher(input.trim());
if (matcher.matches()) {
return new DataValueRangeMatcher(parseType(matcher.group(1)), parseDataValueRanges(matcher.group(2)));
} else {
return new WildcardDataMatcher(parseType(input));
}
}
private int parseType(String input) throws TargetMatcherParseException {
input = input.trim();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
int id = getItemID(input);
if (id > 0) {
return id;
}
Material material = Enums.findFuzzyByValue(Material.class, input);
if (material != null) {
return material.getId();
}
throw new TargetMatcherParseException("Unknown block or item name: " + input);
}
}
private Predicate<Short> parseDataValueRanges(String input) throws TargetMatcherParseException {
List<Predicate<Short>> predicates = new ArrayList<Predicate<Short>>();
for (String part : input.split(";")) {
predicates.add(parseRange(part));
}
return Predicates.or(predicates);
}
private Predicate<Short> parseRange(String input) throws TargetMatcherParseException {
input = input.trim();
Matcher matcher;
matcher = LESS_THAN_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.atMost(Short.parseShort(matcher.group(1)));
}
matcher = GREATER_THAN_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.atLeast(Short.parseShort(matcher.group(1)));
}
matcher = RANGE_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.closed(Short.parseShort(matcher.group(1)), Short.parseShort(matcher.group(2)));
}
try {
short s = Short.parseShort(input);
return Range.closed(s, s);
} catch (NumberFormatException e) {
throw new TargetMatcherParseException("Unknown data value range: " + input);
}
}
/**
* Get an item's ID from its name.
*
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
if (type != null) {
return type.getID();
} else {
return -1;
}
}
}
@@ -0,0 +1,40 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.blacklist.target;
public class WildcardDataMatcher implements TargetMatcher {
private final int typeId;
public WildcardDataMatcher(int typeId) {
this.typeId = typeId;
}
@Override
public int getMatchedTypeId() {
return typeId;
}
@Override
public boolean test(Target target) {
return target.getTypeId() == typeId;
}
}
@@ -1,36 +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 com.sk89q.worldguard.blacklist.Blacklist;
public class BukkitBlacklist extends Blacklist {
private WorldGuardPlugin plugin;
public BukkitBlacklist(Boolean useAsWhitelist, WorldGuardPlugin plugin) {
super(useAsWhitelist, plugin.getLogger());
this.plugin = plugin;
}
@Override
public void broadcastNotification(String msg) {
plugin.broadcastNotification(msg);
}
}
@@ -0,0 +1,78 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
class BukkitOfflinePlayer extends LocalPlayer {
private final OfflinePlayer player;
BukkitOfflinePlayer(OfflinePlayer offlinePlayer) {
this.player = offlinePlayer;
}
@Override
public String getName() {
return player.getName();
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean hasGroup(String group) {
return false;
}
@Override
public Vector getPosition() {
return Vector.ZERO;
}
@Override
public void kick(String msg) {
}
@Override
public void ban(String msg) {
}
@Override
public void printRaw(String msg) {
}
@Override
public String[] getGroups() {
return new String[0];
}
@Override
public boolean hasPermission(String perm) {
return false;
}
}
@@ -1,21 +1,21 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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;
@@ -25,18 +25,40 @@ import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
public class BukkitPlayer extends LocalPlayer {
private Player player;
private WorldGuardPlugin plugin;
private final WorldGuardPlugin plugin;
private final Player player;
private final String name;
private final boolean silenced;
public BukkitPlayer(WorldGuardPlugin plugin, Player player) {
this(plugin, player, false);
}
BukkitPlayer(WorldGuardPlugin plugin, Player player, boolean silenced) {
checkNotNull(plugin);
checkNotNull(player);
this.plugin = plugin;
this.player = player;
// getName() takes longer than before in newer versions of Minecraft
this.name = player.getName();
this.silenced = silenced;
}
@Override
public String getName() {
return player.getName();
return name;
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
@@ -52,13 +74,17 @@ public class BukkitPlayer extends LocalPlayer {
@Override
public void kick(String msg) {
player.kickPlayer(msg);
if (!silenced) {
player.kickPlayer(msg);
}
}
@Override
public void ban(String msg) {
player.setBanned(true);
player.kickPlayer(msg);
if (!silenced) {
player.setBanned(true);
player.kickPlayer(msg);
}
}
@Override
@@ -68,11 +94,18 @@ public class BukkitPlayer extends LocalPlayer {
@Override
public void printRaw(String msg) {
player.sendMessage(msg);
if (!silenced) {
player.sendMessage(msg);
}
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
public Player getPlayer() {
return player;
}
}
@@ -1,40 +1,49 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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 com.google.common.collect.ImmutableList;
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 com.sk89q.worldguard.blacklist.target.MaterialTarget;
import com.sk89q.worldguard.blacklist.target.Target;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
public class BukkitUtil {
private static Method ONLINE_PLAYERS_METHOD;
private BukkitUtil() {
}
@@ -80,6 +89,20 @@ public class BukkitUtil {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Create a dummy region that encompasses the size of a chunk.
*
* @param chunk The chunk
* @return The dummy region
*/
public static ProtectedRegion toRegion(Chunk chunk) {
World world = chunk.getWorld();
int minX = chunk.getX() << 4;
int minZ = chunk.getZ() << 4;
return new ProtectedCuboidRegion("_", new BlockVector(minX, 0, minZ), new BlockVector(minX + 15, world.getMaxHeight(), minZ + 15));
}
/**
* Matches one player based on name.
*
@@ -152,6 +175,17 @@ public class BukkitUtil {
return (item.getDurability() & 0x3F) == 0;
}
/**
* Get just the potion effect bits. This is to work around bugs with potion
* parsing.
*
* @param item item
* @return new bits
*/
public static int getPotionEffectBits(ItemStack item) {
return item.getDurability() & 0x3F;
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
@@ -231,6 +265,14 @@ public class BukkitUtil {
str = str.replace("&2", ChatColor.GRAY.toString());
str = str.replace("&w", ChatColor.WHITE.toString());
str = str.replace("&k", ChatColor.MAGIC.toString());
str = str.replace("&l", ChatColor.BOLD.toString());
str = str.replace("&m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("&n", ChatColor.UNDERLINE.toString());
str = str.replace("&o", ChatColor.ITALIC.toString());
str = str.replace("&x", ChatColor.RESET.toString());
return str;
}
@@ -244,26 +286,12 @@ public class BukkitUtil {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingSand
|| entity instanceof FallingBlock
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
/**
* Returns whether our running CraftBukkit already supports
* the HangingEvent instead of the PaintingEvent
*
* @return true if the hanging event is supported
*/
public static boolean hasHangingEvent() {
Class<?> tmp = null;
try {
tmp = Class.forName("org.bukkit.event.hanging.HangingEvent");
} catch (ClassNotFoundException ignored) { }
return (tmp != null);
}
/**
* Search an enum for a value, and return the first one found. Return null if the
* enum entry is not found.
@@ -282,4 +310,92 @@ public class BukkitUtil {
return null;
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @return a target
*/
public static Target createTarget(Block block) {
checkNotNull(block);
return new MaterialTarget(block.getTypeId(), block.getData());
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @param material a fallback material
* @return a target
*/
public static Target createTarget(Block block, Material material) {
checkNotNull(material);
if (block.getType() == material) {
return new MaterialTarget(block.getTypeId(), block.getData());
} else {
return new MaterialTarget(material.getId(), (short) 0);
}
}
/**
* Get a blacklist target for the given item.
*
* @param item the item
* @return a target
*/
public static Target createTarget(ItemStack item) {
checkNotNull(item);
return new MaterialTarget(item.getTypeId(), item.getDurability());
}
/**
* Get a blacklist target for the given material.
*
* @param material the material
* @return a target
*/
public static Target createTarget(Material material) {
checkNotNull(material);
return new MaterialTarget(material.getId(), (short) 0);
}
/**
* Get a collection of the currently online players.
*
* @return The online players
*/
@SuppressWarnings("unchecked")
public static Collection<? extends Player> getOnlinePlayers() {
try {
return Bukkit.getServer().getOnlinePlayers();
} catch (NoSuchMethodError ignored) {
}
try {
if (ONLINE_PLAYERS_METHOD == null) {
ONLINE_PLAYERS_METHOD = getOnlinePlayersMethod();
}
Object result = ONLINE_PLAYERS_METHOD.invoke(Bukkit.getServer());
if (result instanceof Player[]) {
return ImmutableList.copyOf((Player[]) result);
} else if (result instanceof Collection<?>) {
return (Collection<? extends Player>) result;
} else {
throw new RuntimeException("Result of getOnlinePlayers() call was not a known data type");
}
} catch (Exception e) {
throw new RuntimeException("WorldGuard is not compatible with this version of Bukkit", e);
}
}
private static Method getOnlinePlayersMethod() throws NoSuchMethodException {
try {
return Server.class.getMethod("getOnlinePlayers");
} catch (NoSuchMethodException e1) {
return Server.class.getMethod("_INVALID_getOnlinePlayers");
}
}
}
@@ -1,41 +1,44 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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 com.google.common.collect.ImmutableMap;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.protection.managers.storage.DriverType;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.protection.managers.storage.file.DirectoryYamlDriver;
import com.sk89q.worldguard.protection.managers.storage.sql.SQLDriver;
import com.sk89q.worldguard.session.handler.WaterBreathing;
import com.sk89q.worldguard.util.report.Unreported;
import com.sk89q.worldguard.util.sql.DataSourceConfig;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import 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.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import java.util.logging.Logger;
/**
* Represents the global configuration and also delegates configuration
@@ -46,6 +49,8 @@ import com.sk89q.worldguard.blacklist.Blacklist;
*/
public class ConfigurationManager {
private static final Logger log = Logger.getLogger(ConfigurationManager.class.getCanonicalName());
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
@@ -67,50 +72,31 @@ public class ConfigurationManager {
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Holds configurations for different worlds.
*/
private ConcurrentMap<String, WorldConfiguration> worlds;
/**
* The global configuration for use when loading worlds
*/
private YAMLProcessor config;
/**
* 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>();
@Unreported private WorldGuardPlugin plugin;
@Unreported private ConcurrentMap<String, WorldConfiguration> worlds;
@Unreported private YAMLProcessor config;
private boolean hasCommandBookGodMode = false;
public boolean useRegionsScheduler;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean useGodPermission;
public boolean useGodGroup;
public boolean useAmphibiousGroup;
public boolean usePlayerMove;
public boolean usePlayerTeleports;
public boolean deopOnJoin;
public boolean blockInGameOp;
public Map<String, String> hostKeys = new HashMap<String, String>();
public boolean migrateRegionsToUuid;
public boolean keepUnresolvedNames;
@Unreported 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;
@Unreported public RegionDriver selectedRegionStoreDriver;
@Unreported public Map<DriverType, RegionDriver> regionStoreDriverMap;
/**
* Construct the object.
@@ -122,6 +108,25 @@ public class ConfigurationManager {
this.worlds = new ConcurrentHashMap<String, WorldConfiguration>();
}
/**
* Get the folder for storing data files and configuration.
*
* @return the data folder
*/
public File getDataFolder() {
return plugin.getDataFolder();
}
/**
* Get the folder for storing data files and configuration for each
* world.
*
* @return the data folder
*/
public File getWorldsDataFolder() {
return new File(getDataFolder(), "worlds");
}
/**
* Load the configuration.
*/
@@ -135,25 +140,23 @@ public class ConfigurationManager {
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for global config: ");
log.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));
migrateRegionsToUuid = config.getBoolean("regions.uuid-migration.perform-on-next-start", true);
keepUnresolvedNames = config.getBoolean("regions.uuid-migration.keep-names-that-lack-uuids", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
useGodPermission = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
useGodGroup = config.getBoolean("auto-invincible-group", false);
useAmphibiousGroup = config.getBoolean("auto-no-drowning-group", false);
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
usePlayerMove = config.getBoolean("use-player-move-event", true);
usePlayerTeleports = config.getBoolean("use-player-teleports", true);
deopOnJoin = config.getBoolean(
"security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean(
"security.block-in-game-op-command", false);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
hostKeys = new HashMap<String, String>();
Object hostKeysRaw = config.getProperty("host-keys");
@@ -167,12 +170,25 @@ public class ConfigurationManager {
}
}
useSqlDatabase = config.getBoolean(
"regions.sql.use", false);
// ====================================================================
// Region store drivers
// ====================================================================
sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
sqlUsername = config.getString("regions.sql.username", "worldguard");
sqlPassword = config.getString("regions.sql.password", "worldguard");
boolean useSqlDatabase = config.getBoolean("regions.sql.use", false);
String sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
String sqlUsername = config.getString("regions.sql.username", "worldguard");
String sqlPassword = config.getString("regions.sql.password", "worldguard");
String sqlTablePrefix = config.getString("regions.sql.table-prefix", "");
DataSourceConfig dataSourceConfig = new DataSourceConfig(sqlDsn, sqlUsername, sqlPassword, sqlTablePrefix);
SQLDriver sqlDriver = new SQLDriver(dataSourceConfig);
DirectoryYamlDriver yamlDriver = new DirectoryYamlDriver(getWorldsDataFolder(), "regions.yml");
this.regionStoreDriverMap = ImmutableMap.<DriverType, RegionDriver>builder()
.put(DriverType.MYSQL, sqlDriver)
.put(DriverType.YAML, yamlDriver)
.build();
this.selectedRegionStoreDriver = useSqlDatabase ? sqlDriver : yamlDriver;
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
@@ -180,10 +196,6 @@ public class ConfigurationManager {
}
config.setHeader(CONFIG_HEADER);
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
}
}
/**
@@ -193,6 +205,13 @@ public class ConfigurationManager {
worlds.clear();
}
public void disableUuidMigration() {
config.setProperty("regions.uuid-migration.perform-on-next-start", false);
if (!config.save()) {
log.severe("Error saving configuration!");
}
}
/**
* Get the configuration for a world.
*
@@ -215,47 +234,6 @@ public class ConfigurationManager {
return config;
}
/**
* Forget a player.
*
* @param player The player to forget about
*/
public void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
// The blacklist needs to forget players
Blacklist bl = entry.getValue().getBlacklist();
if (bl != null) {
bl.forgetPlayer(player);
}
}
hasGodMode.remove(player.getName());
hasAmphibious.remove(player.getName());
}
/**
* Enable god mode for a player.
*
* @param player The player to enable god mode for.
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
/**
* Disable god mode for a player.
*
* @param player The player to disable godmode for
*/
@Deprecated
public void disableGodMode(Player player) {
hasGodMode.remove(player.getName());
}
/**
* Check to see if god mode is enabled for a player.
*
@@ -263,13 +241,7 @@ public class ConfigurationManager {
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(Player player) {
if (hasCommandBookGodMode) {
GodComponent god = CommandBook.inst().getComponentManager().getComponent(GodComponent.class);
if (god != null) {
return god.hasGodMode(player);
}
}
return hasGodMode.contains(player.getName());
return plugin.getSessionManager().get(player).isInvincible(player);
}
/**
@@ -278,7 +250,10 @@ public class ConfigurationManager {
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(Player player) {
hasAmphibious.add(player.getName());
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(true);
}
}
/**
@@ -287,7 +262,10 @@ public class ConfigurationManager {
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(Player player) {
hasAmphibious.remove(player.getName());
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(false);
}
}
/**
@@ -297,7 +275,8 @@ public class ConfigurationManager {
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
return handler != null && handler.hasWaterBreathing();
}
public void updateCommandBookGodMode() {
@@ -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;
}
}
@@ -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;
}
}
@@ -0,0 +1,153 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.UseBlockEvent;
import com.sk89q.worldguard.bukkit.event.entity.DamageEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.UseEntityEvent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import javax.annotation.Nullable;
import static com.sk89q.worldguard.bukkit.event.DelegateEvents.setSilent;
import static com.sk89q.worldguard.bukkit.util.Events.fireAndTestCancel;
/**
* A helper class to query whether a block or entity is protected by
* WorldGuard.
*/
public class ProtectionQuery {
/**
* Test whether a block can be placed at a given location.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param location the location of the block
* @param newMaterial the new material
* @return true if the action is permitted
*/
public boolean testBlockPlace(@Nullable Object cause, Location location, Material newMaterial) {
return !fireAndTestCancel(setSilent(new PlaceBlockEvent(null, Cause.create(cause), location, newMaterial)));
}
/**
* Test whether a block can be broken.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param block the block broken
* @return true if the action is permitted
*/
public boolean testBlockBreak(@Nullable Object cause, Block block) {
return !fireAndTestCancel(setSilent(new BreakBlockEvent(null, Cause.create(cause), block)));
}
/**
* Test whether a block can be interacted with.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param block the block that is interacted with
* @return true if the action is permitted
*/
public boolean testBlockInteract(@Nullable Object cause, Block block) {
return !fireAndTestCancel(setSilent(new UseBlockEvent(null, Cause.create(cause), block)));
}
/**
* Test whether an entity can be placed.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param location the location that the entity will be spawned at
* @param type the type that is to be spawned
* @return true if the action is permitted
*/
public boolean testEntityPlace(@Nullable Object cause, Location location, EntityType type) {
return !fireAndTestCancel(setSilent(new SpawnEntityEvent(null, Cause.create(cause), location, type)));
}
/**
* Test whether an entity can be destroyed.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param entity the entity broken
* @return true if the action is permitted
*/
public boolean testEntityDestroy(@Nullable Object cause, Entity entity) {
return !fireAndTestCancel(setSilent(new SpawnEntityEvent(null, Cause.create(cause), entity)));
}
/**
* Test whether an entity can be interacted with.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param entity the entity interacted with
* @return true if the action is permitted
*/
public boolean testEntityInteract(@Nullable Object cause, Entity entity) {
return !fireAndTestCancel(setSilent(new UseEntityEvent(null, Cause.create(cause), entity)));
}
/**
* Test whether an entity can be damaged.
*
* <p>The cause does not have to be a player. It can be {@code null}
* if the cause is not known, although the checks will executed
* assuming that the actor is a non-member of all regions.</p>
*
* @param cause the cause, which can be a block, an entity, or a player, or {@code null} if unknown
* @param entity the entity damaged
* @return true if the action is permitted
*/
public boolean testEntityDamage(@Nullable Object cause, Entity entity) {
return !fireAndTestCancel(setSilent(new DamageEntityEvent(null, Cause.create(cause), entity)));
}
}
@@ -0,0 +1,117 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.RegionResultSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Keeps a cache of {@link RegionResultSet}s. The contents of the cache
* must be externally invalidated occasionally (and frequently).
*
* <p>This class is fully concurrent.</p>
*/
class QueryCache {
private final ConcurrentMap<CacheKey, ApplicableRegionSet> cache = new ConcurrentHashMap<CacheKey, ApplicableRegionSet>(16, 0.75f, 2);
/**
* Get from the cache a {@code ApplicableRegionSet} if an entry exists;
* otherwise, query the given manager for a result and cache it.
*
* @param manager the region manager
* @param location the location
* @return a result
*/
public ApplicableRegionSet queryContains(RegionManager manager, Location location) {
checkNotNull(manager);
checkNotNull(location);
CacheKey key = new CacheKey(location);
ApplicableRegionSet result = cache.get(key);
if (result == null) {
result = manager.getApplicableRegions(location);
cache.put(key, result);
}
return result;
}
/**
* Invalidate the cache and clear its contents.
*/
public void invalidateAll() {
cache.clear();
}
/**
* Key object for the map.
*/
private static class CacheKey {
private final World world;
private final int x;
private final int y;
private final int z;
private final int hashCode;
private CacheKey(Location location) {
this.world = location.getWorld();
this.x = location.getBlockX();
this.y = location.getBlockY();
this.z = location.getBlockZ();
// Pre-compute hash code
int result = world.hashCode();
result = 31 * result + x;
result = 31 * result + y;
result = 31 * result + z;
this.hashCode = result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
if (x != cacheKey.x) return false;
if (y != cacheKey.y) return false;
if (z != cacheKey.z) return false;
if (!world.equals(cacheKey.world)) return false;
return true;
}
@Override
public int hashCode() {
return hashCode;
}
}
}
@@ -0,0 +1,311 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit;
import com.sk89q.worldedit.Vector2D;
import com.sk89q.worldguard.protection.managers.RegionContainerImpl;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.migration.Migration;
import com.sk89q.worldguard.protection.managers.migration.MigrationException;
import com.sk89q.worldguard.protection.managers.migration.UUIDMigration;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A region container creates {@link RegionManager}s for loaded worlds, which
* allows access to the region data of a world. Generally, only data is
* loaded for worlds that are loaded in the server.
*
* <p>This class is thread safe and its contents can be accessed from
* multiple concurrent threads.</p>
*
* <p>An instance of this class can be retrieved using
* {@link WorldGuardPlugin#getRegionContainer()}.</p>
*/
public class RegionContainer {
private static final Logger log = Logger.getLogger(RegionContainer.class.getCanonicalName());
/**
* Invalidation frequency in ticks.
*/
private static final int CACHE_INVALIDATION_INTERVAL = 2;
private final Object lock = new Object();
private final WorldGuardPlugin plugin;
private final QueryCache cache = new QueryCache();
private RegionContainerImpl container;
/**
* Create a new instance.
*
* @param plugin the plugin
*/
RegionContainer(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Initialize the region container.
*/
void initialize() {
ConfigurationManager config = plugin.getGlobalStateManager();
container = new RegionContainerImpl(config.selectedRegionStoreDriver);
// Migrate to UUIDs
autoMigrate();
loadWorlds();
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
load(event.getWorld());
}
@EventHandler
public void onWorldUnload(WorldUnloadEvent event) {
unload(event.getWorld());
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
RegionManager manager = get(event.getWorld());
if (manager != null) {
Chunk chunk = event.getChunk();
manager.loadChunk(new Vector2D(chunk.getX(), chunk.getZ()));
}
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
RegionManager manager = get(event.getWorld());
if (manager != null) {
Chunk chunk = event.getChunk();
manager.unloadChunk(new Vector2D(chunk.getX(), chunk.getZ()));
}
}
}, plugin);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
cache.invalidateAll();
}
}, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
}
/**
* Save data and unload.
*/
void unload() {
synchronized (lock) {
container.unloadAll();
}
}
/**
* Get the region store driver.
*
* @return the driver
*/
public RegionDriver getDriver() {
return container.getDriver();
}
/**
* Try loading the region managers for all currently loaded worlds.
*/
private void loadWorlds() {
synchronized (lock) {
for (World world : Bukkit.getServer().getWorlds()) {
load(world);
}
}
}
/**
* Reload the region container.
*
* <p>This method may block until the data for all loaded worlds has been
* unloaded and new data has been loaded.</p>
*/
public void reload() {
synchronized (lock) {
unload();
loadWorlds();
}
}
/**
* Load the region data for a world if it has not been loaded already.
*
* @param world the world
* @return a region manager, either returned from the cache or newly loaded
*/
@Nullable
private RegionManager load(World world) {
checkNotNull(world);
WorldConfiguration config = plugin.getGlobalStateManager().get(world);
if (!config.useRegions) {
return null;
}
RegionManager manager;
synchronized (lock) {
manager = container.load(world.getName());
if (manager != null) {
// Bias the region data for loaded chunks
List<Vector2D> positions = new ArrayList<Vector2D>();
for (Chunk chunk : world.getLoadedChunks()) {
positions.add(new Vector2D(chunk.getX(), chunk.getZ()));
}
manager.loadChunks(positions);
}
}
return manager;
}
/**
* Unload the region data for a world.
*
* @param world a world
*/
void unload(World world) {
checkNotNull(world);
synchronized (lock) {
container.unload(world.getName());
}
}
/**
* Get the region manager for a world if one exists.
*
* <p>If you wish to make queries and performance is more important
* than accuracy, use {@link #createQuery()} instead.</p>
*
* <p>This method may return {@code null} if region data for the given
* world has not been loaded, has failed to load, or support for regions
* has been disabled.</p>
*
* @param world the world
* @return a region manager, or {@code null} if one is not available
*/
@Nullable
public RegionManager get(World world) {
return container.get(world.getName());
}
/**
* Get an immutable list of loaded {@link RegionManager}s.
*
* @return a list of managers
*/
public List<RegionManager> getLoaded() {
return Collections.unmodifiableList(container.getLoaded());
}
/**
* Get the a set of region managers that are failing to save.
*
* @return a set of region managers
*/
public Set<RegionManager> getSaveFailures() {
return container.getSaveFailures();
}
/**
* Create a new region query.
*
* @return a new query
*/
public RegionQuery createQuery() {
return new RegionQuery(plugin, cache);
}
/**
* Execute a migration and block any loading of region data during
* the migration.
*
* @param migration the migration
* @throws MigrationException thrown by the migration on error
*/
public void migrate(Migration migration) throws MigrationException {
checkNotNull(migration);
synchronized (lock) {
try {
log.info("Unloading and saving region data that is currently loaded...");
unload();
migration.migrate();
} finally {
log.info("Loading region data for loaded worlds...");
loadWorlds();
}
}
}
/**
* Execute auto-migration.
*/
private void autoMigrate() {
ConfigurationManager config = plugin.getGlobalStateManager();
if (config.migrateRegionsToUuid) {
RegionDriver driver = getDriver();
UUIDMigration migrator = new UUIDMigration(driver, plugin.getProfileService());
migrator.setKeepUnresolvedNames(config.keepUnresolvedNames);
try {
migrate(migrator);
log.info("Regions saved after UUID migration! This won't happen again unless " +
"you change the relevant configuration option in WorldGuard's config.");
config.disableUuidMigration();
} catch (MigrationException e) {
log.log(Level.WARNING, "Failed to execute the migration", e);
}
}
}
}
@@ -0,0 +1,373 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.FailedLoadRegionSet;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.PermissiveRegionSet;
import com.sk89q.worldguard.protection.RegionResultSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
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.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.util.Collection;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* This object allows easy spatial queries involving region data for the
* purpose of implementing protection / region flag checks.
*
* <p>Results may be cached for brief amounts of time. If you want to get
* data for the purposes of changing it, use of this class is not recommended.
* Some of the return values of the methods may be simulated to reduce
* boilerplate code related to implementing protection, meaning that false
* data is returned.</p>
*/
public class RegionQuery {
private final WorldGuardPlugin plugin;
private final ConfigurationManager config;
@SuppressWarnings("deprecation")
private final GlobalRegionManager globalManager;
private final QueryCache cache;
/**
* Create a new instance.
*
* @param plugin the plugin
* @param cache the query cache
*/
RegionQuery(WorldGuardPlugin plugin, QueryCache cache) {
checkNotNull(plugin);
checkNotNull(cache);
this.plugin = plugin;
this.config = plugin.getGlobalStateManager();
this.cache = cache;
//noinspection deprecation
this.globalManager = plugin.getGlobalRegionManager();
}
/**
* Query for regions containing the given location.
*
* <p>An instance of {@link RegionResultSet} will always be returned,
* even if regions are disabled or region data failed to load. An
* appropriate "virtual" set will be returned in such a case
* (for example, if regions are disabled, the returned set
* would permit all activities).</p>
*
* @param location the location
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(Location location) {
checkNotNull(location);
World world = location.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return PermissiveRegionSet.getInstance();
}
RegionManager manager = globalManager.get(location.getWorld());
if (manager != null) {
return cache.queryContains(manager, location);
} else {
return FailedLoadRegionSet.getInstance();
}
}
/**
* Returns true if the BUILD flag allows the action in the location, but it
* can be overridden by a list of other flags. The BUILD flag will not
* override the other flags, but the other flags can override BUILD. If
* neither BUILD or any of the flags permit the action, then false will
* be returned.
*
* <p>Use this method when checking flags that are related to build
* protection. For example, lighting fire in a region should not be
* permitted unless the player is a member of the region or the
* LIGHTER flag allows it. However, the LIGHTER flag should be able
* to allow lighting fires even if BUILD is set to DENY.</p>
*
* <p>How this method works (BUILD can be overridden by other flags but
* not the other way around) is inconsistent, but it's required for
* legacy reasons.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testBuild(Location location, Player player, StateFlag... flag) {
if (flag.length == 0) {
return testState(location, player, DefaultFlag.BUILD);
}
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, player, DefaultFlag.BUILD)),
queryState(location, player, flag)));
}
/**
* Returns true if the BUILD flag allows the action in the location, but it
* can be overridden by a list of other flags. The BUILD flag will not
* override the other flags, but the other flags can override BUILD. If
* neither BUILD or any of the flags permit the action, then false will
* be returned.
*
* <p>Use this method when checking flags that are related to build
* protection. For example, lighting fire in a region should not be
* permitted unless the player is a member of the region or the
* LIGHTER flag allows it. However, the LIGHTER flag should be able
* to allow lighting fires even if BUILD is set to DENY.</p>
*
* <p>How this method works (BUILD can be overridden by other flags but
* not the other way around) is inconsistent, but it's required for
* legacy reasons.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testBuild(Location location, RegionAssociable associable, StateFlag... flag) {
if (flag.length == 0) {
return testState(location, associable, DefaultFlag.BUILD);
}
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, associable, DefaultFlag.BUILD)),
queryState(location, associable, flag)));
}
/**
* Test whether the (effective) value for a list of state flags equals
* {@code ALLOW}.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testState(Location location, @Nullable Player player, StateFlag... flag) {
return StateFlag.test(queryState(location, player, flag));
}
/**
* Test whether the (effective) value for a list of state flags equals
* {@code ALLOW}.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testState(Location location, @Nullable RegionAssociable associable, StateFlag... flag) {
return StateFlag.test(queryState(location, associable, flag));
}
/**
* Get the (effective) value for a list of state flags. The rules of
* states is observed here; that is, {@code DENY} overrides {@code ALLOW},
* and {@code ALLOW} overrides {@code NONE}. One flag may override another.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region groups that apply
* @param flags a list of flags to check
* @return a state
* @see RegionResultSet#queryState(RegionAssociable, StateFlag...)
*/
@Nullable
public State queryState(Location location, @Nullable Player player, StateFlag... flags) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryState(localPlayer, flags);
}
/**
* Get the (effective) value for a list of state flags. The rules of
* states is observed here; that is, {@code DENY} overrides {@code ALLOW},
* and {@code ALLOW} overrides {@code NONE}. One flag may override another.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* @param location the location
* @param associable an optional associable
* @param flags a list of flags to check
* @return a state
* @see RegionResultSet#queryState(RegionAssociable, StateFlag...)
*/
@Nullable
public State queryState(Location location, @Nullable RegionAssociable associable, StateFlag... flags) {
return getApplicableRegions(location).queryState(associable, flags);
}
/**
* Get the effective value for a flag. If there are multiple values
* (for example, multiple overlapping regions with
* the same priority may have the same flag set), then the selected
* (or "winning") value will depend on the flag type.
*
* <p>Only some flag types actually have a strategy for picking the
* "best value." For most types, the actual value that is chosen to be
* returned is undefined (it could be any value). As of writing, the only
* type of flag that actually has a strategy for picking a value is the
* {@link StateFlag}.</p>
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return a value, which could be {@code null}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
@Nullable
public <V> V queryValue(Location location, @Nullable Player player, Flag<V> flag) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryValue(localPlayer, flag);
}
/**
* Get the effective value for a flag. If there are multiple values
* (for example, multiple overlapping regions with
* the same priority may have the same flag set), then the selected
* (or "winning") value will depend on the flag type.
*
* <p>Only some flag types actually have a strategy for picking the
* "best value." For most types, the actual value that is chosen to be
* returned is undefined (it could be any value). As of writing, the only
* type of flag that actually has a strategy for picking a value is the
* {@link StateFlag}.</p>
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return a value, which could be {@code null}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
@Nullable
public <V> V queryValue(Location location, @Nullable RegionAssociable associable, Flag<V> flag) {
return getApplicableRegions(location).queryValue(associable, flag);
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
* from the collection will be used.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return a collection of values
* @see RegionResultSet#queryAllValues(RegionAssociable, Flag)
*/
public <V> Collection<V> queryAllValues(Location location, @Nullable Player player, Flag<V> flag) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryAllValues(localPlayer, flag);
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
* from the collection will be used.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return a collection of values
* @see RegionResultSet#queryAllValues(RegionAssociable, Flag)
*/
public <V> Collection<V> queryAllValues(Location location, @Nullable RegionAssociable associable, Flag<V> flag) {
return getApplicableRegions(location).queryAllValues(associable, flag);
}
}
@@ -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;
}
}
}
@@ -1,337 +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.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.LogListBlock;
public class ReportWriter {
private static final SimpleDateFormat dateFmt =
new SimpleDateFormat("yyyy-MM-dd kk:mm Z");
private Date date = new Date();
private StringBuilder output = new StringBuilder();
public ReportWriter(WorldGuardPlugin plugin) {
appendReportHeader(plugin);
appendServerInformation(plugin.getServer());
appendPluginInformation(plugin.getServer().getPluginManager().getPlugins());
appendWorldInformation(plugin.getServer().getWorlds());
appendGlobalConfiguration(plugin.getGlobalStateManager());
appendWorldConfigurations(plugin, plugin.getServer().getWorlds(),
plugin.getGlobalRegionManager(), plugin.getGlobalStateManager());
appendln("-------------");
appendln("END OF REPORT");
appendln();
}
protected static String repeat(String str, int n) {
if(str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
protected void appendln(String text) {
output.append(text);
output.append("\r\n");
}
protected void appendln(String text, Object ... args) {
output.append(String.format(text, args));
output.append("\r\n");
}
protected void append(LogListBlock log) {
output.append(log.toString());
}
protected void appendln() {
output.append("\r\n");
}
protected void appendHeader(String text) {
String rule = repeat("-", text.length());
output.append(rule);
output.append("\r\n");
appendln(text);
output.append(rule);
output.append("\r\n");
appendln();
}
private void appendReportHeader(WorldGuardPlugin plugin) {
appendln("WorldGuard Configuration Report");
appendln("Generated " + dateFmt.format(date));
appendln();
appendln("Version: " + plugin.getDescription().getVersion());
appendln();
}
private void appendGlobalConfiguration(ConfigurationManager config) {
appendHeader("Global Configuration");
LogListBlock log = new LogListBlock();
LogListBlock configLog = log.putChild("Configuration");
Class<? extends ConfigurationManager> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
if (field.getName().equalsIgnoreCase("CONFIG_HEADER")) continue;
Object val = field.get(config);
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException ignore) {
}
}
append(log);
appendln();
}
private void appendServerInformation(Server server) {
appendHeader("Server Information");
LogListBlock log = new LogListBlock();
Runtime runtime = Runtime.getRuntime();
log.put("Java", "%s %s (%s)",
System.getProperty("java.vendor"),
System.getProperty("java.version"),
System.getProperty("java.vendor.url"));
log.put("Operating system", "%s %s (%s)",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
log.put("Available processors", runtime.availableProcessors());
log.put("Free memory", runtime.freeMemory() / 1024 / 1024 + " MB");
log.put("Max memory", runtime.maxMemory() / 1024 / 1024 + " MB");
log.put("Total memory", runtime.totalMemory() / 1024 / 1024 + " MB");
log.put("Server ID", server.getServerId());
log.put("Server name", server.getServerName());
log.put("Implementation", server.getVersion());
//log.put("Address", server.getIp(), server.getPort());
log.put("Player count", "%d/%d",
server.getOnlinePlayers().length, server.getMaxPlayers());
append(log);
appendln();
}
private void appendPluginInformation(Plugin[] plugins) {
appendHeader("Plugins (" + plugins.length + ")");
LogListBlock log = new LogListBlock();
for (Plugin plugin : plugins) {
log.put(plugin.getDescription().getName(), plugin.getDescription().getVersion());
}
append(log);
appendln();
/*appendHeader("Plugin Information");
log = new LogListBlock();
for (Plugin plugin : plugins) {
log.putChild(plugin.getDescription().getName())
.put("Data folder", plugin.getDataFolder())
.put("Website", plugin.getDescription().getWebsite())
.put("Entry point", plugin.getDescription().getMain());
}
append(log);
appendln();*/
}
private void appendWorldInformation(List<World> worlds) {
appendHeader("Worlds");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
int loadedChunkCount = world.getLoadedChunks().length;
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock entitiesLog = worldLog.putChild("Entities");
infoLog.put("Seed", world.getSeed());
infoLog.put("Environment", world.getEnvironment().toString());
infoLog.put("Player count", world.getPlayers().size());
infoLog.put("Entity count", world.getEntities().size());
infoLog.put("Loaded chunk count", loadedChunkCount);
infoLog.put("Spawn location", world.getSpawnLocation());
infoLog.put("Raw time", world.getFullTime());
Map<Class<? extends Entity>, Integer> entityCounts =
new HashMap<Class<? extends Entity>, Integer>();
// Collect entities
for (Entity entity : world.getEntities()) {
Class<? extends Entity> cls = entity.getClass();
if (entityCounts.containsKey(cls)) {
entityCounts.put(cls, entityCounts.get(cls) + 1);
} else {
entityCounts.put(cls, 1);
}
}
// Print entities
for (Map.Entry<Class<? extends Entity>, Integer> entry
: entityCounts.entrySet()) {
entitiesLog.put(entry.getKey().getSimpleName(),
"%d [%f]",
entry.getValue(),
(float) (entry.getValue() / (double) loadedChunkCount));
}
i++;
}
append(log);
appendln();
}
private void appendWorldConfigurations(WorldGuardPlugin plugin, List<World> worlds,
GlobalRegionManager regionMgr, ConfigurationManager mgr) {
appendHeader("World Configurations");
LogListBlock log = new LogListBlock();
int i = 0;
for (World world : worlds) {
LogListBlock worldLog = log.putChild(world.getName() + " (" + i + ")");
LogListBlock infoLog = worldLog.putChild("Information");
LogListBlock configLog = worldLog.putChild("Configuration");
LogListBlock blacklistLog = worldLog.putChild("Blacklist");
LogListBlock regionsLog = worldLog.putChild("Region manager");
infoLog.put("Configuration file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/config.yml")).getAbsoluteFile());
infoLog.put("Blacklist file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/blacklist.txt")).getAbsoluteFile());
infoLog.put("Regions file", (new File(plugin.getDataFolder(), "worlds/"
+ world.getName() + "/regions.yml")).getAbsoluteFile());
WorldConfiguration config = mgr.get(world);
Class<? extends WorldConfiguration> cls = config.getClass();
for (Field field : cls.getFields()) {
try {
Object val = field.get(config);
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException ignore) {
}
}
if (config.getBlacklist() == null) {
blacklistLog.put("State", "DISABLED");
} else {
blacklistLog.put("State", "Enabled");
blacklistLog.put("Number of items",
config.getBlacklist().getItemCount());
blacklistLog.put("Is whitelist",
config.getBlacklist().isWhitelist());
}
RegionManager worldRegions = regionMgr.get(world);
regionsLog.put("Type", worldRegions.getClass().getCanonicalName());
regionsLog.put("Number of regions", worldRegions.getRegions().size());
LogListBlock globalRegionLog = regionsLog.putChild("Global region");
ProtectedRegion globalRegion = worldRegions.getRegion("__global__");
if (globalRegion == null) {
globalRegionLog.put("Status", "UNDEFINED");
} else {
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (flag instanceof StateFlag) {
globalRegionLog.put(flag.getName(),
globalRegion.getFlag(flag));
}
}
}
}
append(log);
appendln();
}
public void write(File file) throws IOException {
FileWriter writer = null;
BufferedWriter out;
try {
writer = new FileWriter(file);
out = new BufferedWriter(writer);
out.write(output.toString());
out.close();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
@Override
public String toString() {
return output.toString();
}
}
@@ -1,24 +1,24 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the WorldGuard team and contributors
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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
* 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 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
* GNU General Public License for more details.
* This program is 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/>.
*/
* 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.Bukkit;
import org.bukkit.World;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -42,7 +42,16 @@ public class WGBukkit {
* @return the WorldGuard plugin or null
*/
public static WorldGuardPlugin getPlugin() {
return (WorldGuardPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
return WorldGuardPlugin.inst();
}
/**
* Set cache to null for reload WorldGuardPlugin
* @deprecated instance is now stored directly in {@link WorldGuardPlugin}
*/
@Deprecated
public static void cleanCache() {
// do nothing - plugin instance is stored in plugin class now
}
/**
@@ -53,12 +62,10 @@ public class WGBukkit {
* @return a region manager or null
*/
public static RegionManager getRegionManager(World world) {
WorldGuardPlugin plugin = getPlugin();
if (plugin == null) {
if (getPlugin() == null) {
return null;
}
return plugin.getRegionManager(world);
return WorldGuardPlugin.inst().getRegionManager(world);
}
}
@@ -1,19 +1,19 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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/>.
*/
@@ -22,22 +22,30 @@ package com.sk89q.worldguard.bukkit;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
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.blacklist.BlacklistLoggerHandler;
import com.sk89q.worldguard.blacklist.logger.ConsoleHandler;
import com.sk89q.worldguard.blacklist.logger.DatabaseHandler;
import com.sk89q.worldguard.blacklist.logger.FileHandler;
import com.sk89q.worldguard.blacklist.target.TargetMatcherParseException;
import com.sk89q.worldguard.blacklist.target.TargetMatcherParser;
import com.sk89q.worldguard.bukkit.commands.CommandUtils;
import com.sk89q.worldguard.bukkit.internal.BukkitBlacklist;
import com.sk89q.worldguard.bukkit.internal.TargetMatcherSet;
import com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.chest.SignChestProtection;
import com.sk89q.worldguard.util.report.Unreported;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.yaml.snakeyaml.parser.ParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Holds the configuration for individual worlds.
@@ -47,6 +55,9 @@ import java.util.logging.Level;
*/
public class WorldConfiguration {
private static final Logger log = Logger.getLogger(WorldConfiguration.class.getCanonicalName());
private static final TargetMatcherParser matcherParser = new TargetMatcherParser();
public static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's world configuration file\r\n" +
"#\r\n" +
@@ -58,18 +69,21 @@ public class WorldConfiguration {
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private WorldGuardPlugin plugin;
@Unreported private WorldGuardPlugin plugin;
private String worldName;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
@Unreported private String worldName;
@Unreported private YAMLProcessor parentConfig;
@Unreported private YAMLProcessor config;
private File blacklistFile;
private Blacklist blacklist;
private ChestProtection chestProtection = new SignChestProtection();
@Unreported private Blacklist blacklist;
@Unreported private ChestProtection chestProtection = new SignChestProtection();
/* Configuration data start */
public boolean summaryOnStart;
public boolean opPermissions;
public boolean buildPermissions;
public String buildPermissionDenyMessage = "";
public boolean fireSpreadDisableToggle;
public boolean itemDurability;
public boolean simulateSponge;
@@ -98,12 +112,15 @@ public class WorldConfiguration {
public boolean blockWitherSkullExplosions;
public boolean blockWitherSkullBlockDamage;
public boolean blockEnderDragonBlockDamage;
public boolean blockEnderDragonPortalCreation;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockOtherExplosions;
public boolean blockEntityPaintingDestroy;
public boolean blockEntityItemFrameDestroy;
public boolean blockPluginSpawning;
public boolean blockGroundSlimes;
public boolean blockZombieDoorDestruction;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
@@ -118,8 +135,10 @@ public class WorldConfiguration {
public boolean disableMobDamage;
public boolean useRegions;
public boolean highFreqFlags;
public boolean checkLiquidFlow;
public int regionWand;
public Set<EntityType> blockCreatureSpawn;
public boolean allowTamedSpawns;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
@@ -149,10 +168,19 @@ public class WorldConfiguration {
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableMyceliumSpread;
public boolean disableVineGrowth;
public boolean disableEndermanGriefing;
public boolean disableSnowmanTrails;
public boolean disableSoilDehydration;
public Set<Integer> allowedSnowFallOver;
public boolean regionInvinciblityRemovesMobs;
public boolean fakePlayerBuildOverride;
public boolean explosionFlagCancellation;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
public boolean strictEntitySpawn;
public TargetMatcherSet allowAllInteract;
public TargetMatcherSet blockUseAtFeet;
private Map<String, Integer> maxRegionCounts;
@@ -180,7 +208,9 @@ public class WorldConfiguration {
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
if (summaryOnStart) {
log.info("Loaded configuration for world '" + worldName + "'");
}
}
private boolean getBoolean(String node, boolean def) {
@@ -238,6 +268,26 @@ public class WorldConfiguration {
return res;
}
private TargetMatcherSet getTargetMatchers(String node) {
TargetMatcherSet set = new TargetMatcherSet();
List<String> inputs = parentConfig.getStringList(node, null);
if (inputs == null || inputs.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
return set;
}
for (String input : inputs) {
try {
set.add(matcherParser.fromInput(input));
} catch (TargetMatcherParseException e) {
log.warning("Failed to parse the block / item type specified as '" + input + "'");
}
}
return set;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res = parentConfig.getStringList(node, def);
@@ -282,12 +332,24 @@ public class WorldConfiguration {
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for world " + worldName + ": ");
log.severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
} catch (ParserException e) {
log.severe("Error parsing configuration for world " + worldName + ". ");
throw e;
}
summaryOnStart = getBoolean("summary-on-start", true);
opPermissions = getBoolean("op-permissions", true);
buildPermissions = getBoolean("build-permission-nodes.enable", false);
buildPermissionDenyMessage = CommandUtils.replaceColorMacros(
getString("build-permission-nodes.deny-message", "&eSorry, but you are not permitted to do that here."));
strictEntitySpawn = getBoolean("event-handling.block-entity-spawns-with-untraceable-cause", false);
allowAllInteract = getTargetMatchers("event-handling.interaction-whitelist");
blockUseAtFeet = getTargetMatchers("event-handling.emit-block-use-at-feet");
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
@@ -298,14 +360,14 @@ public class WorldConfiguration {
PotionEffectType effect = PotionEffectType.getByName(potionName);
if (effect == null) {
plugin.getLogger().warning("Unknown potion effect type '" + potionName + "'");
log.warning("Unknown potion effect type '" + potionName + "'");
} else {
blockPotions.add(effect);
}
}
blockPotionsAlways = getBoolean("gameplay.block-potions-overly-reliably", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
simulateSponge = getBoolean("simulation.sponge.enable", false);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
@@ -334,14 +396,19 @@ public class WorldConfiguration {
blockWitherSkullExplosions = getBoolean("mobs.block-wither-skull-explosions", false);
blockWitherSkullBlockDamage = getBoolean("mobs.block-wither-skull-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
allowTamedSpawns = getBoolean("mobs.allow-tamed-spawns", true);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
disableSnowmanTrails = getBoolean("mobs.disable-snowman-trails", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockEntityItemFrameDestroy = getBoolean("mobs.block-item-frame-destroy", false);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
blockGroundSlimes = getBoolean("mobs.block-above-ground-slimes", false);
blockOtherExplosions = getBoolean("mobs.block-other-explosions", false);
blockZombieDoorDestruction = getBoolean("mobs.block-zombie-door-destruction", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -380,10 +447,16 @@ public class WorldConfiguration {
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-growth", false);
disableSoilDehydration = getBoolean("dynamics.disable-soil-dehydration", false);
allowedSnowFallOver = new HashSet<Integer>(getIntList("dynamics.snow-fall-blocks", null));
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
fakePlayerBuildOverride = getBoolean("regions.fake-player-build-override", true);
explosionFlagCancellation = getBoolean("regions.explosion-flags-block-entity-damage", true);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
checkLiquidFlow = getBoolean("regions.protect-against-liquid-flow", false);
regionWand = getInt("regions.wand", 334);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
@@ -410,9 +483,9 @@ public class WorldConfiguration {
EntityType creature = EntityType.fromName(creatureName);
if (creature == null) {
plugin.getLogger().warning("Unknown mob type '" + creatureName + "'");
log.warning("Unknown mob type '" + creatureName + "'");
} else if (!creature.isAlive()) {
plugin.getLogger().warning("Entity type '" + creatureName + "' is not a creature");
log.warning("Entity type '" + creatureName + "' is not a creature");
} else {
blockCreatureSpawn.add(creature);
}
@@ -452,52 +525,54 @@ public class WorldConfiguration {
this.blacklist = null;
} else {
this.blacklist = blist;
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
if (summaryOnStart) {
log.log(Level.INFO, "Blacklist loaded.");
}
BlacklistLogger blacklistLogger = blist.getLogger();
BlacklistLoggerHandler blacklistLogger = blist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName, plugin.getLogger()));
blacklistLogger.addHandler(new DatabaseHandler(dsn, user, pass, table, worldName, log));
}
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName, plugin.getLogger()));
blacklistLogger.addHandler(new ConsoleHandler(worldName, log));
}
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger());
FileHandler handler =
new FileHandler(logFilePattern, logFileCacheSize, worldName, log);
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist.");
log.log(Level.WARNING, "WorldGuard blacklist does not exist.");
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: "
log.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
if (summaryOnStart) {
log.log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockLighter
log.log(Level.INFO, blockLighter
? "(" + worldName + ") Lighters are blocked."
: "(" + worldName + ") Lighters are PERMITTED.");
plugin.getLogger().log(Level.INFO, preventLavaFire
log.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.");
log.log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
plugin.getLogger().log(Level.INFO, "(" + worldName
log.log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
plugin.getLogger().log(Level.INFO, "(" + worldName
log.log(Level.INFO, "(" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
@@ -563,7 +638,9 @@ public class WorldConfiguration {
for (String group : plugin.getGroups(player)) {
if (maxRegionCounts.containsKey(group)) {
int groupMax = maxRegionCounts.get(group);
if (max < groupMax) max = groupMax;
if (max < groupMax) {
max = groupMax;
}
}
}
if (max <= -1) {
@@ -1,880 +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 com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import java.util.Set;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
private EntityType fireballType;
private EntityType witherType;
private EntityType witherSkullType;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
fireballType = BukkitUtil.tryEnum(EntityType.class, "LARGE_FIREBALL", "FIREBALL");
witherType = BukkitUtil.tryEnum(EntityType.class, "WITHER");
witherSkullType = BukkitUtil.tryEnum(EntityType.class, "WITHER_SKULL");
}
/**
* Register events.
*/
public 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());
if (block.getTypeId() == BlockID.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
}
}
@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());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
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.getDamager() instanceof Projectile) {
onEntityDamageByProjectile(event);
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
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(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event, true);
} else if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP ,localPlayer)) {
tryCancelPVPEvent((Player) attacker, player, event, false);
}
}
}
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 (!mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event, true);
} else if (!set.allows(DefaultFlag.PVP, localPlayer)) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event, false);
}
} 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());
// Check Invincible
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
// Check Mob
if (attacker != null && attacker instanceof LivingEntity && !(attacker instanceof Player)) {
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;
}
}
}
// Check Player
if (event.getDamager() instanceof EnderPearl || event.getDamager() instanceof Snowball) 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(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event, true);
} else if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)) {
tryCancelPVPEvent((Player) attacker, player, event, false);
}
}
}
}
}
@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());
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());
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());
event.setCancelled(true);
return;
}
if (wcfg.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (wcfg.disableDrowningDamage && type == DamageCause.DROWNING) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (entity instanceof Player) {
Player player = (Player) entity;
if (cfg.hasGodMode(player) || (wcfg.useRegions && RegionQueryUtil.isInvincible(plugin, player))) {
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();
event.setCancelled(true);
return;
}
// Not all explosions come from an entity
if (ent != null) {
if (ent.getType() == witherType) {
if (wcfg.blockWitherBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockWitherExplosions) {
event.setCancelled(true);
return;
}
}
if (ent.getType() == witherSkullType) {
if (wcfg.blockWitherSkullBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockWitherSkullExplosions) {
event.setCancelled(true);
return;
}
}
if (ent instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
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;
}
}
}
}
}
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();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
ent.remove();
event.setCancelled(true);
return;
}
if (event.getEntityType() == witherType) {
if (wcfg.blockWitherExplosions) {
event.setCancelled(true);
return;
}
}
else if (event.getEntityType() == witherSkullType) {
if (wcfg.blockWitherSkullExplosions) {
event.setCancelled(true);
return;
}
}
else if (event.getEntityType() == fireballType) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
}
else if (event.getEntityType() == EntityType.CREEPER) {
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
}
else if (event.getEntityType() == EntityType.PRIMED_TNT) {
if (wcfg.blockTNTExplosions) {
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)) {
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;
}
}
if (wcfg.blockGroundSlimes && entityType == EntityType.SLIME
&& eventLoc.getY() >= 60
&& event.getSpawnReason() == SpawnReason.NATURAL) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disablePigZap) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
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 onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
}
/**
* 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();
if (ent instanceof Enderman) {
if (event.getTo() == Material.AIR) {
// pickup
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;
}
}
} 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;
}
}
}
} else if (ent.getType() == witherType) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.blockWitherBlockDamage || wcfg.blockWitherExplosions) {
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);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
Entity entity = event.getEntity();
ThrownPotion potion = event.getPotion();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.blockPotionsAlways && wcfg.blockPotions.size() > 0) {
boolean blocked = false;
for (PotionEffect effect : potion.getEffects()) {
if (wcfg.blockPotions.contains(effect.getType())) {
blocked = true;
break;
}
}
if (blocked) {
event.setCancelled(true);
return;
}
}
GlobalRegionManager regionMan = plugin.getGlobalRegionManager();
int blockedEntities = 0;
for (LivingEntity e : event.getAffectedEntities()) {
if (!regionMan.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, boolean aggressorTriggered) {
final DisallowedPVPEvent disallowedPVPEvent = new DisallowedPVPEvent(attackingPlayer, defendingPlayer, event);
plugin.getServer().getPluginManager().callEvent(disallowedPVPEvent);
if (!disallowedPVPEvent.isCancelled()) {
if (aggressorTriggered) attackingPlayer.sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
else attackingPlayer.sendMessage(ChatColor.DARK_RED + "That player is in a no-PvP area.");
event.setCancelled(true);
}
}
}
@@ -1,206 +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 org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
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.HangingBreakEvent.RemoveCause;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
/**
* Listener for painting related events.
*
* @author BangL <henno.rickowski@gmail.com>
*/
public class WorldGuardHangingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardHangingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public 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);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
Entity removerEntity = entityEvent.getRemover();
if (removerEntity instanceof Player) {
Player player = (Player) removerEntity;
if (wcfg.getBlacklist() != null) {
if (hanging instanceof Painting
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (hanging instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, hanging.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (removerEntity instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, hanging.getLocation())) {
event.setCancelled(true);
return;
}
}
if (hanging instanceof Painting
&& (wcfg.blockEntityPaintingDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame
&& (wcfg.blockEntityItemFrameDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
}
}
} else {
// Explosions from mobs are not covered by HangingBreakByEntity
if (hanging instanceof Painting && wcfg.blockEntityPaintingDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame && wcfg.blockEntityItemFrameDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingPlace(HangingPlaceEvent 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 (event.getEntity() instanceof Painting
&& !wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (event.getEntity() instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), 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 onEntityInteract(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getRightClicked();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.useRegions && (entity instanceof ItemFrame || entity instanceof Painting)) {
if (!plugin.getGlobalRegionManager().canBuild(player, entity.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (entity instanceof ItemFrame
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
} else if (entity instanceof Painting
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
}
}
}
}
@@ -1,174 +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 org.bukkit.ChatColor;
import org.bukkit.Warning;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
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 org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
/**
* Listener for painting related events.
*
* @author sk89q
* @deprecated Use {@link com.sk89q.worldguard.bukkit.WorldGuardHangingListener} instead.
*/
@Deprecated
@Warning(reason="This listener has been replaced by WorldGuardHangingListener")
public class WorldGuardPaintingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardPaintingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@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
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation()))) {
event.setCancelled(true);
}
}
}
@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 onEntityInteract(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getRightClicked();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (wcfg.useRegions && entity instanceof Painting) {
if (!plugin.getGlobalRegionManager().canBuild(player, entity.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (entity instanceof Painting
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,44 +1,61 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* 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
* 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 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.
* This program is 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 General Public License
* 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 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;
import java.util.ArrayList;
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.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.squirrelid.cache.HashMapCache;
import com.sk89q.squirrelid.cache.ProfileCache;
import com.sk89q.squirrelid.cache.SQLiteCache;
import com.sk89q.squirrelid.resolver.*;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.commands.GeneralCommands;
import com.sk89q.worldguard.bukkit.commands.ProtectionCommands;
import com.sk89q.worldguard.bukkit.commands.ToggleCommands;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.listener.*;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.util.UnresolvedNamesException;
import com.sk89q.worldguard.session.SessionManager;
import com.sk89q.worldguard.util.concurrent.EvenMoreExecutors;
import com.sk89q.worldguard.util.logging.ClassSourceValidator;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import com.sk89q.worldguard.util.task.SimpleSupervisor;
import com.sk89q.worldguard.util.task.Supervisor;
import com.sk89q.worldguard.util.task.Task;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
@@ -50,53 +67,43 @@ import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
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 javax.annotation.Nullable;
import java.io.*;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
/**
* 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 static final Logger log = Logger.getLogger(WorldGuardPlugin.class.getCanonicalName());
private static WorldGuardPlugin inst;
private final CommandsManager<CommandSender> commands;
/**
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Used for scheduling flags.
*/
private FlagStateManager flagStateManager;
private final ConfigurationManager configuration = new ConfigurationManager(this);
private final RegionContainer regionContainer = new RegionContainer(this);
private final GlobalRegionManager globalRegionManager = new GlobalRegionManager(this, regionContainer);
private SessionManager sessionManager;
private final Supervisor supervisor = new SimpleSupervisor();
private ListeningExecutorService executorService;
private ProfileService profileService;
private ProfileCache profileCache;
private PlayerMoveListener playerMoveListener;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
*/
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new GlobalRegionManager(this);
final WorldGuardPlugin plugin = this;
final WorldGuardPlugin plugin = inst = this;
commands = new CommandsManager<CommandSender>() {
@Override
public boolean hasPermission(CommandSender player, String perm) {
@@ -105,15 +112,36 @@ public class WorldGuardPlugin extends JavaPlugin {
};
}
/**
* Get the current instance of WorldGuard
* @return WorldGuardPlugin instance
*/
public static WorldGuardPlugin inst() {
return inst;
}
/**
* Called on plugin enable.
*/
@Override
@SuppressWarnings("deprecation")
public void onEnable() {
configureLogger();
getDataFolder().mkdirs(); // Need to create the plugins/WorldGuard folder
executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20));
sessionManager = new SessionManager(this);
// Set the proper command injector
commands.setInjector(new SimpleInjector(this));
// Catch bad things being done by naughty plugins that include
// WorldGuard's classes
ClassSourceValidator verifier = new ClassSourceValidator(this);
verifier.reportMismatches(ImmutableList.of(WGBukkit.class, ProtectedRegion.class, ProtectedCuboidRegion.class, Flag.class));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
@@ -128,45 +156,55 @@ public class WorldGuardPlugin extends JavaPlugin {
}
}, 0L);
// Need to create the plugins/WorldGuard folder
getDataFolder().mkdirs();
File cacheDir = new File(getDataFolder(), "cache");
cacheDir.mkdirs();
try {
profileCache = new SQLiteCache(new File(cacheDir, "profiles.sqlite"));
} catch (IOException e) {
log.log(Level.WARNING, "Failed to initialize SQLite profile cache");
profileCache = new HashMapCache();
}
profileService = new CacheForwardingService(
new CombinedProfileService(
BukkitPlayerService.getInstance(),
HttpRepositoryService.forMinecraft()),
profileCache);
PermissionsResolverManager.initialize(this);
configuration.load();
// This must be done before configuration is loaded
LegacyWorldGuardMigration.migrateBlacklist(this);
log.info("Loading region data...");
regionContainer.initialize();
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);
}
getServer().getScheduler().scheduleSyncRepeatingTask(this, sessionManager, SessionManager.RUN_DELAY, SessionManager.RUN_DELAY);
// Register events
getServer().getPluginManager().registerEvents(sessionManager, this);
(new WorldGuardPlayerListener(this)).registerEvents();
(new WorldGuardBlockListener(this)).registerEvents();
(new WorldGuardEntityListener(this)).registerEvents();
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
if (hasHangingEvent()) {
(new WorldGuardHangingListener(this)).registerEvents();
} else {
(new WorldGuardPaintingListener(this)).registerEvents();
(new WorldGuardHangingListener(this)).registerEvents();
// Modules
(playerMoveListener = new PlayerMoveListener(this)).registerEvents();
(new BlacklistListener(this)).registerEvents();
(new ChestProtectionListener(this)).registerEvents();
(new RegionProtectionListener(this)).registerEvents();
(new RegionFlagsListener(this)).registerEvents();
(new WorldRulesListener(this)).registerEvents();
(new BlockedPotionsListener(this)).registerEvents();
(new EventAbstractionListener(this)).registerEvents();
(new PlayerModesListener(this)).registerEvents();
(new BuildPermissionListener(this)).registerEvents();
(new InvincibilityListener(this)).registerEvents();
if ("true".equalsIgnoreCase(System.getProperty("worldguard.debug.listener"))) {
(new DebuggingListener(this, log)).registerEvents();
}
configuration.updateCommandBookGodMode();
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
@@ -180,32 +218,44 @@ public class WorldGuardPlugin extends JavaPlugin {
}
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);
}
}
for (Player player : BukkitUtil.getOnlinePlayers()) {
ProcessPlayerEvent event = new ProcessPlayerEvent(player);
Events.fire(event);
}
}
/**
* Called on plugin disable.
*/
@Override
public void onDisable() {
globalRegionManager.unload();
executorService.shutdown();
try {
log.log(Level.INFO, "Shutting down executor and waiting for any pending tasks...");
List<Task<?>> tasks = supervisor.getTasks();
if (!tasks.isEmpty()) {
StringBuilder builder = new StringBuilder("Known tasks:");
for (Task<?> task : tasks) {
builder.append("\n");
builder.append(task.getName());
}
log.log(Level.INFO, builder.toString());
}
Futures.successfulAsList(tasks).get();
executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
log.log(Level.WARNING, "Some tasks failed while waiting for remaining tasks to finish", e);
}
regionContainer.unload();
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
@@ -216,12 +266,7 @@ public class WorldGuardPlugin extends JavaPlugin {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
if (e.getCause() instanceof NumberFormatException) {
sender.sendMessage(ChatColor.RED + "Number expected, string received instead.");
} else {
sender.sendMessage(ChatColor.RED + "An error has occurred. See console.");
e.printStackTrace();
}
sender.sendMessage(ChatColor.RED + convertThrowable(e.getCause()));
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
@@ -229,15 +274,54 @@ public class WorldGuardPlugin extends JavaPlugin {
return true;
}
/**
* Convert the throwable into a somewhat friendly message.
*
* @param throwable the throwable
* @return a message
*/
public String convertThrowable(@Nullable Throwable throwable) {
if (throwable instanceof NumberFormatException) {
return "Number expected, string received instead.";
} else if (throwable instanceof StorageException) {
log.log(Level.WARNING, "Error loading/saving regions", throwable);
return "Region data could not be loaded/saved: " + throwable.getMessage();
} else if (throwable instanceof RejectedExecutionException) {
return "There are currently too many tasks queued to add yours. Use /wg running to list queued and running tasks.";
} else if (throwable instanceof CancellationException) {
return "WorldGuard: Task was cancelled";
} else if (throwable instanceof InterruptedException) {
return "WorldGuard: Task was interrupted";
} else if (throwable instanceof UnresolvedNamesException) {
return throwable.getMessage();
} else if (throwable instanceof CommandException) {
return throwable.getMessage();
} else {
log.log(Level.WARNING, "WorldGuard encountered an unexpected error", throwable);
return "WorldGuard: An unexpected error occurred! Please see the server console.";
}
}
/**
* Get the GlobalRegionManager.
*
* @return The plugin's global region manager
* @return the plugin's global region manager
* @deprecated use {@link #getRegionContainer()}
*/
@Deprecated
public GlobalRegionManager getGlobalRegionManager() {
return globalRegionManager;
}
/**
* Get the object that manages region data.
*
* @return the region container
*/
public RegionContainer getRegionContainer() {
return regionContainer;
}
/**
* Get the WorldGuard Configuration.
*
@@ -254,8 +338,8 @@ public class WorldGuardPlugin extends JavaPlugin {
*
* @return The flag state manager
*/
public FlagStateManager getFlagStateManager() {
return flagStateManager;
public SessionManager getSessionManager() {
return sessionManager;
}
/**
@@ -267,6 +351,43 @@ public class WorldGuardPlugin extends JavaPlugin {
return configuration;
}
/**
* Get the supervisor.
*
* @return the supervisor
*/
public Supervisor getSupervisor() {
return supervisor;
}
/**
* Get the global executor service for internal usage (please use your
* own executor service).
*
* @return the global executor service
*/
public ListeningExecutorService getExecutorService() {
return executorService;
}
/**
* Get the profile lookup service.
*
* @return the profile lookup service
*/
public ProfileService getProfileService() {
return profileService;
}
/**
* Get the profile cache.
*
* @return the profile cache
*/
public ProfileCache getProfileCache() {
return profileCache;
}
/**
* Check whether a player is in a group.
* This calls the corresponding method in PermissionsResolverManager
@@ -352,7 +473,7 @@ public class WorldGuardPlugin extends JavaPlugin {
// Invoke the permissions resolver
if (sender instanceof Player) {
Player player = (Player) sender;
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player.getName(), perm);
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player, perm);
}
return false;
@@ -400,7 +521,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* @return A {@link List} of players who match {@code filter}
*/
public List<Player> matchPlayerNames(String filter) {
Player[] players = getServer().getOnlinePlayers();
Collection<? extends Player> players = BukkitUtil.getOnlinePlayers();
filter = filter.toLowerCase();
@@ -453,7 +574,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* @return {@code players} as an {@link Iterable}
* @throws CommandException If {@code players} is empty
*/
protected Iterable<Player> checkPlayerMatch(List<Player> players)
protected Iterable<? extends Player> checkPlayerMatch(List<? extends Player> players)
throws CommandException {
// Check to see if there were any matches
if (players.size() == 0) {
@@ -478,15 +599,15 @@ public class WorldGuardPlugin extends JavaPlugin {
* @return iterator for players
* @throws CommandException if no matches are found
*/
public Iterable<Player> matchPlayers(CommandSender source, String filter)
public Iterable<? extends Player> matchPlayers(CommandSender source, String filter)
throws CommandException {
if (getServer().getOnlinePlayers().length == 0) {
if (BukkitUtil.getOnlinePlayers().isEmpty()) {
throw new CommandException("No players matched query.");
}
if (filter.equals("*")) {
return checkPlayerMatch(Arrays.asList(getServer().getOnlinePlayers()));
return checkPlayerMatch(Lists.newArrayList(BukkitUtil.getOnlinePlayers()));
}
// Handle special hash tag groups
@@ -498,7 +619,7 @@ public class WorldGuardPlugin extends JavaPlugin {
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (Player player : getServer().getOnlinePlayers()) {
for (Player player : BukkitUtil.getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
}
@@ -514,7 +635,7 @@ public class WorldGuardPlugin extends JavaPlugin {
org.bukkit.util.Vector sourceVector
= sourcePlayer.getLocation().toVector();
for (Player player : getServer().getOnlinePlayers()) {
for (Player player : BukkitUtil.getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)
&& player.getLocation().toVector().distanceSquared(
sourceVector) < 900) {
@@ -546,7 +667,7 @@ public class WorldGuardPlugin extends JavaPlugin {
public Player matchSinglePlayer(CommandSender sender, String filter)
throws CommandException {
// This will throw an exception if there are no matches
Iterator<Player> players = matchPlayers(sender, filter).iterator();
Iterator<? extends Player> players = matchPlayers(sender, filter).iterator();
Player match = players.next();
@@ -692,6 +813,47 @@ public class WorldGuardPlugin extends JavaPlugin {
return new BukkitPlayer(this, player);
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player The player to wrap
* @param silenced True to silence messages
* @return The wrapped player
*/
public LocalPlayer wrapPlayer(Player player, boolean silenced) {
return new BukkitPlayer(this, player, silenced);
}
/**
* Wrap a player as a LocalPlayer.
*
* <p>This implementation is incomplete -- permissions cannot be checked.</p>
*
* @param player The player to wrap
* @return The wrapped player
*/
public LocalPlayer wrapOfflinePlayer(OfflinePlayer player) {
return new BukkitOfflinePlayer(player);
}
/**
* Return a protection query helper object that can be used by another
* plugin to test whether WorldGuard permits an action at a particular
* place.
*
* @return an instance
*/
public ProtectionQuery createProtectionQuery() {
return new ProtectionQuery();
}
/**
* Configure WorldGuard's loggers.
*/
private void configureLogger() {
RecordMessagePrefixer.register(Logger.getLogger("com.sk89q.worldguard"), "[WorldGuard] ");
}
/**
* Create a default configuration file from the .jar.
*
@@ -719,7 +881,7 @@ public class WorldGuardPlugin extends JavaPlugin {
if (copy == null) throw new FileNotFoundException();
input = file.getInputStream(copy);
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
log.severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
@@ -733,7 +895,7 @@ public class WorldGuardPlugin extends JavaPlugin {
output.write(buf, 0, length);
}
getLogger().info("Default configuration file written: "
log.info("Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
@@ -765,22 +927,13 @@ public class WorldGuardPlugin extends JavaPlugin {
public void broadcastNotification(String msg) {
getServer().broadcast(msg, "worldguard.notify");
Set<Permissible> subs = getServer().getPluginManager().getPermissionSubscriptions("worldguard.notify");
for (Player player : getServer().getOnlinePlayers()) {
for (Player player : BukkitUtil.getOnlinePlayers()) {
if (!(subs.contains(player) && player.hasPermission("worldguard.notify")) &&
hasPermission(player, "worldguard.notify")) { // Make sure the player wasn't already broadcasted to.
player.sendMessage(msg);
}
}
getLogger().info(msg);
}
/**
* Forgets a player.
*
* @param player The player to remove state information for
*/
public void forgetPlayer(Player player) {
flagStateManager.forget(player);
log.info(msg);
}
/**
@@ -823,6 +976,10 @@ public class WorldGuardPlugin extends JavaPlugin {
return getGlobalRegionManager().get(world);
}
public PlayerMoveListener getPlayerMoveListener() {
return playerMoveListener;
}
/**
* Replace macros in the text.
*
@@ -839,11 +996,11 @@ public class WorldGuardPlugin extends JavaPlugin {
* @return The message with macros replaced
*/
public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
Collection<? extends Player> online = BukkitUtil.getOnlinePlayers();
message = message.replace("%name%", toName(sender));
message = message.replace("%id%", toUniqueName(sender));
message = message.replace("%online%", String.valueOf(online.length));
message = message.replace("%online%", String.valueOf(online.size()));
if (sender instanceof Player) {
Player player = (Player) sender;
@@ -855,4 +1012,5 @@ public class WorldGuardPlugin extends JavaPlugin {
return message;
}
}
@@ -1,178 +0,0 @@
// $Id$
/*
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
* All rights reserved.
*/
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;
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
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);
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();
}
}
}
}
@@ -0,0 +1,283 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit.cause;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.bukkit.internal.WGMetadata;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.metadata.Metadatable;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An instance of this object describes the actors that played a role in
* causing an event, with the ability to describe a situation where one actor
* controls several other actors to create the event.
*
* <p>For example, if a player fires an arrow that hits an item frame, the player
* is the initiator, while the arrow is merely controlled by the player to
* hit the item frame.</p>
*/
public final class Cause {
private static final String CAUSE_KEY = "worldguard.cause";
private static final Cause UNKNOWN = new Cause(Collections.emptyList(), false);
private final List<Object> causes;
private final boolean indirect;
/**
* Create a new instance.
*
* @param causes a list of causes
* @param indirect whether the cause is indirect
*/
private Cause(List<Object> causes, boolean indirect) {
checkNotNull(causes);
this.causes = causes;
this.indirect = indirect;
}
/**
* Test whether the traced cause is indirect.
*
* <p>If the cause is indirect, then the root cause may not be notified,
* for example.</p>
*
* @return true if the cause is indirect
*/
public boolean isIndirect() {
return indirect;
}
/**
* Return whether a cause is known. This method will return true if
* the list of causes is empty or the list of causes only contains
* objects that really are not root causes (i.e primed TNT).
*
* @return true if known
*/
public boolean isKnown() {
if (causes.isEmpty()) {
return false;
}
boolean found = false;
for (Object object : causes) {
if (!(object instanceof TNTPrimed) && !(object instanceof Vehicle)) {
found = true;
break;
}
}
return found;
}
@Nullable
public Object getRootCause() {
if (!causes.isEmpty()) {
return causes.get(0);
}
return null;
}
@Nullable
public Player getFirstPlayer() {
for (Object object : causes) {
if (object instanceof Player) {
return (Player) object;
}
}
return null;
}
@Nullable
public Entity getFirstEntity() {
for (Object object : causes) {
if (object instanceof Entity) {
return (Entity) object;
}
}
return null;
}
@Nullable
public Entity getFirstNonPlayerEntity() {
for (Object object : causes) {
if (object instanceof Entity && !(object instanceof Player)) {
return (Entity) object;
}
}
return null;
}
@Nullable
public Block getFirstBlock() {
for (Object object : causes) {
if (object instanceof Block) {
return (Block) object;
}
}
return null;
}
/**
* Find the first type matching one in the given array.
*
* @param types an array of types
* @return a found type or null
*/
@Nullable
public EntityType find(EntityType... types) {
for (Object object : causes) {
if (object instanceof Entity) {
for (EntityType type : types) {
if (((Entity) object).getType() == type) {
return type;
}
}
}
}
return null;
}
@Override
public String toString() {
return Joiner.on(" | ").join(causes);
}
/**
* Create a new instance with the given objects as the cause,
* where the first-most object is the initial initiator and those
* following it are controlled by the previous entry.
*
* @param cause an array of causing objects
* @return a cause
*/
public static Cause create(@Nullable Object... cause) {
if (cause != null) {
Builder builder = new Builder(cause.length);
builder.addAll(cause);
return builder.build();
} else {
return UNKNOWN;
}
}
/**
* Create a new instance that indicates that the cause is not known.
*
* @return a cause
*/
public static Cause unknown() {
return UNKNOWN;
}
/**
* Add a parent cause to a {@code Metadatable} object.
*
* <p>Note that {@code target} cannot be an instance of
* {@link Block} because {@link #create(Object...)} will not bother
* checking for such data on blocks (because it is relatively costly
* to do so).</p>
*
* @param target the target
* @param parent the parent cause
* @throws IllegalArgumentException thrown if {@code target} is an instance of {@link Block}
*/
public static void trackParentCause(Metadatable target, Object parent) {
if (target instanceof Block) {
throw new IllegalArgumentException("Can't track causes on Blocks because Cause doesn't check block metadata");
}
WGMetadata.put(target, CAUSE_KEY, parent);
}
/**
* Builds causes.
*/
private static final class Builder {
private final List<Object> causes;
private final Set<Object> seen = Sets.newHashSet();
private boolean indirect;
private Builder(int expectedSize) {
this.causes = new ArrayList<Object>(expectedSize);
}
private void addAll(@Nullable Object... element) {
if (element != null) {
for (Object o : element) {
if (o == null || seen.contains(o)) {
continue;
}
seen.add(o);
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
addAll(((Projectile) o).getShooter());
} else if (o instanceof Vehicle) {
addAll(((Vehicle) o).getPassenger());
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
indirect = true;
addAll(((Creature) o).getTarget());
} else if (o instanceof Tameable) {
indirect = true;
addAll(((Tameable) o).getOwner());
}
// Add manually tracked parent causes
Object source = o;
int index = causes.size();
while (source instanceof Metadatable && !(source instanceof Block)) {
source = WGMetadata.getIfPresent((Metadatable) source, CAUSE_KEY, Object.class);
if (source != null) {
causes.add(index, source);
seen.add(source);
}
}
causes.add(o);
}
}
}
public Cause build() {
return new Cause(causes, indirect);
}
}
}
@@ -0,0 +1,135 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit.commands;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.task.FutureForwardingTask;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
public class AsyncCommandHelper {
private final ListenableFuture<?> future;
private final WorldGuardPlugin plugin;
private final CommandSender sender;
@Nullable
private Object[] formatArgs;
private AsyncCommandHelper(ListenableFuture<?> future, WorldGuardPlugin plugin, CommandSender sender) {
checkNotNull(future);
checkNotNull(plugin);
checkNotNull(sender);
this.future = future;
this.plugin = plugin;
this.sender = sender;
}
public AsyncCommandHelper formatUsing(Object... args) {
this.formatArgs = args;
return this;
}
private String format(String message) {
if (formatArgs != null) {
return String.format(message, formatArgs);
} else {
return message;
}
}
public AsyncCommandHelper registerWithSupervisor(String description) {
plugin.getSupervisor().monitor(
FutureForwardingTask.create(
future, format(description), sender));
return this;
}
public AsyncCommandHelper sendMessageAfterDelay(String message) {
FutureProgressListener.addProgressListener(future, sender, format(message));
return this;
}
public AsyncCommandHelper thenRespondWith(String success, String failure) {
// Send a response message
Futures.addCallback(
future,
new MessageFutureCallback.Builder(plugin, sender)
.onSuccess(format(success))
.onFailure(format(failure))
.build());
return this;
}
public AsyncCommandHelper thenTellErrorsOnly(String failure) {
// Send a response message
Futures.addCallback(
future,
new MessageFutureCallback.Builder(plugin, sender)
.onFailure(format(failure))
.build());
return this;
}
public AsyncCommandHelper forRegionDataLoad(World world, boolean silent) {
checkNotNull(world);
formatUsing(world.getName());
registerWithSupervisor("Loading region data for '%s'");
if (silent) {
thenTellErrorsOnly("Failed to load regions '%s'");
} else {
sendMessageAfterDelay("(Please wait... loading the region data for '%s')");
thenRespondWith(
"Loaded region data for '%s'",
"Failed to load regions '%s'");
}
return this;
}
public AsyncCommandHelper forRegionDataSave(World world, boolean silent) {
checkNotNull(world);
formatUsing(world.getName());
registerWithSupervisor("Saving region data for '%s'");
if (silent) {
thenTellErrorsOnly("Failed to save regions '%s'");
} else {
sendMessageAfterDelay("(Please wait... saving the region data for '%s')");
thenRespondWith(
"Saved region data for '%s'",
"Failed to load regions '%s'");
}
return this;
}
public static AsyncCommandHelper wrap(ListenableFuture<?> future, WorldGuardPlugin plugin, CommandSender sender) {
return new AsyncCommandHelper(future, plugin, sender);
}
}
@@ -0,0 +1,196 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit.commands;
import com.google.common.base.Function;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.paste.EngineHubPaste;
import org.bukkit.ChatColor;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Command-related utility methods.
*/
public final class CommandUtils {
private static final Logger log = Logger.getLogger(CommandUtils.class.getCanonicalName());
private CommandUtils() {
}
/**
* Replace color macros in a string.
*
* @param str the string
* @return the new string
*/
public static String replaceColorMacros(String str) {
// TODO: Make this more efficient
str = str.replace("`r", ChatColor.RED.toString());
str = str.replace("`R", ChatColor.DARK_RED.toString());
str = str.replace("`y", ChatColor.YELLOW.toString());
str = str.replace("`Y", ChatColor.GOLD.toString());
str = str.replace("`g", ChatColor.GREEN.toString());
str = str.replace("`G", ChatColor.DARK_GREEN.toString());
str = str.replace("`c", ChatColor.AQUA.toString());
str = str.replace("`C", ChatColor.DARK_AQUA.toString());
str = str.replace("`b", ChatColor.BLUE.toString());
str = str.replace("`B", ChatColor.DARK_BLUE.toString());
str = str.replace("`p", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("`P", ChatColor.DARK_PURPLE.toString());
str = str.replace("`0", ChatColor.BLACK.toString());
str = str.replace("`1", ChatColor.DARK_GRAY.toString());
str = str.replace("`2", ChatColor.GRAY.toString());
str = str.replace("`w", ChatColor.WHITE.toString());
str = str.replace("`k", ChatColor.MAGIC.toString());
str = str.replace("`l", ChatColor.BOLD.toString());
str = str.replace("`m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("`n", ChatColor.UNDERLINE.toString());
str = str.replace("`o", ChatColor.ITALIC.toString());
str = str.replace("`x", ChatColor.RESET.toString());
// MC classic
str = str.replace("&c", ChatColor.RED.toString());
str = str.replace("&4", ChatColor.DARK_RED.toString());
str = str.replace("&e", ChatColor.YELLOW.toString());
str = str.replace("&6", ChatColor.GOLD.toString());
str = str.replace("&a", ChatColor.GREEN.toString());
str = str.replace("&2", ChatColor.DARK_GREEN.toString());
str = str.replace("&b", ChatColor.AQUA.toString());
str = str.replace("&3", ChatColor.DARK_AQUA.toString());
str = str.replace("&9", ChatColor.BLUE.toString());
str = str.replace("&1", ChatColor.DARK_BLUE.toString());
str = str.replace("&d", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("&5", ChatColor.DARK_PURPLE.toString());
str = str.replace("&0", ChatColor.BLACK.toString());
str = str.replace("&8", ChatColor.DARK_GRAY.toString());
str = str.replace("&7", ChatColor.GRAY.toString());
str = str.replace("&f", ChatColor.WHITE.toString());
str = str.replace("&k", ChatColor.MAGIC.toString());
str = str.replace("&l", ChatColor.BOLD.toString());
str = str.replace("&m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("&n", ChatColor.UNDERLINE.toString());
str = str.replace("&o", ChatColor.ITALIC.toString());
str = str.replace("&x", ChatColor.RESET.toString());
str = str.replace("&r", ChatColor.RESET.toString());
return str;
}
/**
* Get the name of the given owner object.
*
* @param owner the owner object
* @return a name
*/
public static String getOwnerName(@Nullable Object owner) {
if (owner == null) {
return "?";
} else if (owner instanceof Player) {
return ((Player) owner).getName();
} else if (owner instanceof ConsoleCommandSender) {
return "*CONSOLE*";
} else if (owner instanceof BlockCommandSender) {
return ((BlockCommandSender) owner).getBlock().getLocation().toString();
} else {
return "?";
}
}
/**
* Return a function that accepts a string to send a message to the
* given sender.
*
* @param sender the sender
* @return a function
*/
public static Function<String, ?> messageFunction(final CommandSender sender) {
return new Function<String, Object>() {
@Override
public Object apply(@Nullable String s) {
sender.sendMessage(s);
return null;
}
};
}
/**
* Submit data to a pastebin service and inform the sender of
* success or failure.
*
* @param plugin The plugin
* @param sender The sender
* @param content The content
* @param successMessage The message, formatted with {@link String#format(String, Object...)} on success
*/
public static void pastebin(WorldGuardPlugin plugin, final CommandSender sender, String content, final String successMessage) {
ListenableFuture<URL> future = new EngineHubPaste().paste(content);
AsyncCommandHelper.wrap(future, plugin, sender)
.registerWithSupervisor("Submitting content to a pastebin service...")
.sendMessageAfterDelay("(Please wait... sending output to pastebin...)");
Futures.addCallback(future, new FutureCallback<URL>() {
@Override
public void onSuccess(URL url) {
sender.sendMessage(ChatColor.YELLOW + String.format(successMessage, url));
}
@Override
public void onFailure(Throwable throwable) {
log.log(Level.WARNING, "Failed to submit pastebin", throwable);
sender.sendMessage(ChatColor.RED + "Failed to submit to a pastebin. Please see console for the error.");
}
});
}
}
@@ -0,0 +1,220 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) 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 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 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.bukkit.commands;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.debug.*;
import com.sk89q.worldguard.util.report.CancelReport;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.util.BlockIterator;
import java.util.logging.Logger;
public class DebuggingCommands {
private static final Logger log = Logger.getLogger(DebuggingCommands.class.getCanonicalName());
private static final int MAX_TRACE_DISTANCE = 20;
private final WorldGuardPlugin plugin;
/**
* Create a new instance.
*
* @param plugin The plugin instance
*/
public DebuggingCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"testbreak"}, usage = "[player]", desc = "Simulate a block break", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireBreakEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK BREAK at " + ChatColor.DARK_AQUA + block);
LoggingBlockBreakEvent event = new LoggingBlockBreakEvent(block, target);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testplace"}, usage = "[player]", desc = "Simulate a block place", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void firePlaceEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK PLACE at " + ChatColor.DARK_AQUA + block);
LoggingBlockPlaceEvent event = new LoggingBlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), target.getItemInHand(), target, true);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testinteract"}, usage = "[player]", desc = "Simulate a block interact", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireInteractEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK INTERACT at " + ChatColor.DARK_AQUA + block);
LoggingPlayerInteractEvent event = new LoggingPlayerInteractEvent(target, Action.RIGHT_CLICK_BLOCK, target.getItemInHand(), block, BlockFace.SOUTH);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testdamage"}, usage = "[player]", desc = "Simulate an entity damage", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireDamageEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Entity entity = traceEntity(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing ENTITY DAMAGE on " + ChatColor.DARK_AQUA + entity);
LoggingEntityDamageByEntityEvent event = new LoggingEntityDamageByEntityEvent(target, entity, DamageCause.ENTITY_ATTACK, 1);
testEvent(sender, target, event, args.hasFlag('s'));
}
/**
* Simulate an event and print its report.
*
* @param receiver The receiver of the messages
* @param target The target
* @param event The event
* @param stacktraceMode Whether stack traces should be generated and posted
* @param <T> The type of event
*/
private <T extends Event & CancelLogging> void testEvent(CommandSender receiver, Player target, T event, boolean stacktraceMode) throws CommandPermissionsException {
boolean isConsole = receiver instanceof ConsoleCommandSender;
if (!receiver.equals(target)) {
if (!isConsole) {
log.info(receiver.getName() + " is simulating an event on " + target.getName());
}
target.sendMessage(
ChatColor.RED + "(Please ignore any messages that may immediately follow.)");
}
Bukkit.getPluginManager().callEvent(event);
int start = new Exception().getStackTrace().length;
CancelReport report = new CancelReport(event, event.getCancels(), start);
report.setDetectingPlugin(!stacktraceMode);
String result = report.toString();
if (stacktraceMode) {
receiver.sendMessage(ChatColor.GRAY + "The report was printed to console.");
log.info("Event report for " + receiver.getName() + ":\n\n" + result);
plugin.checkPermission(receiver, "worldguard.debug.pastebin");
CommandUtils.pastebin(plugin, receiver, result, "Event debugging report: %s.txt");
} else {
receiver.sendMessage(result.replaceAll("(?m)^", ChatColor.AQUA.toString()));
if (result.length() >= 500 && !isConsole) {
receiver.sendMessage(ChatColor.GRAY + "The report was also printed to console.");
log.info("Event report for " + receiver.getName() + ":\n\n" + result);
}
}
}
/**
* Get the source of the test.
*
* @param sender The message sender
* @param target The provided target
* @param fromTarget Whether the source should be the target
* @return The source
* @throws CommandException Thrown if a condition is not met
*/
private Player getSource(CommandSender sender, Player target, boolean fromTarget) throws CommandException {
if (fromTarget) {
return target;
} else {
if (sender instanceof Player) {
return (Player) sender;
} else {
throw new CommandException(
"If this command is not to be used in-game, use -t to run the test from the viewpoint of the given player rather than yourself.");
}
}
}
/**
* Find the first non-air block in a ray trace.
*
* @param sender The sender
* @param target The target
* @param fromTarget Whether the trace should originate from the target
* @return The block found
* @throws CommandException Throw on an incorrect parameter
*/
private Block traceBlock(CommandSender sender, Player target, boolean fromTarget) throws CommandException {
Player source = getSource(sender, target, fromTarget);
BlockIterator it = new BlockIterator(source);
int i = 0;
while (it.hasNext() && i < MAX_TRACE_DISTANCE) {
Block block = it.next();
if (block.getType() != Material.AIR) {
return block;
}
i++;
}
throw new CommandException("Not currently looking at a block that is close enough.");
}
/**
* Find the first nearby entity in a ray trace.
*
* @param sender The sender
* @param target The target
* @param fromTarget Whether the trace should originate from the target
* @return The entity found
* @throws CommandException Throw on an incorrect parameter
*/
private Entity traceEntity(CommandSender sender, Player target, boolean fromTarget) throws CommandException {
Player source = getSource(sender, target, fromTarget);
BlockIterator it = new BlockIterator(source);
int i = 0;
while (it.hasNext() && i < MAX_TRACE_DISTANCE) {
Block block = it.next();
// A very in-accurate and slow search
Entity[] entities = block.getChunk().getEntities();
for (Entity entity : entities) {
if (!entity.equals(target) && entity.getLocation().distanceSquared(block.getLocation()) < 10) {
return entity;
}
}
i++;
}
throw new CommandException("Not currently looking at an entity that is close enough.");
}
}
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff. Show more