Compare commits

..
433 Commits
Author SHA1 Message Date
wizjany 3827266eb3 Release 7.0.5. 2021-06-07 22:52:20 -04:00
wizjany c3dbfdd699 Changelog for 7.0.5. 2021-06-07 22:49:23 -04:00
wizjany f19ebab0e1 Handle spigot's entity mount event (#1755)
* Add handler for spigot's EntityMountEvent.

Closes #1677.

* checkstyle.
2021-06-06 19:34:26 -04:00
stonar96andwizjany f8f95a44f0 Fix Iron Doors (#1781)
Co-authored-by: wizjany <wizjany@gmail.com>
2021-06-06 19:30:40 -04:00
stonar96 0a74d02fc9 Add nonplayer-protection-domains flag (#1763) 2021-06-06 19:28:00 -04:00
stonar96 46a662e1a7 Fix Dispenser Shulker Box bug and cleanup (#1776) 2021-06-06 19:27:48 -04:00
stonar96 149d1f84e8 Remove unused RegionGroup.MEMBERS from the teleport flag (#1769) 2021-05-23 12:37:06 -04:00
stonar96andwizjany c4e76af5f4 Fix Cause#isKnown() (#1768)
* Fix Cause#isKnown()

* Grammar

Co-authored-by: wizjany <wizjany@gmail.com>
2021-05-15 15:03:55 -04:00
stonar96 c1c26360e3 Remove unnecessary FlagValueCalculator#getPriority(ProtectedRegion) calls 2021-05-15 15:03:02 -04:00
stonar96 65c894cfe9 Fix doc comment of FlagValueCalculator#getMembership(RegionAssociable) 2021-05-15 15:02:08 -04:00
TheBusyBiscuitandwizjany 7dcec2b3b4 Small performance improvement for PlayerDomain#contains() (#1765)
* Improve performance by putting UUID checks first.

* Added wizjany's suggestion

Co-authored-by: wizjany <wizjany@gmail.com>
2021-05-15 15:01:15 -04:00
stonar96 09ce3b6373 Update Java version in CONTRIBUTING.md (#1764) 2021-05-10 11:22:38 +10:00
wizjany de22a5cd25 Deprecate and immediately void setMin/MaxPoint in ProtectedCuboidRegion.
Not sure why these were here to begin with, Poly doesn't have them either
and mutating regions after creation leads to undefined behavior.
2021-04-12 14:18:11 -04:00
JOO200 d2c2bfbab2 Deprecate flags (replaced by RegistryFlag), added some null checks (#1747) 2021-04-10 13:58:39 -04:00
wizjany 528ba32a93 Also change paperlib to shade.
This change has been sitting here for a while uncommitted and unpushed.
2021-03-06 15:36:25 -05:00
JOO200 f37fbb1ae8 Fix Falling blocks may change snow layers to that block 2021-03-06 15:31:06 -05:00
wizjany f1f8b625a8 Gradle cleanup/unfuckery.
Fixes #1729
2021-02-10 15:21:03 -05:00
wizjany e933050436 Change relocated/shaded artifacts to compileOnly. 2021-02-10 13:33:48 -05:00
wizjany 59d4c7b96d Fix nullability annotation. 2021-02-10 00:02:28 -05:00
Shane Freeder 0c7f4bb8f7 Fix TimedHandler not calling delegated handler (#1727)
The original commit was calling super, which means that the actual
registered handlers were not called, also, added getInvincibility
which was originally missing
2021-02-09 23:48:03 -05:00
wizjany 3c9b21d01f Add timings to third-party session handlers (#1717)
* Add Timings for third-party session handlers.

These often cause WorldGuard to get blamed by timings.

* Add config option to turn off extra timings.

* Move relocation to the right build file.

* Move config to a map for potential future expansion.

* Calculate timing immediately per-factory.

Instead of on each handler creation.
2021-02-06 11:10:04 -05:00
wizjany aeea455560 Ignore BlockFertilizeEvent with empty list.
Plugins can clear this list without fully cancelling the event.
Fixes #1723
2021-02-06 10:58:29 -05:00
wizjany 129d27351a Don't send empty messages from chorus-fruit/enderpearl teleports. 2021-02-02 19:44:38 -05:00
wizjany 310ce9a662 Make UUIDFlag ctors public.
smh.
2021-01-26 16:18:07 -05:00
kikelkik e04c654cde Added arguments to /rg toggle-bypass: on, off 2021-01-23 22:01:28 -05:00
JOO200 b1674e5cb7 Added test cases for FlagValueCalculator and MapFlags 2021-01-23 21:43:44 -05:00
JOO200 89c6a33b90 Improved queryMapValue to return defaultValue instead of null 2021-01-23 21:43:44 -05:00
JOO200 88c91ce3fc Add fallback value to queryMapValue, use Flag$chooseValue 2021-01-23 21:43:44 -05:00
JOO200 b70f5a73ce Added methods to query values from map flags 2021-01-23 21:43:44 -05:00
JOO200 b6fc9ddd93 Add UUIDFlag 2021-01-23 21:33:29 -05:00
wizjany cbb3212082 Don't throw error when swapping armor slots into the offhand.
Lots of conflicting info here, but the offhand slot is in fact part of
the quickbar/hotbar (yay bukkit naming) but does *not* use a hotbar "button",
since it has its own hotkey (i.e., F by default instead of 0-8).
The result is a hotbar_swap *action* with a swap_offhand *clicktype*.

Fixes #1698.
2021-01-09 18:16:40 -05:00
Intelli 04d5a3b437 Fixed NoClassDefFoundError if WorldEdit failed to initialize 2021-01-03 17:46:29 -05:00
Matthew Millerandwizjany 282425f3cf Move the Mob Blocker feature from CraftBook to WorldGuard (#1695)
* Move the Mob Blocker feature from CraftBook to WorldGuard

* Formatting.

Co-authored-by: wizjany <wizjany@gmail.com>
2020-12-31 10:51:49 +10:00
wizjany 15a08097ae Small readme tweaks.
Fix dead/outdated links, clarify deps.
2020-12-09 11:28:13 -05:00
wizjany 035a645de0 Deal with bamboo as growth from spread event listener.
Closes #1673, #1674.
2020-11-27 09:10:28 -05:00
wizjany 59c146f59a Don't allow setting unknown flags in FlagHelperBox. 2020-11-17 18:53:22 -05:00
wizjany d313f2caad Add nether warts to crop list.
Closes #1669.
2020-11-17 18:50:35 -05:00
wizjany 8350267b10 Don't marshal SetFlag in FlagHelperBox. 2020-11-17 18:50:35 -05:00
JOO200 e98196af40 Catch Throwables instead of Exceptions while (un)marshalling flags 2020-11-17 17:17:26 -05:00
wizjany 3879772103 Move /rg bypass perm check inside the command.
Using @CommandPermissions would cause the root command to be excluded
from the client. This is a temp workaround until piston/proper perms
are somehow implemented.
2020-11-17 16:36:36 -05:00
wizjany 48233c3327 Make resource processing update with project version.
Should prevent old version strings from finding their way into plugin.yml
2020-11-03 14:42:39 -05:00
wizjany 664ab18f00 Fix sponge-simulation clearing NBT of waterlogged blocks.
Fixes #1659.
Didn't realize people still used this feature.
2020-10-23 23:41:56 -04:00
Matthew Miller 07bf1871ab Add an SVG logo 2020-10-23 21:44:09 +10:00
JOO200 5921be432c Change anvil usage to build permissions and add use-anvil flag (#1644) 2020-10-17 17:51:39 -04:00
wizjany 60b16fc4c7 Add sweet berry bush to crop list. 2020-09-26 22:16:19 -04:00
wizjany 746b630d01 Note the new region converter class for devs. 2020-09-26 16:05:27 -04:00
wizjany 0b362088f4 Bump to snapshot version. 2020-09-26 12:57:03 -04:00
wizjany 014277fb2f Release 7.0.4. 2020-09-26 12:55:18 -04:00
wizjany f7ff984c34 Update changelog for release. 2020-09-26 12:46:20 -04:00
Pisich d4b2060766 Removed extra ";" 2020-09-26 12:06:06 -04:00
JOO200 0e73b50d6f Moved default bypass options to global configuration section 2020-09-16 13:34:56 -04:00
JOO200 136ec31f38 Add configurable announcement for current bypass status 2020-09-16 13:34:56 -04:00
JOO200andwizjany ad000ab051 Rename config option for default bypass option
Co-authored-by: wizjany <wizjany@gmail.com>
2020-09-16 13:34:56 -04:00
JOO200 af67f1dd6a Add config option to deny region bypass by default 2020-09-16 13:34:56 -04:00
wizjany 8dee2ad3b8 Don't check ride for unsaddled striders. 2020-09-11 20:44:47 -04:00
wizjany c860fce299 Document ProtectedRegion's comparable behavior.
ProtectedRegion's compareTo is inconsistent with equals when comparing regions across managers.
2020-09-09 15:16:15 -04:00
wizjany 0cb84927a3 Don't fire xp spawn events for fishing where xp was already 0.
Dedicated to @mikroskeem who let me forget about this.
2020-08-30 13:25:36 -04:00
wizjany 2ed60eba02 Add deprecation warnings for names in Domains. 2020-08-21 15:51:33 -04:00
wizjany 91a1494634 Add piglin brutes. 2020-08-16 18:03:05 -04:00
Matthew Miller 5b8c3e7f70 Use a lower level exception in BukkitWorldConfiguration to get a printout when more severe YAML issues occur 2020-08-16 16:55:19 +10:00
Matthew Miller c1ff4fc3d3 s/WorlGuard/WorldGuard 2020-08-16 14:44:57 +10:00
JOO200andwizjany 691325c8f0 Update worldguard-bukkit/src/main/java/com/sk89q/worldguard/bukkit/BukkitWorldConfiguration.java
fixed typo

Co-authored-by: wizjany <wizjany@gmail.com>
2020-08-14 14:01:58 -04:00
JOO200 3da19a7ff0 Added world option to block turtle egg trampling 2020-08-14 14:01:58 -04:00
wizjany f677af566f Don't try dropping items from falling blocks that won't drop one.
To quote myself from the adjacent commit almost exactly one year ago,
"some plugins do weird things with falling blocks."

Fixes #1624.
2020-08-07 13:59:22 -04:00
wizjany 58eaf31879 Merge pull request #1618 from JOO200/piston
Implement new alternative association mode to limit piston movement
2020-08-03 10:53:31 -04:00
wizjany 6708b21016 Abstract RegionOverlapAssociation, deprecate/fix packaging. 2020-08-03 10:46:40 -04:00
wizjany ed4287ace7 Cleanup use-max-prio algorithm, add tests. 2020-08-03 10:21:35 -04:00
wizjany 03f05d3a4e Simplify and remove duplicate code. 2020-08-03 07:21:56 -04:00
JOO200 c8bde17994 Fixed "null" output for invalid worldedit selections 2020-08-01 16:55:37 +02:00
JOO200 449145ba1f Renamed option to use-max-priority-association, Code cleanup 2020-08-01 13:54:27 +02:00
JOO200 85c5f53d29 only detect max priority once 2020-07-30 20:37:49 +02:00
JOO200 5162ce3dbd Implement new alternative association mode to limit piston movement 2020-07-30 20:24:18 +02:00
wizjany efe1e48bd4 Merge pull request #1615 from JOO200/toRegionSelector
Add Helper to convert WorldGuard's ProtectedRegion to WorldEdit's Region and RegionSelector
2020-07-29 23:42:00 -04:00
wizjany 1710c07623 Check non-waterloggable waterlogged blocks for liquid flow.
Fixes #1616.
2020-07-29 23:39:04 -04:00
JOO200 6f9ed5d10f Private ctor to match checkstyle. 2020-07-27 17:55:11 +02:00
JOO200 f0ec54af49 Added missing license to WorldEditRegionConverter 2020-07-27 17:17:20 +02:00
JOO200 e9e1885f2e Moved toRegion and toRegionSelector in a helper class 2020-07-27 17:03:50 +02:00
wizjany f8e2d8d6b7 Redstone wire is toggled between dot and cross on interact now. 2020-07-19 16:47:30 -04:00
wizjany 2c0b592b19 Declare some recently hidden dependencies. 2020-07-17 01:11:12 -04:00
wizjany 46e230e625 Missed import. 2020-07-16 21:41:08 -04:00
wizjany fe24668c6a Re-add pom-switcheroo to expose spigot as a dep instead of paper.
Makes it easier for downstream projects that don't have paper-repo.
2020-07-15 19:23:44 -04:00
wizjany 23efd5fec2 Fireworks are now projectiles.
Only use paper-api for fallback.
2020-07-15 19:23:01 -04:00
JOO200 e54235a65e Removed unnecessary relevant flag as it's checked by the UseBlockEvent listener 2020-07-15 18:43:25 -04:00
JOO200 5ec3ed6092 Changed handling von PlayerTakeLecternBookEvent to match the chest-access flag 2020-07-15 18:43:25 -04:00
TheMolkaPL 1652c9bfc0 Allocate WorldPlayerTuple only when using cache 2020-07-03 20:26:56 -04:00
TheMolkaPL a97db0ede9 Add an option to disable bypass permission cache 2020-07-03 20:26:56 -04:00
wizjany 36e42eefd0 Update gradle wrapper, more buildscript fixes. 2020-07-03 17:06:31 -04:00
wizjany 5b8eef92b8 Build script cleanup/updates. 2020-07-02 19:09:09 -04:00
wizjany d73dc6d719 Cleanup issue template a bit. 2020-07-02 18:55:08 -04:00
wizjany 74d8a4f0e7 Typo. 2020-06-27 19:55:34 -04:00
JOO200 613406aab4 Add Weeping Vines and Twisting Vines to vine-growth flag 2020-06-27 18:19:11 -04:00
wizjany 66fd84ba2f Add GitHub Sponsors link. 2020-06-27 00:24:46 -04:00
wizjany 53abb6c4ad Back to snapshot. 2020-06-26 02:09:36 -04:00
wizjany 923369e28c Release 7.0.4-beta1. 2020-06-26 02:02:48 -04:00
wizjany bc551da903 Update buildscript and WE dep. 2020-06-26 01:21:30 -04:00
wizjany bffe5e76f2 Additional 1.16 material defs. 2020-06-26 00:52:29 -04:00
JOO200 8722322cd8 Added new flag respawn-anchors similar to block respawn anchor usage 2020-06-26 00:02:50 -04:00
JOO200 0fa92d4836 Removed unnecessary if branch 2020-06-26 00:02:49 -04:00
JOO200 e52875bd0b Removed duplicate pressure plates check 2020-06-26 00:02:49 -04:00
JOO200 dbad328d0d Update to Minecraft 1 16, PaperLib to 1 0 4 2020-06-26 00:02:49 -04:00
wizjany 5407315799 Release 7.0.3 for MC 1.14/1.15.
Last release before switching to 1.16.
2020-06-25 23:40:40 -04:00
wizjany b769469f5b Changelog for 7.0.3. 2020-06-25 23:11:51 -04:00
wizjany 3a9b1b1525 Add deprecation warnings to StringFlags. 2020-06-25 22:57:28 -04:00
wizjany ff5f933879 Typo. 2020-06-24 10:42:12 -04:00
wizjany 0492fafe30 Color 3rd party flags and unregistered flags in /rg info. 2020-06-21 17:25:38 -04:00
wizjany 36d95ad090 More inventory holder snapshot use. 2020-06-21 16:57:58 -04:00
wizjany c1ec708050 Use Inventory#getHolder(boolean useSnapshot) where available.
Dedicated to @phoenix616
2020-06-21 16:39:28 -04:00
wizjany f4a3e8a936 Allow setting passthrough on global via /rg flags.
Closes #1584.
2020-06-11 14:57:22 -04:00
wizjany 6c5380ba0b Prioritize tamed owners over entity targets.
Fixes #1587.
2020-06-08 13:14:04 -04:00
wizjany 868089b44f Actually read TargetMatchers from world configs.
Previously only read from global.
2020-06-01 15:52:16 -04:00
wizjany 9905d22ddf Add dyes as tools for interact handling. 2020-05-19 14:50:46 -04:00
UltraFaceguy 4eaa376e2c Providing a solution for tools being unable to interact with usable blocks 2020-05-12 20:56:41 -04:00
JOO200 37ae70f35d Add coral-fade flag and world configuration to disable coral fading
Closes #1532
2020-05-10 03:12:20 -04:00
wizjany 1a69250d9b Allow droppers to drop items without using them.
Fixes #1570.
2020-05-10 03:12:18 -04:00
wizjany b2d2d0815b Silence EntityChangeBlock for redstone ore.
We already silence this for Action.PHYSICAL PlayerInteractEvents.
Unfortunately Bukkit throws another event at us without the extra info
about interaction type, which gets fired if the interact flag is allow.
So silence that too.

Closes #1573.
2020-05-10 03:12:17 -04:00
wizjany 47cd96a3af Add tests to validate behavior of non-player causes in multiple regions. 2020-05-02 10:41:51 -04:00
wizjany 0a735e0146 Don't warn about small global regions.
Closes #1567.
2020-05-01 19:39:59 -04:00
stonar96 60590acfe3 Remove unnecessary checks and add comments 2020-04-29 15:15:07 -04:00
stonar96 6030bea13e Improve default teleport-message and remove null check 2020-04-29 15:15:07 -04:00
stonar96 20f89ea2ae Add teleport-message flag 2020-04-29 15:15:07 -04:00
wizjany 4c351fb0e3 Workaround for CraftBukkit's move event throttling. 2020-04-28 16:19:18 -04:00
wizjany 5e7829c3fe Allow FML2 in forge host keys.
Closes #1542.
2020-04-24 11:43:22 -04:00
wizjany 37e66dae7d Track BlockProjectileSource causes. 2020-04-24 10:06:16 -04:00
wizjany 662ae2bc84 Add issue templates. 2020-04-16 09:02:01 -04:00
wizjany fa60582afe Sand/gravel tick now, even if physics is cancelled. 2020-04-09 18:47:01 -04:00
wizjany 17c1647163 Move profile cache updating to join event.
Adding it to onEnable might back up the executor on /reloads.
2020-04-07 11:25:56 -04:00
wizjany 1fcda13469 Check waterlogged blocks for water-flow flag.
Also remove some terribly outdated obsidian generator protection.

Fixes #1546.
2020-03-29 20:16:50 -04:00
wizjany 570b7f7b77 Allow passthrough allow on global to override added members/owners. 2020-03-29 19:48:13 -04:00
wizjany aca0d843f6 Allow WorldEdit's //world override to affect region commands.
Priority is `-w` flag > //world override > player world > error.
Also makes regions selectable from console.
2020-03-23 21:32:25 -04:00
wizjany 1172ebd419 More spawn protection warnings.
Can't have enough of these apparently.
2020-03-23 16:40:12 -04:00
wizjany a09ccc5b45 Fire block breaks for piston extends, not just places. 2020-03-21 11:25:46 -04:00
wizjany e6bdf8abb5 Fix cauldron NPE.
Closes #1541.
2020-03-19 22:34:39 -04:00
wizjany df2ae6a666 Tweak some region info output, fix teleport location. 2020-03-19 13:34:20 -04:00
wizjany e4481f9337 Protect cauldron level change.
Closes #1262.
2020-03-12 15:26:22 -04:00
wizjany 2169aa218e Add option to always use default MC times for sending titles.
Alleviates issues with other plugins setting extremely short/long times.
2020-02-15 16:04:47 -05:00
wizjany 523e45188d Default nether-portal-protection to true.
Pre 1.14, this was false by default as one could repeatedly force portal
searches by entering a portal which would lead into a protected area.

Since 1.14, the event we have access too happens independently of the
portal search, so the player will get teleported regardless of whether
a portal is present or if the creation gets cancelled.
2020-02-15 13:31:38 -05:00
wizjany d95c6af1be Remove metadata when the entity is done.
Apparently Bukkit doesn't actually do this.
Fixes WORLDGUARD-4169.
2020-02-13 23:20:04 -05:00
wizjany 0d860bfca7 Change bypass cache to expireAfterWrite.
This hasn't caused issues for the past 5 years but I guess ¯\_(ツ)_/¯
2020-02-06 18:16:55 -05:00
wizjany 6f6125fe00 Treat farmland and turtle egg PIE as EntityChangeBlock.
Note that as in d37f015f this decouples the event from interact flag,
meaning that block-trampling must be explicitly set to allow to maintain
previous behavior. It also means that setting interact to allow won't
by default allow players to trample turtle eggs (but this wasn't the case
for farmland, since that was already handled by ECB - thanks Bukkit).

Fixes WORLDGUARD-4163.
2020-02-01 11:39:20 -05:00
wizjany 0332929531 Bump bStats to 1.7, adding plugin id. 2020-01-31 11:18:50 -05:00
Wyatt Childers 637665f52d Add a scripts folder to gitignore for dev scripts 2020-01-14 22:51:13 -05:00
wizjany db3838ccfe Add flag to prevent natural health regen and hunger drain. 2020-01-09 20:41:57 -05:00
wizjany 789405d116 Ignore session reset if player doesn't move a block.
So technically we do this block check in Session#testMoveTo, but the
/wg flushstates command can force a session re-initialization even if
the player hasn't moved a full block yet.
The amount of logic going on between the event call and the point where
we test that force boolean is rather lengthy though, so ignoring it for
the time being may be worth it.
TL;DR: Don't want WG in timings for PlayerMoveEvent needlessly.
2020-01-07 17:24:43 -05:00
wizjany d37f015f0c De-couple chest-access from interact. READ BELOW.
This is possibly a breaking change, in that WG will be overprotective
in regions which previously had interact set to allow but didn't change
the chest-access flag. If you previously had regions like this where you
would like to have non-members access chests, you will need to set the
chest-access flag to allow.

This change was made to alleviate some confusion that became more
evident recently with lecterns, since interacting with lecterns allowed
one to read a book, but the chest-access flag controlled taking the book.
This required setting interact to allow and chest-access to deny (at
least for nonmembers) to allow guests to read books but not take them.

This is a tentative change and may be reverted if it is too unpopular.
Thanks for testing dev builds :^)
2020-01-05 22:52:23 -05:00
wizjany 239eda3f96 Bump to snapshot. This will likely become 7.1 soon anyway. 2020-01-05 22:43:00 -05:00
wizjany 0715cbe216 Release 7.0.2. 2020-01-05 22:42:15 -05:00
wizjany 738b24bfc1 Changelog for 7.0.2.
Small one.
2020-01-05 22:35:05 -05:00
wizjany b835ee39d5 Check water/lava placement from dispensers on edge of region.
Fixes WORLDGUARD-4161.
2020-01-03 23:11:56 -05:00
Pieter12345 4a7552e6be Prevent pushing pistons across region borders
Pistons are classified as not pushable regardless of their state, causing WorldGuard to not protect against them moving. This commit fixes that.
2020-01-01 13:53:09 -05:00
Joo200 c6c0fc9d74 Fixed failed checkstyle gradle task 2020-01-01 13:53:01 -05:00
wizjany f43a4eaad8 Add spawn-protection overlap check when defining regions.
Update cached username on login.
Bump WorldEdit dep version.
2019-12-19 15:42:34 -05:00
JOO200 abfa5cb6a5 bee nests can be modified by right click (like beehives) 2019-12-16 14:08:04 -05:00
JOO200 05f7d68705 Use Paper-API 1.15 as Dependency 2019-12-16 14:08:04 -05:00
wizjany 9adac4f239 Initial 1.15 stuff.
Materials is not really cross-version compatible. Really could do with
some rewriting at some point.
2019-12-10 23:48:50 -05:00
wizjany c5355adb4b Back to snapshot. 2019-11-22 23:51:25 -05:00
wizjany fb37342b3c Release 7.0.1. 2019-11-22 23:43:05 -05:00
wizjany 1fd94a3655 Switch blacklist to drilldown since bstats doesn't support bar charts.
See https://github.com/Bastian/bStats/issues/67

Also update blacklist example txt with correct names.
2019-11-17 18:13:45 -05:00
wizjany c413cf4123 Remove pointless iterable. 2019-11-17 18:13:45 -05:00
wizjany 87162acf11 Switch blacklist stat to entry counts. 2019-11-17 18:13:45 -05:00
wizjany 2c14acc28c Add some custom charts to bStats.
Should give a good view of feature usage, especially some badly
supported features like SQL and chest protection.
2019-11-17 18:13:45 -05:00
wizjany 26477406f1 Fix pistons flag not applying to sticky pistons pulling. 2019-10-11 22:12:03 -04:00
wizjany 121b34ecb9 Add applicable regions section to /wg report. 2019-10-06 13:09:08 -04:00
wizjany 3ebaaf9c8b Add /rg toggle-bypass command to turn off region bypass temporarily.
Makes it easier to test things without op/de-op, switching ranks, etc
all the time.
2019-10-06 12:17:07 -04:00
wizjany 4c9812db04 Fix exit-deny-message using wrong region set on enderpearl/chorus-fruit. 2019-10-06 12:17:07 -04:00
wizjany e792dd6f98 Workaround colors on newlines of string flags issue in text lib.
Also fix newline lookbehind replacement, and only replace color macros
in string flags.
2019-10-06 12:17:07 -04:00
wizjany d410e1f84e Re-arrange messages in (re)define commands.
Only send messages after successful add.
2019-10-06 12:17:07 -04:00
wizjany d07f95952d Causes only track blocks, not locations. 2019-09-26 20:24:11 -04:00
wizjany cb9ab3a7b2 Check creeper-explosion flag for all entity damage, not just players. 2019-09-26 10:38:02 -04:00
wizjany 1c3cf02ebd BlockMultiPlace has an immutable state list.
Fixes WORLDGUARD-4143.
2019-09-22 15:16:57 -04:00
wizjany fc0f7acab5 Fix infinite loop in addowner checks.
Fixes WORLDGUARD-4138.
2019-09-22 14:28:38 -04:00
wizjany 20db92541b Make use of BlockFertilizeEvent, various BlockState lists.
Only mostly tested to work. BlockFertilize unfortunately doesn't let
us cancel the preceding stuff like StructureGrow and item use.

Also workaround Bukkit sending 2 events for trampling.
2019-09-18 15:43:36 -04:00
wizjany 5fca3b3c3d Track causes when players ignite creepers.
Fixes WORLDGUARD-4136.
2019-09-13 17:34:37 -04:00
wizjany c633a2d070 Cover some more plants as crop-growth.
Note that spigot doesn't throw events for bamboo yet, so this only
applies to sugar canes and cacti at the moment. Should work if spigot
implements BlockGrowEvent for cacti though.

Fixes WORLDGUARD-4137.
2019-09-13 17:20:51 -04:00
wizjany effbd62e68 Ignore hopper minecarts with the ignore hopper setting. 2019-09-13 16:43:27 -04:00
wizjany 056eaa6587 Teleport async on Paper. 2019-09-13 16:42:35 -04:00
wizjany cb2c0870ec List is not a valid cause. Each element is its own cause.
Fixes WORLDGUARD-4140.

Specifically, fixes not being able to break lilypads while in a boat,
even through the player would normally be able to.

Note that slowdown is client-side and getting stuck is due to Spigot
not updating the client when the break is cancelled, which are unrelated
to this issue (and not fixable by us).
2019-09-13 16:32:28 -04:00
wizjany 179c324c80 Apparently world names are allowed to have spaces. 2019-08-18 23:43:57 -04:00
wizjany 96d15d6dbf Only store existing per-player time/weather in handlers.
Fixes WORLDGUARD-4124.

This will fix various issues with logging in to regions with these flags
set and then moving out of them, or when moving between two adjacent
regions with the flags set and then moving out.
2019-08-18 12:00:50 -04:00
wizjany 120d2e223d Extract/half-fix addowner checks.
Max-region-count-for-player is super bork.

Fixes WORLDGUARD-4129.
2019-08-18 10:39:56 -04:00
wizjany 70ea6bad6e Some cleanup for flag command. 2019-08-18 10:38:07 -04:00
wizjany e59d61e1cf Extract NumberFlag for suggestions, make FlagHelper prettier in console. 2019-08-06 23:08:10 -04:00
wizjany bbed280f62 Update docs links to point to enginehub.
Also don't allow block-place/block-break setting from flag helper.
2019-08-06 21:50:05 -04:00
wizjany f165ae3d95 Back to snapshot. 2019-08-06 00:12:41 -04:00
wizjany 124898ec91 7.0.1 RC 2. 2019-08-06 00:12:26 -04:00
wizjany ba32d24363 Merge pull request #414 from EngineHub/feature/paper
Add some Paper-specific features
2019-08-05 23:49:04 -04:00
wizjany 0bba822295 Link ender crystal entity <-> material. 2019-08-03 18:10:54 -04:00
wizjany 7538af2686 TippedArrow again. 2019-08-02 16:34:26 -04:00
wizjany 48922118b1 Fix fireworks, protect by default (this is a behavioral change).
Add regions.use-paper-entity-origin setting, false by default because
it can have some weird implications.
2019-08-01 23:47:27 -04:00
wizjany 14fe2d0e79 Use Paper player profiles if available.
Also fall back to caching to memory if SQLite can't be linked.
This is a common issue with (bad) server hosts who mount /tmp as noexec,
which causes sqlite's native binaries to fail to link.
2019-08-01 20:24:34 -04:00
wizjany 11a1ac6742 User paper firework tracking. 2019-08-01 20:24:33 -04:00
wizjany c5bfdcb0e6 Use PaperLib for some performance enhancements. 2019-08-01 20:24:32 -04:00
wizjany 93dae282b2 Apparently some plugins do weird things with falling blocks. 2019-08-01 20:12:58 -04:00
wizjany 3468e3d47e Handful of small fixes.
* Fix material loading from config requiring minecraft: namespace.
* Fix disallowed-lightning blocks. Lightning entities are weird.
* Fix /wg reload overwriting config changes.
* General around thread usage/naming/shutdown. If anyone was actually
  making their own managers/indices you deserve to break.
2019-07-31 22:53:20 -04:00
wizjany b7ad0257b7 Remove legacy potion code. 2019-07-30 18:44:24 -04:00
wizjany 070f6e005f Merge pull request #415 from EngineHub/kotlin-dsl
Migrate gradle to kotlin dsl.
2019-07-30 16:56:46 -04:00
wizjany cc3f4d4d44 Relocate squirrelid in source, fix flyway shading. 2019-07-30 09:44:19 -04:00
wizjany 21e65be110 Fix poms, remove bukkit lib project since it's currently unused. 2019-07-29 23:41:38 -04:00
wizjany 61494fd76e Migrate gradle to kotlin dsl. 2019-07-29 23:25:13 -04:00
wizjany 556b638d04 Switch build badge to TC.
And remove dead wiki links.
2019-07-29 11:34:18 -04:00
wizjany 825b3a3f36 Save defaults to config file. 2019-07-27 22:40:03 -04:00
wizjany afe042ef4d Add option for resetting fall distance when void falling teleport is on.
reset-fall-on-void-teleport, defaults to false. (I can't remember if
old WG 6 behavior was to do this or not...?)
2019-07-27 21:57:49 -04:00
wizjany 4044e2b122 Ender crystal explosions can't be cause tracked. 2019-07-26 22:51:19 -04:00
wizjany aa4137822f Fix sleep flag. 2019-07-24 14:35:42 -04:00
wizjany f37acd3de6 Whitelist player->player interacts.
As noted before, any more specific events should still be blocked (such
as potion use).
2019-07-23 20:13:12 -04:00
wizjany b0e4cf148b ItemElytra extends ItemArmor... 2019-07-19 20:45:16 -04:00
wizjany 248ffd0ba8 Maybe fix travis. 2019-07-18 14:54:13 -04:00
wizjany 3272759f25 Check waterlogged blocks when emptying buckets.
Fixes WORLDGUARD-4119.
2019-07-17 07:45:31 -04:00
wizjany 456a16591b Handle UseEntity player->player events as PvP.
Fixes WORLDGUARD-4118.
Tell me if this breaks other intended behaviors somehow.
2019-07-16 18:48:57 -04:00
wizjany 79f6635b8a Make /wg profile text more clear.
This patch dedicated to @phoenix616.
2019-07-16 18:42:48 -04:00
wizjany 1f362bef59 Minecarts spawn in the clicked (rail) block. 2019-07-09 07:47:54 -04:00
wizjany 63209d1174 Null-check for last commit. 2019-07-07 01:22:04 -04:00
wizjany f546700189 Allow interact-whitelist for entities with matching item types. 2019-07-06 11:02:36 -04:00
wizjany 35e0db36d3 Workaround for sign dying issue.
Signs still get dyed even if you deny using dye.
2019-07-03 09:53:11 -04:00
wizjany ab7751e046 Unfix WORLDGUARD-3360.
There's a reason this wasn't done before. This is fundamentally broken.
2019-07-02 23:08:50 -04:00
wizjany a9cd23c6ef Don't replace in comments and strings when you refactor... 2019-07-02 17:39:21 -04:00
wizjany 8ca01b37a4 Add config to disable villagers getting zapped to witches.
"weather.disable-villager-witchification"
2019-06-30 19:58:10 -04:00
wizjany aa8997aeca Add TP button to /rg list where applicable. 2019-06-30 11:37:50 -04:00
wizjany b757fcc88b Send CUI changes when using /rg select. 2019-06-27 08:06:09 -04:00
wizjany 7593e1a01c Initial update to 1.14. 2019-06-25 22:12:18 -04:00
wizjany af3eb85962 Add on-equip blacklist event.
Note that due to deficiencies in the Bukkit API, the event will attempt
to be overprotective and cancel some events that may not actually result
in the player equipping an item. Maintainable PRs welcome. (i.e. would
rather not have to have a list of slot numbers for various inventories
and match them to items :upside_down:)
2019-06-25 22:11:33 -04:00
wizjany aabb0b2345 Treat damaged anvils like regular anvils. 2019-06-24 12:16:19 -04:00
wizjany 6d25513739 Don't allow setting build + passthrough in the flag helper.
It masks the warning message and too many people mess this up.
2019-06-22 14:15:21 -04:00
wizjany 96b61743b9 Fix lava fire being off by default.
No clue how this was never brought up before.

Also add system property to disable the ClassSourceValidator.
2019-06-19 23:50:18 -04:00
wizjany ff7209a58b Only check ride flag for pigs with saddles. 2019-06-19 23:22:21 -04:00
wizjany fe4f0cfc49 Bump dependencies.
Also remove intake. Unsure when that was ever used.
2019-06-13 09:17:20 -04:00
wizjany 9cf1e02506 Bump to 7.0.1-SNAPSHOT 2019-06-11 22:43:26 -04:00
wizjany b0f8852198 Bump to 7.0.0. Rename -legacy to -bukkit. 2019-06-11 22:32:04 -04:00
wizjany cce9c39e01 Changelog for 7.0.0. 2019-06-11 22:32:03 -04:00
wizjany 11c95861f9 More compat for 1.14. 2019-06-11 20:16:16 -04:00
KisaragiEffective 75bb0adbe6 Update README.md
fix syntax
2019-06-08 19:22:30 -04:00
Wyatt Childers 32ec74aed7 Fixed execute bit on gradlew 2019-06-08 15:54:50 -04:00
wizjany b152cdc4ec Tweak some event handling.
Fixes WORLDGUARD-4097, WORLDGUARD-3360.
2019-06-06 19:23:46 -04:00
Matthew Miller d019e43a81 Back to SNAPSHOT for continued development 2019-06-05 22:09:42 +10:00
Matthew Miller 8c778ed861 Update to RC2 2019-06-05 22:02:51 +10:00
wizjany 1b842204e9 Update readme links. 2019-06-04 18:31:19 -04:00
wizjany 8aa4c25186 Seeds don't modify blocks.
They already throw place events.
2019-06-04 17:20:42 -04:00
wizjany 026361ae0b Exclude some transitive deps. 2019-06-04 00:00:12 -04:00
wizjany 426a709e43 Fire off block place for items that modify blocks. 2019-06-02 19:33:42 -04:00
wizjany 903a831248 Fix dispenser workaround. 2019-06-02 12:12:57 -04:00
wizjany 1792bcb18a Fail (slightly) faster. 2019-05-31 14:08:45 -04:00
wizjany 23ab79c999 Wrap and unwrap.
Exceptions are fun.
2019-05-29 21:38:31 -04:00
wizjany a29afe8cc1 Also apply crop-growth to fully grown stems creating "fruit". 2019-05-27 20:51:28 -04:00
wizjany 029f867a41 Add crop-growth flag/config option.
Fixes WORLDGUARD-4088.
2019-05-27 20:42:17 -04:00
wizjany ce35798f67 Fix issues with sometimes-loaded worlds in location flags. 2019-05-26 02:19:33 -04:00
wizjany 0f989fc1b4 Small config cleanup. 2019-05-25 09:59:52 -04:00
wizjany 4871752f49 Switch to useInteractedBlock/useItemInHand for PlayerInteractEvent.
Bukkit has very odd behavior regarding cancelling this event.

Fixes WORLDGUARD-4090.
2019-05-22 18:21:37 -04:00
wizjany c4b31cf085 Allow newlines in blacklist messages with \n.
Fixes WORLDGUARD-4089.
2019-05-22 08:16:16 -04:00
wizjany 6e30f98322 Fix unknown group flag unmarshalling.
i.e. don't.
2019-05-21 19:44:53 -04:00
wizjany 4b320ab733 Workaround CraftBukkit bug causing BlockSpreadEvent to report air. 2019-05-21 19:42:56 -04:00
wizjany f516999087 Fix error when group flag existed for non-existent flag.
Probably caused by bad API usage /shrug.
2019-05-21 16:31:42 -04:00
wizjany 2b854f0d72 Use isTagged instead of getValues.
The implementation of getValues is quite atrocious for this purpose.
2019-05-20 23:56:37 -04:00
wizjany 36d25c08c6 Specify materials explicitly. 2019-05-17 23:52:21 -04:00
wizjany 3e899a70c4 Fix /rg claim. 2019-05-15 19:24:23 -04:00
wizjany d6c2504bbf Make CPU profiling interval configurable.
Also lower the default to something more sensible.

Also cleanup unused imports.
2019-05-14 19:01:47 -04:00
wizjany f2d2f47394 Don't fail hard in 1.14. (#409)
Prevent lots of console spam and lack of protection.
2019-05-14 12:33:56 -04:00
Matthew Miller aefebf32c2 Back to SNAPSHOT for continued development 2019-05-14 20:34:56 +10:00
Matthew Miller 7102f6204c WorldGuard 7.0.0 Release Candidate 1 2019-05-14 20:23:05 +10:00
wizjany d542ba78ff Remove AsyncCommandHelper for new AsyncCommandBuilder.
Helper suffers from race conditions for short-lived tasks, leading to
some poor UX conditions such as errors not propagating to the user
(because the exception handler wasn't attached to the future yet), or
lack of success messages.

This commit replaces that system by a Builder which takes a callable to
begin, and then takes supervisor, delay message, and the success and
failure messages and handlers as parts of the builder. The success and
failure handlers wrap the callable itself before submitting to the
executor so they will always be run. The supervisor and delay are added
as listeners to the future since they aren't required if the task is
sufficiently short-lived (and to maintain compatibility with the classes
which are now in WorldEdit).

The builder also supports Components for success and failure messages,
as well as consumers of the callable's result or exception for better
customization of output, instead of having to rely on adding a callback
to the future.

The future is still returned for certain special usages.
2019-05-12 14:40:09 -04:00
wizjany e7ef6af012 Handle BlockExplodeEvent as other explosion.
Also misc cleanup.
Closes #407, WORLDGUARD-3843.
2019-05-12 00:17:34 -04:00
isokissa3 1ffa4b48b8 Enderpearl & chorus-teleport flags should be checked before handlers
Before every handler would have been called, making them believe that the entry was successful
2019-05-11 14:36:15 -04:00
wizjany d4c49a7539 Clean up task monitoring, cancelling, exception handling etc.
Fixes a few issues such as /wg stopprofile leaving a pseudo-cancelled
task in the supervisor, delaying server shutdowns until profiles finish,
not forwarding exceptions that occur during tasks running correctly, etc.
2019-05-11 14:23:45 -04:00
wizjany 2e2be7092d Ensure un-marshalled registry flags are always lowercase.
Possibly old region files still had uppercase entries?

Fixes WORLDGUARD-3949 regression.
2019-05-11 11:30:46 -04:00
wizjany ec4c53da77 Minor cleanup. 2019-05-11 11:30:45 -04:00
Pietje 024a51549d Fix gitignore (#406)
Using Github Desktop on Windows, file paths with a leading slash do not seem to match anything. This commit changes the gitignore entries to a more widely supported format.
2019-05-09 22:41:36 +10:00
Matthew Miller 8c345cb64b Updated for Text3 2019-05-06 16:49:33 +10:00
wizjany 461f3e1faf Merge pull request #404 from TheMolkaPL/stoplag-fix
Fix activityHaltToggle in /stoplag
2019-05-05 17:10:37 -04:00
wizjany 6fd7190ff2 Ensure session handler order. 2019-05-05 16:55:27 -04:00
wizjany 5180673878 Treat inventory minecarts under chest-access.
Fixes WORLDGUARD-3585.
2019-05-05 16:14:35 -04:00
wizjany c57dd20f24 Brace. 2019-05-05 15:48:42 -04:00
TheMolkaPL 71df9c0011 Fix activityHaltToggle in /stoplag 2019-05-05 16:25:21 +02:00
wizjany b27f18788c Wrap /rg flags in a task. 2019-05-05 00:02:24 -04:00
wizjany 18365bbe42 Formatting fixes. 2019-05-04 23:21:19 -04:00
wizjany 82451595cb Add greeting-title and farewell-title flags.
Totally didn't accidentally include the flags in last commit.
Closes WORLDGUARD-4008.
2019-05-04 22:56:55 -04:00
wizjany c516eb2174 Add frosted-ice-melt flag, and frosted-ice-form flag.
Frosted-ice-form is checked with build, meaning it can be set to allow
for non-members to use frost walker, deny for members to not be able to
use frost walker, or none to respect membership.

Reverts behavior of ice-melt flag to pre-7.x behavior.
Apparently this wasn't covered before.

Fixes WORLDGUARD-4077.
Closes #364.
2019-05-04 20:52:28 -04:00
wizjany 7199b8e70f Add /rg flags command.
Provides an overview of all flags set on a region, including inherited
values, and allows the user to set or unset flags with a single click.
2019-05-04 20:52:13 -04:00
wizjany fc4c67ff29 Merge pull request #403 from EngineHub/feature/we-piston-commands-compat
WE Piston Compat
2019-05-01 00:34:50 -04:00
wizjany d9bb321f83 Add more fancy texts and pagination.
Also some general cleanup.
2019-04-30 19:53:19 -04:00
Kenzie Togami 7692e30721 Switch to new Exception stuff from WE 2019-04-30 15:24:15 -07:00
Kenzie Togami 5f88bef5ac Correct print(TextComponent) method 2019-04-30 13:34:45 -07:00
wizjany 5b0bfd50d3 Fix build. 2019-04-28 21:06:12 -04:00
wizjany 5c0be800ae Brace. 2019-04-28 20:43:01 -04:00
TheMolkaPL ac505f0064 Warn about consequences and add /stoplag confirm 2019-04-28 20:41:20 -04:00
wizjany 2aee42cbf2 Clean up gradle dependencies. Tell me if this breaks downstream builds.
Either I broke something, or you were using WG's jar for some dep that we
don't consider to be API.
2019-04-28 20:36:28 -04:00
wizjany 5c8b6d3f95 Lots of fancy texts. 2019-04-28 20:21:38 -04:00
wizjany eab7b5c47f Remove artifactory resolve block 2019-04-27 16:43:32 -04:00
wizjany 36eba9c9dd That's not supposed to be there. 2019-04-26 15:07:36 -04:00
wizjany 3b8b67da84 Add logo to source, remove outdated notes. 2019-04-26 15:06:47 -04:00
wizjany d9b09ab7f1 Damage is already handled and entering is handled via interact.
This method is redundant.
2019-04-25 11:13:30 -04:00
Matthew Miller 50e62bd0e7 Update text for WorldEdit changes (#401)
* Update for text in WE

* Properly write the legacy converter

* Made the text less thicc

* Update for new text API in WE
2019-04-25 19:40:01 +10:00
Matthew Miller abfe3a2eb9 Fixed chipped and damaged anvils not being protected from use/interact 2019-04-23 12:36:20 +10:00
wizjany e94af1d77e Treat kelp as vines for vine-growth.
Closes WORLDGUARD-4068.
2019-04-19 23:25:26 -04:00
wizjany 1dbd25d15e Add block-trampling flag.
Applies to turtle eggs and farmland.

Closes WORLDGUARD-4067, WORLDGUARD-3666.

Also do some misc cleanup.
2019-04-19 23:14:14 -04:00
wizjany c3675a10a2 Force eject players from vehicles if the get too far.
Fixes WORLDGUARD-3936.
2019-04-17 21:24:10 -04:00
wizjany ef2783f30a Add snowman-trails flag.
Closes WORLDGUARD-3566, #378.

Also clean up some listeners, and the flag listing.
2019-04-17 21:23:29 -04:00
wizjany 2c2b475513 Track AreaEffectCloud cause.
Also a bit of cleanup in EventAbstractionListener.

Fixes WORLDGUARD-3776.
2019-04-17 20:16:38 -04:00
wizjany 0ebb4e0ffa Formatting fix. 2019-04-14 11:34:54 -04:00
KisaragiEffective 47fb9bd30d Remove redudant type parameters. 2019-04-08 22:04:02 +09:00
KisaragiEffective 5ffade9787 Update CONTRIBUTING.md (#399)
fix broken link to Oracle Conventions
2019-04-07 23:12:13 +10:00
wizjany ca92464cca Revert "Load before worlds do."
This reverts commit 397a71a602.

Apparently this doesn't actually fix the issue. Some things
just straight up happen without sending events to plugins and there's
nothing we can do about it.
2019-04-06 17:33:56 -04:00
wizjany 453740b56a Don't whitelist droppers and hoppers.
By the time this code is called, the performance hit happened already.
There's a separate way to whitelist these that still allows keeping
the protections active.
2019-04-06 14:27:55 -04:00
wizjany 397a71a602 Load before worlds do.
When worlds first load, events start happening before plugins normally
(POSTWORLD) enable. This means that regions and other protections won't
be active when these events are called.

This shouldn't break anything that depends on us, e.g. custom flags,
since our API contract already states that should be done on load,
and all plugins are loaded on startup (just not enabled).
2019-04-05 22:03:29 -04:00
wizjany 44c4e5816f Move log message about loading regions to proper location. 2019-04-02 17:18:44 -04:00
wizjany 41268ca443 Don't break completely if regions fail to load. 2019-04-02 17:13:24 -04:00
Matthew Miller c7ed49388c Make 'invincibility-removes-mobs' affect projectile shooting entities. 2019-03-31 21:14:29 +10:00
wizjany 874e429779 Make input more lenient. Allow specifying TZ other than UTC.
Also remove 'none' and cleanup LocationFlag.
2019-03-30 20:07:35 -04:00
JOO200 9c5eee90da Changed to java 8 time api 2019-03-30 18:41:42 -04:00
JOO200 4f088e5bf0 Added TimestampFlag 2019-03-30 18:41:42 -04:00
wizjany c2f96c9587 Checkstyle pls.
That was the auto-folder's fault.
2019-03-30 18:39:55 -04:00
wizjany c181a86fd1 Better wrapped player usage. Requires latest WorldEdit build. 2019-03-30 18:09:27 -04:00
wizjany e2ffab5ee8 Cleanup last commit. 2019-03-28 23:07:48 -04:00
wizjany 8a3f066023 Turtle eggs throw PIE when being broken. 2019-03-28 23:02:28 -04:00
wizjany c53ed56b3a Check flag change handlers when world changes.
Global regions aren't actually part of the ApplicableRegionSet,
so the set difference will be empty even if the global region has changed.
2019-03-23 12:29:12 -04:00
wizjany 6144ca82ac Fix removing regions from manager with the REMOVE_CHILDREN strategy. (#397)
* Added test for removing regions from manager.

* Fix removing regions with REMOVE_CHILDREN strategy.
2019-03-22 14:20:32 -04:00
wizjany d091cb578f Don't check spaces that won't get moved into by pistons.
Fixes WORLDGUARD-4064.
2019-03-20 21:50:00 -04:00
wizjany b2fe4c9c71 Move tests to core.
(None of them are implementation-specific)
2019-03-20 17:50:12 -04:00
wizjany ea47e93323 Really remove deprecated flags. 2019-03-14 18:10:56 -04:00
wizjany 10100bd194 Remove deprecated flags. Make sure we register our flags first.
Also make enderpearl + chorus fruit flags respect entry/exit deny message flags.
2019-03-14 18:07:41 -04:00
wizjany 91687dc204 Only check for flag changes when regions change.
This functionally reverts e5b76a5, though individual classes can change
this behavior on an individual basis by overriding the method.

Also, make time-lock and weather-lock restore only initial values,
which should be more intuitive behavior when multiple regions overlap
with different flag values.
2019-03-12 18:45:08 -04:00
wizjany e091a59063 Remove ender-chest protection.
Enderchests are not modified on use. In fact, they don't even
have inventories, so they are not modified at all. To deny usage,
the interact flag must be denied, since they most closely fit in
a category with other interact-covered blocks (and not use-covered
blocks, since using them does not change the region in any way).

This commit reverts f7d36b and ea4f4c0.
2019-03-10 19:09:36 -04:00
wizjany ee7dc27283 Actually report game rule values.
Was just "<Recursive>" before, which is pretty useless.
2019-03-07 17:44:20 -05:00
wizjany 54c3cdad77 Bukkit does this apparently. 2019-03-06 19:43:59 -05:00
wizjany ff37cc7935 Add item-frame-rotation flag.
When set to allow, allows players to rotate item in item frames even if
they wouldn't normally have permissions to modify the item frame.

Fixes WORLDGUARD-3588.
2019-03-06 19:05:36 -05:00
wizjany b6e2bca5bc Make chat + command flag handing more sane.
* Send/receive chat and allowed/blocked cmd flags now respect deny-message flag.
* Added `regions.cancel-chat-without-recipients` option to disable the default behavior.
2019-03-04 18:53:26 -05:00
Nonsence 1f85a53117 Update README.md: Fix broken markup (#396) 2019-03-04 08:21:26 -05:00
wizjany bd4726f887 Update links in readme. 2019-03-02 15:46:22 -05:00
wizjany 9ea2312751 Apparently some people see red flag and think those are broken.
This has unfortunately happened more than 2 times.
2019-03-02 13:14:01 -05:00
wizjany cc988c0b5a Minor typo. 2019-03-02 12:43:58 -05:00
wizjany af93530dbe Fix region equality across multiple region managers. (#395)
It is possible, for example when teleporting between two worlds, that
regions in two different managers are compared. If the regions in each
world have the same name, they would return equal. Removing the equals
override will prevent two different regions from seeming equal even if
they are not.
2019-03-01 21:42:07 -05:00
wizjany 43d8cf8cba Bye Java 6. 2019-02-26 12:14:38 -05:00
wizjany 090a00d6d8 Fire UseItemEvent when fishing rod is cast.
This apparently no longer throws an interact.

Fixes WORLDGUARD-4018.
2019-02-25 23:47:24 -05:00
wizjany a233be1df8 Sponge simulation now also clears waterlogged blocks.
Fixes WORLDGUARD-4011.
2019-02-15 16:00:30 -05:00
wizjany f9339e144e CSV support was removed 8 years ago.
Even the migrator is long gone.

056f8a57c7
2019-02-13 23:30:40 -05:00
wizjany 1f1e6eedf6 Cleanup session loading.
Apparently the spigot server stores time-lock between logout and login,
but not weather-lock. This should work around any such issues by
re-applying handlers on login.
2019-02-12 14:56:03 -05:00
wizjany 96e7c43f56 Fix newline parsing in StringFlag.
This was committed broken 7 years ago and no one told us til today.
2019-02-11 22:22:41 -05:00
wizjany f8e129f33e Add debug listener for DamageEntityEvent. 2019-02-11 16:57:15 -05:00
wizjany 144c31645c Use fake player build override for NPCs in SessionManager too. 2019-02-08 22:29:00 -05:00
Wizjany d24157e693 Allow NPCs to bypass region protections. (#393) 2019-02-04 18:50:09 +10:00
wizjany d5dddba8bc Prevent exception with legacy materials.
Not sure what this legacy material layer is doing here, but it can
potentially throw exceptions when we add one to our material flags.
2019-02-03 19:28:59 -05:00
Wizjany 72a392aca2 Moved SquirrelID relocation to core project. (#394)
This allows projects depending on core to properly use the ProfileService and ProfileResolver without themselves relocating the package.
2019-01-27 19:47:08 -05:00
wizjany c6442e6669 Re-enabled checkstyle, do some cleanup. 2019-01-27 16:13:58 -05:00
Wizjany 0102dbb9bc Move MapFlag to core. (#392)
Original PR was made before API stuff was moved to core, so when the PR was pulled it ended up back in legacy.
2019-01-27 13:54:30 -05:00
Wizjany 3f7a9f9bc8 Change CI link to enginehub 2019-01-23 17:19:46 -05:00
Matthew Miller ae51d74afb Back to SNAPSHOT for continued development 2019-01-22 22:17:22 +10:00
Matthew Miller e51a22032e Bumped to Beta 3 2019-01-22 22:13:46 +10:00
Matthew Miller 84017bffc4 Added macro and colour support to deny-message 2019-01-19 21:51:52 +10:00
Matthew Miller 60731f9836 cleanup block listener 2019-01-12 18:12:06 +10:00
Matthew Miller 3ea7c9fc08 Added GLIDE and SWIM MoveTypes, and made Horses use RIDE 2019-01-02 17:24:49 +10:00
Matthew Miller 9804c69044 Added an option to block conduit effects 2019-01-02 14:25:43 +10:00
Mark Vogel cd39387e7f Add MapFlag (#375)
* Add MapFlag

Signed-off-by: Mark <33119mark@gmail.com>

* Remove apache import

Signed-off-by: Mark <33119mark@gmail.com>

* Add copyright

Signed-off-by: Mark <33119mark@gmail.com>
2018-12-30 17:20:12 +10:00
Matthew Miller b48e145508 Move StringMatcher to before other things 2018-12-29 12:38:45 +10:00
Matthew Miller 405b210fb5 Cleanup usage of BukkitWorldConfiguration 2018-12-26 15:19:23 +10:00
Matthew Miller d4d7601125 Fixed broken merge 2018-12-26 14:34:18 +10:00
Matthew Miller fdd9064170 Abstracted the commands away from the Bukkit platform (#391)
* Start work on abstracting commands out of worldedit-legacy

* A lot more work towards abstract commands

* Move a lot of code to WorldEdit

* Setup the exception converter

* Use WorldEdit styling and move more of the RegionContainer across.

* Abstract away the debug commands and a few other things - Only the matcher to go.

* It compiles

* It now seems to run fine

* Fixed version typo
2018-12-26 14:32:35 +10:00
Matthew Miller 803c2055c3 Update SquirrelID for JAXB removal. 2018-12-23 12:47:23 +10:00
Matthew Miller 344c6cf814 Minor cleanup of blacklists 2018-12-21 22:33:43 +10:00
Matthew Miller 863f6cc13b Switched to heirarchy object report 2018-12-18 18:13:06 +10:00
Matthew Miller 3dd35dabec Remove some files that were listed in the gitignore but still in the repo 2018-12-18 16:52:31 +10:00
Matthew Miller 80aec378d8 Fixed the wrong cache directory being used. 2018-12-10 11:39:03 +10:00
Matthew Miller 6dbd731c92 Added bonemeal to the list of items that modifies blocks. 2018-12-09 16:44:51 +10:00
Matthew Miller aea129889c Update bStats (Didn't realise I forgot to do this) 2018-12-02 21:49:19 +10:00
Matthew Miller 2757a001c0 Gradle 5 2018-12-02 21:40:46 +10:00
Matthew Miller 693314c7f7 Also block /deop 2018-12-02 15:47:45 +10:00
Matthew Miller db35c908ba Switch back to SNAPSHOT for continued development 2018-11-28 20:39:47 +10:00
Matthew Miller 14ce7d1be2 Bump to beta 2 2018-11-28 20:37:39 +10:00
Matthew Miller 015f192193 Added toString to LazyLocation to fix /rg info with the teleport flag. 2018-11-17 16:33:30 +10:00
Matthew Miller 83b375b6e1 Sponges now destroy kelp and seagrass, similar to vanilla behaviour. 2018-11-17 10:15:48 +10:00
Matthew Miller 91696533cf Update to the new Vector system 2018-11-04 16:57:59 +10:00
Matthew Miller 0dc5781326 Can't compileOnly and shadow, gotta find another solution for the bStats repo issue. 2018-10-10 23:24:16 +10:00
Matthew Miller 5ad21521be IvnentoruClickEvent sometimes passes null inventories or inventories with null holders 2018-10-10 20:33:32 +10:00
Matthew Miller e0b91e9529 Merge pull request #389 from Brokkonaut/fix-npe-BukkitOfflinePlayer
Fix NPE in WorldGuardPlugin.wrapOfflinePlayer()
2018-10-08 23:20:11 +10:00
Matthew Miller 7e0ff24c57 Block minecraft:op as well 2018-10-07 23:14:37 +10:00
Brokkonaut be426e92df Fix NPE in WorldGuardPlugin.wrapOfflinePlayer()
The constructor of BukkitOfflinePlayer calls the constructor of BukkitPlayer with a null player. So without this fix it is not possible to create any BukkitOfflinePlayer.
2018-10-05 23:51:08 +02:00
Matthew Miller a6261b9071 Added an option to disable particle effects on deny 2018-09-28 12:16:22 +10:00
Matthew Miller f235e870a7 Back to SNAPSHOT for continued development 2018-09-28 12:16:21 +10:00
Matthew Miller a26eb87603 Release WorldGuard 7 Beta 1 2018-09-28 12:16:21 +10:00
Matthew Miller 7fb7d59856 Merge pull request #388 from PseudoKnight/master
Fix protections for potted plants and undyed shulker boxes
2018-09-26 15:45:20 +10:00
Matthew Miller 01dfebe531 Fixed blockCreatureSpawn not working. 2018-09-26 15:03:30 +10:00
Matthew Miller 87e5770405 Fixed WorldGuard's player not inheriting properly from WorldEdit. 2018-09-26 14:01:25 +10:00
PseudoKnight d3c4681c49 Fix protections for potted plants and undyed shulker boxes 2018-09-22 21:31:00 -07:00
Matthew Miller e43daa726a Added bStats 2018-09-20 23:35:55 +10:00
Matthew Miller 8e819f7a82 Merge pull request #386 from Librazy/master
Delay ProcessPlayerEvent by one tick on bukkit onEnable
2018-09-03 21:25:39 +10:00
Librazy ee4259b88d Delay ProcessPlayerEvent by one tick, allowing other plugin to register their Handlers when /reload 2018-08-30 18:27:40 +08:00
Niklas Linz 8771173146 Update sql-v1
Set value higher to prevent errors with new entitytypes in database.

Example for flag denyspawn with some 1.13 EntityTypes: 

['minecraft:polar_bear', 'minecraft:skeleton', 'minecraft:giant', 'minecraft:witch',
  'minecraft:zombie_pigman', 'minecraft:wither_skull', 'minecraft:husk', 'minecraft:ender_dragon',
  'minecraft:cave_spider', 'minecraft:guardian', 'minecraft:silverfish', 'minecraft:stray',
  'minecraft:vindicator', 'minecraft:endermite', 'minecraft:magma_cube', 'minecraft:spider',
  'minecraft:vex', 'minecraft:zombie', 'minecraft:creeper', 'minecraft:wither', 'minecraft:zombie_villager',
  'minecraft:evoker']

Its to big for 256 chars.

Error:


[19:17:28 WARN]: [WorldGuard] Failed to save the region data for 'akania' during a periodical save
com.sk89q.worldguard.protection.managers.storage.StorageException: Failed to save the region data to the database
        at com.sk89q.worldguard.protection.managers.storage.sql.SQLRegionDatabase.saveChanges(SQLRegionDatabase.java:270) ~[worldguard-legacy-7.0.0-SNAPSHOT-dist.jar:?]
        at com.sk89q.worldguard.protection.managers.RegionManager.saveChanges(RegionManager.java:135) ~[worldguard-legacy-7.0.0-SNAPSHOT-dist.jar:?]
        at com.sk89q.worldguard.protection.managers.RegionContainerImpl$BackgroundSaver.run(RegionContainerImpl.java:228) [worldguard-legacy-7.0.0-SNAPSHOT-dist.jar:?]
        at java.util.TimerThread.mainLoop(Timer.java:556) [?:?]
        at java.util.TimerThread.run(Timer.java:506) [?:?]
Caused by: java.sql.BatchUpdateException: Data truncation: Data too long for column 'value' at row 1
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:488) ~[?:?]
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.SQLError.createBatchUpdateException(SQLError.java:1163) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1778) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeBatchInternal(PreparedStatement.java:1262) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:970) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.sk89q.worldguard.protection.managers.storage.sql.StatementBatch.executeRemaining(StatementBatch.java:50) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.RegionUpdater.replaceFlags(RegionUpdater.java:170) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.RegionUpdater.apply(RegionUpdater.java:331) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.DataUpdater.executeSave(DataUpdater.java:130) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.DataUpdater.saveChanges(DataUpdater.java:73) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.SQLRegionDatabase.saveChanges(SQLRegionDatabase.java:268) ~[?:?]
        ... 4 more
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'value' at row 1
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3974) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1756) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.PreparedStatement.executeBatchInternal(PreparedStatement.java:1262) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:970) ~[spigot-latest.jar:git-Spigot-fe3ab0d-bfb9131]
        at com.sk89q.worldguard.protection.managers.storage.sql.StatementBatch.executeRemaining(StatementBatch.java:50) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.RegionUpdater.replaceFlags(RegionUpdater.java:170) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.RegionUpdater.apply(RegionUpdater.java:331) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.DataUpdater.executeSave(DataUpdater.java:130) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.DataUpdater.saveChanges(DataUpdater.java:73) ~[?:?]
        at com.sk89q.worldguard.protection.managers.storage.sql.SQLRegionDatabase.saveChanges(SQLRegionDatabase.java:268) ~[?:?]
        ... 4 more
2018-08-30 14:10:52 +10:00
Matthew Miller d28a31f255 Merge pull request #379 from sk89q/string-ids
Update WorldGuard to 1.13 and move parts to Core
2018-08-30 14:07:59 +10:00
Matthew Miller b4bda6bfaf NEEDS LATEST WORLDEDIT - Moved report framework to WorldEdit, and made most config values be accessible without the BukkitWorldGuardWorldConfiguration 2018-08-15 12:49:25 +10:00
Matthew Miller 44e3f720de Fixed an EntityType bug and removed more deprecated code. 2018-08-13 22:46:36 +10:00
Matthew Miller 7f47e31686 Fixed UUID migrations sometimes failing. 2018-08-13 22:20:27 +10:00
Matthew Miller b2e64498a8 Move some more code to core. 2018-08-13 22:20:27 +10:00
Matthew Miller e31fa306ab Fixed weather flag 2018-08-13 22:20:27 +10:00
Matthew Miller 1123270a07 Fixed an issue with Bukkit being terrible. 2018-08-13 22:20:27 +10:00
Matthew Miller b850b5caf8 Cleanup some more Bukkit specific code. 2018-08-13 22:20:27 +10:00
Matthew Miller ba61919168 Added block support to the matchers 2018-08-13 22:20:27 +10:00
Matthew Miller 34efb6e40e Modify the target creation methods. 2018-08-13 22:20:27 +10:00
Matthew Miller 3203a81710 Use BlockTarget for blocks. 2018-08-13 22:20:27 +10:00
Matthew Miller d8dba47c0f Fixed bugs in the gamemode marshaller. 2018-08-13 22:20:27 +10:00
Matthew Miller a6cfe7d0c9 Move the lowercase unmarshalling entity code. 2018-08-13 22:20:27 +10:00
Matthew Miller f19d2ee73d Fixed an error with Chest Protection 2018-08-13 22:20:27 +10:00
Matthew Miller bd89bd9d2f Fixed a few more migration issues 2018-08-13 22:20:27 +10:00
Matthew Miller 66eb8fa553 Remove the "/" adding code from EntityTypeFlag. 2018-08-13 22:20:27 +10:00
Matthew Miller dcdd0497d8 Fixed a few permission errors. 2018-08-13 22:20:27 +10:00
Matthew Miller 8ac5f8f6f2 Fixed file permissions 2018-08-13 22:20:26 +10:00
Matthew Miller 45a4e59965 Fixed matching with blocks vs items 2018-08-13 22:20:26 +10:00
Matthew Miller 43ed630034 Fixed Spawn Eggs being awful 2018-08-13 22:20:26 +10:00
Matthew Miller 3189b1ac13 Fixed another error. 2018-08-13 22:20:26 +10:00
Matthew Miller e94083045f Fixed profile migrations happening too early. 2018-08-13 22:20:26 +10:00
Matthew Miller acce59edd4 Fixed an error with chest protection listener. 2018-08-13 22:20:26 +10:00
Matthew Miller bb29883fe0 Switch to real 1.13 release 2018-08-13 22:20:26 +10:00
Matthew Miller e7ff99ae96 Fixed an issue with flags getting double registered. 2018-08-13 22:20:26 +10:00
Matthew Miller b10cf6adbc It now runs 2018-08-13 22:20:26 +10:00
Matthew Miller 2e8d14c995 It compiles. 2018-08-13 22:20:26 +10:00
Matthew Miller 89db0d9fee Further compat work. 2018-08-13 22:20:26 +10:00
Matthew Miller 6c5319f355 Major work towards 1.13 compat 2018-08-13 22:20:01 +10:00
Matthew Miller 8eeab682db Merge pull request #381 from Blamo27/fix/npc-issue
Can't hit NPCs (Sentinel #249)
2018-08-04 10:12:47 +10:00
Dr_Blamo 2ae6f39a09 Fix Sentinel #249 issue (Can't hit NPCs)
https://github.com/mcmonkey4eva/Sentinel/issues/249
=> Can't hit NPCs
2018-08-01 06:35:36 +02:00
wizjany d2c52f7c1b Make send- and receive- chat flags respect group flags. 2018-02-24 09:39:25 -05:00
Wizjany 3a332fd87d Fix off-by-one in area calculation.
Even the volume calculation had it correct.
Also fix code style in contains.
2018-01-21 00:31:47 -05:00
Mitchell Cook 0f72811bfc Added UUID support with player name as secondary. (#374) 2018-01-21 00:29:16 -05:00
wizjany 95b88ea64b Added config option to ignore hoppers moving items.
Defaults to old behavior (false).
2017-10-14 14:41:58 -04:00
wizjany f76259df82 Make the full jump to 1.12.
Warning: this really really really does not work with previous MC versions.
2017-09-16 16:48:38 -04:00
wizjany 3a8e3e84b8 Add missing disabled region support check.
Fixes WORLDGUARD-3839.
2017-06-20 22:04:38 -04:00
wizjany 84bc322de7 Push 6.2.1 and bump. 2017-06-08 12:35:52 -04:00
Benedikt Hruschka 129bbd8ea1 Make flag list more readble 2017-06-08 12:35:51 -04:00
wizjany 4dc6e27660 Backport guava's concurrent package to remain compatible between <= MC 1.11 and >= MC 1.12.
Fixes WORLDGUARD-3820.
2017-06-08 12:35:50 -04:00
wizjany 4cb29796c1 Fix error spamming when hoppers are attached to invalid multichests (triple+).
The extra chests might be unprotected, but this shouldn't be possible in vanilla.
2017-05-22 13:56:46 -04:00
wizjany 85693b91b3 Protect armor stands from all non-Player entities, not just living ones.
Fixes WORLDGUARD-3796.
2017-01-25 19:39:53 -05:00
wizjany 1c29e85f19 Prefer Material enum over ItemType lookup when parsing TargetMatchers.
This will make Bukkit's names take priority when trying to identify a block or item,
since ItemType lookup will return, e.g. "birch_door_item" for "birch_door", even though
there's a block with the name "birch_door".

Note that using int ids is always preferable when possible since there's no confusion there.

Fixes WORLDGUARD-3790.
2017-01-12 14:11:57 -05:00
wizjany e019890f1d Add a flag that blocks the damage from withers.
Doesn't cover the skull projectiles, just body damage.
Fixes WORLDGUARD-3787.
2017-01-08 15:47:38 -05:00
wizjany fb90b1446f Move fireworks to their own flag ("firework-damage"). 2017-01-08 14:22:20 -05:00
wizjany 22ef224a81 Include fireworks in other-explosion flag.
Unfortunately, since fireworks neither have a "shooter" entity nor fire an EntityExplode,
the only way to mitigate damage is a complete on/off for any damage they cause.

Fortunately (probably), this should not interfere with elytra boosting, since the
acceleration is applied directly to the player upon use, not from the firework "explosion".

Fixes WORLDGUARD-3786.
2017-01-04 16:33:19 -05:00
wizjany c0f3171a33 Add mobs.block-armor-stand-destroy config option.
Same as the -painting- and -item-frame- ones.
Fixes WORLDGUARD-3781.
2016-12-22 23:38:28 -05:00
wizjany 67ece5c5d7 Add option to allow Forge clients through host keys.
Setting "security.host-keys-allow-forge-clients" will accept the "\0FML\0" identifier that Forge clients add to their host name when connecting to a server.
Fixes WORLDGUARD-3537, WORLDGUARD-3596.
2016-12-22 19:42:43 -05:00
wizjany 46cca2b950 Fix HealFlag missing.
Meanwhile people were getting fed twice as fast.
Fixes WORLDGUARD-3785.
2016-12-15 21:49:42 -05:00
wizjany 6e56763a7f Protect plants in flower pots via build, not just interact.
Fixes WORLDGUARD-3773.
2016-12-03 13:51:34 -05:00
442 changed files with 17494 additions and 15166 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
*.java diff=java
*.java diff=java
+1
View File
@@ -0,0 +1 @@
github: enginehub
+34
View File
@@ -0,0 +1,34 @@
---
name: Bug report
about: Report a way in which WorldGuard is not working as intended
title: ''
labels: type:bug, status:pending
assignees: ''
---
**Versions**
<!-- Please include the full version of WorldEdit, WorldGuard and the platform (Bukkit/Spigot/Paper) you are running, e.g. output from `/we version`, `/wg version` `/version` commands. Please ensure you are running up to date software before making a bug report. Old versions will receive little to no support. -->
WorldEdit version:
WorldGuard version:
Platform version:
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
**To Reproduce**
<!-- Steps to reproduce the behavior: -->
1. ...
2. ...
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. Screenshots of `/rg info` for any applicable regions (or simply the link from `/wg report -p`) are good to include. -->
**Additional context**
<!-- Add any other context about the problem here. -->
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: EngineHub Discord
url: https://discord.gg/EngineHub
about: Please ask and answer questions here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for WorldGuard
title: ''
labels: type:feature-request, status:pending
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
**Describe alternatives you've considered**
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
+10 -8
View File
@@ -1,17 +1,19 @@
/.classpath
/.project
/.settings
/target
.classpath
.project
.settings/
target/
.DS_Store
**/*.iml
**/.idea
/bin
/dependency-reduced-pom.xml
bin/
dependency-reduced-pom.xml
*-private.sh
/.gradle
**/build
.gradle/
**/build/
out/
scripts/
+1
View File
@@ -1,4 +1,5 @@
language: java
dist: trusty
jdk:
- oraclejdk8
notifications:
+157
View File
@@ -1,5 +1,162 @@
# Changelog
## 7.0.5
* Add a use-anvil flag and exclude it from the use flag (since they can break on use.)
* Expand crop-related options (crop-growth, etc) to sweet berry bushes, nether wart, and bamboo.
* Add a config option (`mobs.block-vehicle-entry`) to prevent non-players from entering vehicles.
* Add a UUID flag (for developers/API usage).
* Add map query methods with fallback flag (for developers/API usage).
* Add `on` and `off` optional arguments for `/rg toggle-bypass` command.
* Add additional timings info for session handlers.
* Fix sponge-simulation clearing NBT from blocks. Note that if you are using sponge simulation you should switch to something like CraftBook as the feature will be removed from WorldGuard in a future (major) version.
* Fix the `/rg` command showing up as unknown client-side to players without bypass perms.
* Fix error propagation from third-party flag loading causing WG to error.
* Fix a (harmless) exception that occurred when swapping armor slots to the offhand slot.
* Fix empty lines being sent on enderpearl/chorus-fruit teleport if the deny messages were empty.
* Fix an issue with falling blocks when using max-priority-association.
* Fix performance issues with third-party plugins querying protection for offline players.
* Fix dispensing shulkers over region boundaries.
* Fix iron door interaction being denied as if it were a regular door.
* Fix being able to enter/exit regions with the flag denied by using entity mounting functions in other plugins.
## 7.0.4 (including beta1)
* Add support for MC 1.16. Dropped support for previous versions.
* Add respawn-anchors flag mirroring the sleep flag (e.g. to prevent using respawn anchors to cause explosions in the overworld)
* Add nether vines to vine-growth flag.
* Add config option to disable the bypass permission cache.
* Fix water-flow flags not checking waterlogged blocks.
* Add config option to consider non-player causes (e.g. pistons, flowing water) to only be members of the highest priority region. This should be enabled for plots-within-city-like setups to prevent things in plots from modifying the city.
* Fix items dropping from falling blocks that were suppressed by other plugins.
* Add config option to block turtle egg trampling.
* Fix ride flag being checked on striders that didn't have saddles.
* Add config option to have /rg bypass toggled off on login.
* Developer changes: Methods taking names in Domains are now explicitly deprecated (was previously just a javadoc comment.); These will eventually be removed: there is no reason to use names over UUIDs. Offline players and NPCs alike have stable UUIDs.
* Also for developers; The new `com.sk89q.worldguard.protection.util.WorldEditRegionConverter` class has some useful static methods to convert to and from WorldEdit's Region and WorldGuard's ProtectedRegion classes.
## 7.0.3
* This is the last release supporting MC 1.14 and 1.15.
* Decouple chest-access flag from interact flag. IMPORTANT: If you relied on allowing players to access chests via setting
the interact flag to allow, you will now need to set the chest-access flag to allow instead (or as well). This does not
affect any setups where users were *not* supposed to be able to access chests and other inventories.
* Add natural-health-regen and natural-hunger-drain flags. Unlike the heal/feed flags, these can not restore or deplete health/hunger.
* Fix the interact flag allowing breaking of turtle eggs (now tied directly to block-trampling flag).
* Fix a memory leak that could occur with many many explosives.
* Add regions.titles-always-use-default-times config option. Set this to true if you use greeting/farewell titles and another plugin
makes the titles disappear too quickly.
* Add protection for cauldrons water level changing.
* Improve diagnostic hints and information, such as spawn protection warnings, flag colors in region info, etc.
* Fix waterlogged blocks bypassing water-flow flag.
* Workaround for a CraftBukkit change that made no-physics-sand/gravel non-functional.
* Workaround for CraftBukkit throttling move events.
* Track projectiles shot by dispensers.
* Allowed setting passthrough allow on global to unprotect it if members/owners are added.
* Add support for newer forge clients (FML2) in host keys.
* Allow using WorldEdit's `//world <worldname>` command to select a world for region commands. This removes the need to
use `-w <worldname>` in every command when running commands from console.
* Add a teleport-message flag, shown when using `/rg tp`.
* Add coral-fade flag, which prevents corals from drying when out of water.
* Fix spammy deny-message when walking over redstone ore with certain flag setups.
* Improve handling of interacting with various tools in hand that didn't modify blocks. (eg opening a chest with an axe in hand)
* Fix allow-all-interact option not being read from per-world configs.
* Fix misattribution of pets (eg wolves) in PvP.
* Improve performance of hopper checks when on recent builds of Paper.
* Add event-handling.break-hoppers-on-denied-move config option to prevent hoppers from being broken (but items still won't be moved).
* Note to developers using the WorldGuard API: If you specifically relied on flags such as greeting/farewell, deny-message, etc being
StringFlags, be warned that this will change in a future version to support JSON text components. Please plan accordingly.
## 7.0.2
* Update to MC 1.15. Still compatible with 1.14, and incompatible with 1.13, as before.
* Add an informational message when defining a region that overlaps vanilla spawn protection.
* Protect against pushing a piston with another piston on a region border.
* Protect against buckets in dispensers on region borders.
## 7.0.1
* Add `/rg toggle-bypass` command which temporarily turns off region bypassing until used again.
* More improvements to `/rg flag` and `/rg flags` commands.
* Fix some checks for adding owners to unclaimed regions.
* Fix an issue with time-/weather-lock flags when logging in to a region with the flag set.
* Fix cause tracking in vehicles (incl. breaking lilypads in a boat)
* Use async teleports on Paper.
* Include hopper minecarts in the ignore hoppers config setting.
* Add sugar cane and cacti to the crop-growth flag. Bamboo is also included pending Spigot throwing an event for it.
* Specifically track when players ignite creepers with flint and steel.
* Fix fuzziness when using bonemeal near a protected region.
* Fix color codes not applying in greeting, etc flags when placed after a newline (\n).
* Add applicable region information to `/wg report`.
* Fix pistons flag not applying to sticky pistons pulling blocks.
* Add some custom metrics for bStats.
* Everything in the RC/beta changelog below.
## 7.0.1 RC 2 (inc. beta 1)
* Due to breaking changes in important Bukkit API, this is not compatible with MC 1.13!
* Update to MC 1.14. Adds protection for new blocks, etc.
* To allow players to read from lecterns, but not take the book, flag interact allow, and then flag chest-access -g nonmembers deny.
* Add ravager-grief flag.
* Fix overprotection of unsaddled pigs with the ride flag.
* Fix lava fire defaulting to off (won't change existing configs).
* Fix damaged/chipped anvils not respecting use flag like regular anvils.
* Add on-equip blacklist event. Note that it is overprotective due to deficiencies in Bukkit API.
* Update WorldEdit CUI when using /rg select.
* Add config option to disable villagers getting zapped into witches. ("weather.disable-villager-witchification")
* Add entity support to interact-whitelist config option (use the Material of the corresponding item).
* Fix vehicle-place protecting the rails at the very top of region boundaries incorrectly.
* Fix for emptying buckets on waterloggable blocks.
* Whitelist all player -> player interactions (previously was spammy in pvp).
* Fix sleep flag not protecting against explosions in nether/end.
* Add config for the teleport-on-void to reset fall distance.
* Fix config options taking material lists requiring "minecraft:" namespace.
* Fix disallowed-lightning-blocks situationally not working.
* Fix errors that occurred when plugins used falling block entities with non-item materials.
* Add special support for Paper servers (papermc.io): Paper's API allows us to track who launched fireworks.
* Fireworks are now protected by default. On Paper servers, members can use them by default (to deal damage),
on non-Paper servers, flag firework-damage allow to revert to old behavior (everyone can deal damage with fireworks by default).
* Misc performance enhancements for Paper servers.
* Add 'regions.use-paper-entity-origin' as an experimental setting (default off) for Paper servers. Enabling it will make non-player entities be treated as members of the place they spawned, instead of their current location when flags are checked.
## 7.0.0
* Added support for MC 1.13, dropped support for previous versions.
* Added lots of interactive text in e.g. `/rg info` command.
* Added `/rg flags` command which allows viewing and interactively setting all flags on a region.
* Large behind-the-scenes changes to WorldGuard's API (developers, see https://worldguard.enginehub.org/en/latest/developer/)
* Places that used numeric block ids (e.g. blacklist) should now use Minecraft's new string IDs.
* Fix various interactions with NPCs and region protection.
* Sponge-simulation now destroys kelp and seagrass, and de-waterlogs blocks.
* Added an option to block conduit effects.
* Fix using newlines in string flags such as greeting and farewell.
* Add item-frame-rotation flag.
* Ender chests no longer require chest-access (since they don't have inventories).
* Add kelp to vine-growth flag/config.
* Add block-trampling flag (for turtle eggs and farmland).
* Add snowman-trails flag.
* Track potion area-of-effect cloud causes for pvp etc. protection.
* Add confirmation to /stoplag command.
* Forcefully eject players from vehicles trying to force their way into entry deny regions (and out of exit deny).
* Fix removing child regions when removing a region with children.
* Fix some over-protectiveness of pistons.
* Chat and command flags (send-/receive- and allowed-/blocked-) now respect deny-message flag.
* Misc fixes.
## 6.2.2
* Added support for MC 1.12.
* Changed flower pots to fall under the build flag.
* Fix heal flag not functioning.
* Add option to allow Forge clients with host-keys setting.
* Add mobs.block-armor-stand-destroy config.
* Add firework-damage flag.
* Add config option to ignore hopper checks.
* Misc fixes.
## 6.2
* Added support for MC 1.11.
* Add a custom flag and session API (for developers, see https://worldguard.enginehub.org/en/latest/developer/)
* Add a config option to ensure location flags (teleport, spawn) are inside their region.
* Misc fixes.
## 6.1.2
* Added support for new blocks in 1.8, 1.9, and 1.10.
* Added protection from nether portals being created in protected region (enable via config `nether-portal-protection`).
+3 -3
View File
@@ -4,12 +4,12 @@ Thank you for your interest in contributing to WorldGuard! We appreciate your
effort, but to make sure that the inclusion of your patch is a smooth process, we
ask that you make note of the following guidelines.
* **Follow the [Oracle coding conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html).**
* **Follow the [Oracle coding conventions](https://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html).**
We can't stress this enough; if your code has notable issues, it may delay
the process significantly.
* **Target Java 6 for source and compilation.** Make sure to mark methods with
* **Target Java 8 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
methods of interfaces.
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
+16
View File
@@ -0,0 +1,16 @@
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/>.
+200 -200
View File
@@ -1,201 +1,201 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
----------------------------------------------------------------------------
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.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
----------------------------------------------------------------------------
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.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
+47 -46
View File
@@ -1,46 +1,47 @@
# ![WorldGuard](http://static.sk89q.com/readme/worldguard-new.png)
WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
* 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 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
[Gradle](http://gradle.org). Detailed compilation information
[can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
Dependencies are automatically handled by Gradle.
Contributing
------------
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://builds.enginehub.org)
* [End-user documentation](http://wiki.sk89q.com/wiki/WorldGuard)
<h1>
<img src="worldguard-logo.svg" alt="WorldGuard" width="400" />
</h1>
WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
* 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 Lesser
General Public License v3.
A Bukkit server implementation (such as [Paper](https://papermc.io)) and the [WorldEdit plugin](https://dev.bukkit.org/projects/worldedit) are required to use WorldGuard. You can get a release copy of WorldGuard from the [BukkitDev site](https://dev.bukkit.org/projects/worldguard).
Compiling
---------
The project is written for Java 8 and our build process makes use of
[Gradle](http://gradle.org).
Dependencies are automatically handled by Gradle.
Contributing
------------
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)
* [Discord](https://discord.gg/enginehub)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](http://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [End-user documentation](https://worldguard.enginehub.org/en/latest/)
-131
View File
@@ -1,131 +0,0 @@
println """
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Read COMPILING.md if you haven't yet
2) Try running 'build' in a separate Gradle run
3) Use gradlew and not gradle
4) If you still need help, ask on IRC! irc.esper.net #sk89q
Output files will be in [subproject]/build/libs
*******************************************
"""
buildscript {
repositories {
mavenCentral()
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" }
jcenter()
}
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:17.0'
}
}
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.1'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1'
classpath 'org.ajoberstar:gradle-git:0.12.0'
}
}
if (!project.hasProperty("artifactory_contextUrl")) ext.artifactory_contextUrl = "http://localhost"
if (!project.hasProperty("artifactory_user")) ext.artifactory_user = "guest"
if (!project.hasProperty("artifactory_password")) ext.artifactory_password = ""
if (!project.hasProperty("gitCommitHash")) {
try {
def repo = org.ajoberstar.grgit.Grgit.open(project.file('.'))
ext.gitCommitHash = repo.head().abbreviatedId
} catch (Exception e) {
ext.gitCommitHash = "no_git_id"
}
}
subprojects {
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'checkstyle'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'com.jfrog.artifactory-upload'
group = 'com.sk89q.worldguard'
version = '7.0.0-SNAPSHOT'
ext.internalVersion = version + ";" + gitCommitHash
sourceCompatibility = 1.8
targetCompatibility = 1.8
checkstyle.configFile = new File(rootProject.projectDir, "config/checkstyle/checkstyle.xml")
repositories {
mavenCentral()
maven { url "http://repo.spongepowered.org/maven/" }
maven { url "https://hub.spigotmc.org/nexus/content/groups/public" }
maven { url "http://maven.sk89q.com/repo/" }
maven { url "http://repo.maven.apache.org/maven2" }
}
if (JavaVersion.current().isJava8Compatible()) {
// Java 8 turns on doclint which we fail
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives jar
archives sourcesJar
archives javadocJar
}
build.dependsOn(checkstyleMain)
build.dependsOn(checkstyleTest)
build.dependsOn(sourcesJar)
build.dependsOn(javadocJar)
shadowJar {
classifier 'dist'
dependencies {
include(dependency('org.khelekore:prtree:1.5.0'))
}
exclude 'GradleStart**'
exclude '.cache'
exclude 'LICENSE*'
}
artifactory {
contextUrl = "${artifactory_contextUrl}"
publish {
repository {
repoKey = project.version.contains("SNAPSHOT") ? 'libs-snapshot-local' : 'libs-release-local'
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
resolve {
repository {
repoKey = 'repo'
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
}
}
+26
View File
@@ -0,0 +1,26 @@
import org.ajoberstar.grgit.Grgit
logger.lifecycle("""
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Try running 'build' in a separate Gradle run
2) Use gradlew and not gradle
3) If you still need help, ask on Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
applyRootArtifactoryConfig()
if (!project.hasProperty("gitCommitHash")) {
apply(plugin = "org.ajoberstar.grgit")
ext["gitCommitHash"] = try {
(ext["grgit"] as Grgit?)?.head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no.git.id"
}
}
+19
View File
@@ -0,0 +1,19 @@
plugins {
`kotlin-dsl`
kotlin("jvm") version embeddedKotlinVersion
}
repositories {
jcenter()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation("gradle.plugin.net.minecrell:licenser:0.4.1")
implementation("org.ajoberstar.grgit:grgit-gradle:3.1.1")
implementation("com.github.jengelman.gradle.plugins:shadow:5.1.0")
implementation("net.ltgt.apt-eclipse:net.ltgt.apt-eclipse.gradle.plugin:0.21")
implementation("net.ltgt.apt-idea:net.ltgt.apt-idea.gradle.plugin:0.21")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7")
}
@@ -0,0 +1,40 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.named
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
private const val ARTIFACTORY_USER = "artifactory_user"
private const val ARTIFACTORY_PASSWORD = "artifactory_password"
fun Project.applyRootArtifactoryConfig() {
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
apply(plugin = "com.jfrog.artifactory")
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
isSkip = true
}
}
fun Project.applyCommonArtifactoryConfig() {
tasks.named<ArtifactoryTask>("artifactoryPublish") {
publishConfigs("archives")
}
}
+18
View File
@@ -0,0 +1,18 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.repositories
fun Project.applyCommonConfiguration() {
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(5, "MINUTES")
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.sourceSets: SourceSetContainer
get() = the<JavaPluginConvention>().sourceSets
+96
View File
@@ -0,0 +1,96 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.internal.HasConvention
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
import org.gradle.api.tasks.Upload
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getPlugin
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.register
fun Project.applyLibrariesConfiguration() {
applyCommonConfiguration()
apply(plugin = "java-base")
apply(plugin = "maven")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
configurations {
create("shade")
getByName("archives").extendsFrom(getByName("default"))
}
group = "${rootProject.group}.worldguard-libs"
tasks.register<ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
dependencies {
exclude(dependency("com.google.code.findbugs:jsr305:1.3.9"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
val filePattern = Regex("(.*)com/sk89q/squirrelid((?:/|$).*)")
val textPattern = Regex("com\\.sk89q\\.squirrelid")
eachFile {
filter {
it.replaceFirst(textPattern, "com.sk89q.worldguard.util.profile")
}
path = path.replaceFirst(filePattern, "$1com/sk89q/worldguard/util/profile$2")
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
artifacts {
val jar = tasks.named("jar")
add("default", jar) {
builtBy(jar)
}
val sourcesJar = tasks.named("sourcesJar")
add("archives", sourcesJar) {
builtBy(sourcesJar)
}
}
tasks.register<Upload>("install") {
configuration = configurations["archives"]
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.version = project.version.toString()
pom.artifactId = project.name
}
}
applyCommonArtifactoryConfig()
}
+119
View File
@@ -0,0 +1,119 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import net.minecrell.gradle.licenser.LicenseExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.CoreJavadocOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getByName
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
fun Project.applyPlatformAndCoreConfiguration() {
applyCommonConfiguration()
apply(plugin = "java")
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "maven")
apply(plugin = "checkstyle")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
apply(plugin = "net.minecrell.licenser")
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "7.6.1"
}
tasks.withType<Test>().configureEach {
useJUnit()
}
dependencies {
"testCompile"("junit:junit:${Versions.JUNIT}")
// TODO switch to jupiter - doesn't support abstract test classes so tests need rewriting
//"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
//"testRuntime"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
(options as CoreJavadocOptions).addStringOption("Xdoclint:none", "-quiet")
}
tasks.register<Jar>("javadocJar") {
dependsOn("javadoc")
archiveClassifier.set("javadoc")
from(tasks.getByName<Javadoc>("javadoc").destinationDir)
}
tasks.named("assemble").configure {
dependsOn("javadocJar")
}
artifacts {
add("archives", tasks.named("jar"))
add("archives", tasks.named("javadocJar"))
}
if (name == "worldguard-core" || name == "worldguard-bukkit") {
tasks.register<Jar>("sourcesJar") {
dependsOn("classes")
archiveClassifier.set("sources")
from(sourceSets["main"].allSource)
}
artifacts {
add("archives", tasks.named("sourcesJar"))
}
tasks.named("assemble").configure {
dependsOn("sourcesJar")
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
applyCommonArtifactoryConfig()
configure<LicenseExtension> {
header = rootProject.file("HEADER.txt")
include("**/*.java")
}
}
fun Project.applyShadowConfiguration() {
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
//include(project(":worldguard-libs:${project.name.replace("worldguard-", "")}"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core:3.0"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
}
}
+8
View File
@@ -0,0 +1,8 @@
object Versions {
// const val PISTON = "0.4.3"
// const val AUTO_VALUE = "1.6.5"
const val WORLDEDIT = "7.2.0-SNAPSHOT"
const val JUNIT = "4.11"
const val SQUIRRELID = "0.2.0"
const val GUAVA = "21.0"
}
+10 -11
View File
@@ -1,22 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- Tabs are strictly banned -->
<module name="FileTabCharacter"/>
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/suppressions.xml"/>
</module>
<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.
Control package usage, so people don't insert Bukkit into WG where it shouldn't belong, etc.
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="config/checkstyle/import-control.xml"/>
<property name="file" value="${config_loc}/import-control.xml"/>
</module>
<!-- Code -->
@@ -27,7 +33,6 @@
<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 -->
@@ -55,10 +60,4 @@
<!-- <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="config/checkstyle/header.txt"/>
<property name="fileExtensions" value="java"/>
</module>
</module>
-18
View File
@@ -1,18 +0,0 @@
/*
* 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/>.
*/
+14 -10
View File
@@ -8,27 +8,31 @@
<allow pkg="org.junit"/>
<allow pkg="org.hamcrest"/>
<allow pkg="org.mockito"/>
<allow pkg="junit.framework"/>
<allow pkg="com.sk89q"/>
<allow pkg="com.google.common"/>
<subpackage name="worldguard">
<allow pkg="org.khelekore"/>
<allow pkg="org.flywaydb"/>
<allow pkg="org.yaml"/>
<allow pkg="org.enginehub.piston"/>
<subpackage name="util.profile.resolver">
<allow pkg="org.bukkit"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
</subpackage>
<subpackage name="bukkit">
<allow pkg="org.bukkit"/>
<allow pkg="net.minecraft.server"/>
<allow pkg="org.bstats.bukkit"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
<allow pkg="co.aikar.timings.lib" />
<allow pkg="org.spigotmc" />
</subpackage>
<subpackage name="sponge">
<allow pkg="org.spongepowered"/>
<allow pkg="com.flowpowered"/>
</subpackage>
<subpackage name="forge">
<allow pkg="net.minecraft"/>
<allow pkg="net.minecraftforge"/>
</subpackage>
</subpackage>
</import-control>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="ProtectedRegion.java" checks="EqualsHashCode"/>
</suppressions>
+2
View File
@@ -0,0 +1,2 @@
group=com.sk89q.worldguard
version=7.0.5
Binary file not shown.
+1 -2
View File
@@ -1,6 +1,5 @@
#Fri Nov 13 12:12:21 EST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip
Vendored Regular → Executable
+75 -51
View File
@@ -1,4 +1,20 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
@@ -6,47 +22,6 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -61,9 +36,49 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -90,7 +105,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@@ -114,6 +129,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
@@ -154,11 +170,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
Vendored
+20 -10
View File
@@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@@ -8,14 +24,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@@ -46,10 +62,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@@ -60,11 +75,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
-3
View File
@@ -1,3 +0,0 @@
rootProject.name = 'worldguard'
include 'worldguard-core', 'worldguard-sponge', 'worldguard-legacy'
+7
View File
@@ -0,0 +1,7 @@
rootProject.name = "worldguard"
include("worldguard-libs")
include("worldguard-libs:core")
include("worldguard-core")
//include("worldguard-libs:bukkit")
include("worldguard-bukkit")
+93
View File
@@ -0,0 +1,93 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.internal.HasConvention
plugins {
id("java-library")
id("net.ltgt.apt-eclipse")
id("net.ltgt.apt-idea")
}
applyPlatformAndCoreConfiguration()
applyShadowConfiguration()
repositories {
maven {
name = "paper"
url = uri("https://papermc.io/repo/repository/maven-public/")
}
maven {
name = "bstats"
url = uri("https://repo.codemc.org/repository/maven-public")
}
maven {
name = "aikar-timings"
url = uri("http://repo.aikar.co/nexus/content/groups/aikar/")
}
}
configurations {
compileClasspath.extendsFrom(create("shade"))
}
dependencies {
"compile"(project(":worldguard-core"))
//"compile"(project(":worldguard-libs:bukkit"))
"api"("com.destroystokyo.paper:paper-api:1.16.2-R0.1-SNAPSHOT")
"shade"("io.papermc:paperlib:1.0.4")
"api"("com.sk89q.worldedit:worldedit-bukkit:${Versions.WORLDEDIT}") { isTransitive = false }
"implementation"("com.google.guava:guava:${Versions.GUAVA}")
"implementation"("com.sk89q:commandbook:2.3") { isTransitive = false }
"shade"("org.bstats:bstats-bukkit:1.7")
"shade"("co.aikar:minecraft-timings:1.0.4")
}
tasks.named<Upload>("install") {
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.whenConfigured {
dependencies.firstOrNull { dep ->
dep!!.withGroovyBuilder {
getProperty("groupId") == "com.destroystokyo.paper" && getProperty("artifactId") == "paper-api"
}
}?.withGroovyBuilder {
setProperty("groupId", "org.spigotmc")
setProperty("artifactId", "spigot-api")
}
}
}
}
tasks.named<Copy>("processResources") {
val internalVersion = project.ext["internalVersion"]
inputs.property("internalVersion", internalVersion)
filesMatching("plugin.yml") {
expand("internalVersion" to internalVersion)
}
}
tasks.named<Jar>("jar") {
val projectVersion = project.version
inputs.property("projectVersion", projectVersion)
manifest {
attributes("Implementation-Version" to projectVersion)
}
}
tasks.named<ShadowJar>("shadowJar") {
configurations = listOf(project.configurations["shade"], project.configurations["runtimeClasspath"])
dependencies {
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats") {
include(dependency("org.bstats:bstats-bukkit"))
}
relocate ("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib") {
include(dependency("io.papermc:paperlib"))
}
relocate ("co.aikar.timings.lib", "com.sk89q.worldguard.bukkit.timingslib") {
include(dependency("co.aikar:minecraft-timings"))
}
}
}
tasks.named("assemble").configure {
dependsOn("shadowJar")
}
@@ -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.bukkit;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.config.YamlConfigurationManager;
import com.sk89q.worldedit.util.report.Unreported;
import java.io.File;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class BukkitConfigurationManager extends YamlConfigurationManager {
@Unreported private WorldGuardPlugin plugin;
@Unreported private ConcurrentMap<String, BukkitWorldConfiguration> worlds = new ConcurrentHashMap<>();
private boolean hasCommandBookGodMode;
boolean extraStats;
boolean timedSessionHandlers;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public BukkitConfigurationManager(WorldGuardPlugin plugin) {
super();
this.plugin = plugin;
}
public Collection<BukkitWorldConfiguration> getWorldConfigs() {
return worlds.values();
}
@Override
public void load() {
super.load();
this.extraStats = getConfig().getBoolean("custom-metrics-charts", true);
this.timedSessionHandlers = getConfig().getBoolean("extra-timings.session-handlers", true);
}
@Override
public File getDataFolder() {
return plugin.getDataFolder();
}
@Override
public void copyDefaults() {
// Create the default configuration file
plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "config.yml"), "config.yml");
}
@Override
public void unload() {
worlds.clear();
}
@Override
public void postLoad() {
// Load configurations for each world
for (World world : WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds()) {
get(world);
}
getConfig().save();
}
/**
* Get the configuration for a world.
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
@Override
public BukkitWorldConfiguration get(World world) {
String worldName = world.getName();
BukkitWorldConfiguration config = worlds.get(worldName);
BukkitWorldConfiguration newConfig = null;
while (config == null) {
if (newConfig == null) {
newConfig = new BukkitWorldConfiguration(plugin, worldName, this.getConfig());
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
}
public void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
hasCommandBookGodMode = true;
return;
}
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -17,12 +17,24 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
package com.sk89q.worldguard.bukkit;
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 com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.paste.ActorCallbackPaste;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.event.debug.CancelLogging;
import com.sk89q.worldguard.bukkit.event.debug.LoggingBlockBreakEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingBlockPlaceEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingEntityDamageByEntityEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingPlayerInteractEvent;
import com.sk89q.worldguard.bukkit.util.report.CancelReport;
import com.sk89q.worldguard.internal.platform.DebugHandler;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@@ -34,68 +46,22 @@ 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.event.entity.EntityDamageEvent;
import org.bukkit.util.BlockIterator;
import java.util.logging.Logger;
public class DebuggingCommands {
public class BukkitDebugHandler implements DebugHandler {
private static final Logger log = Logger.getLogger(DebuggingCommands.class.getCanonicalName());
private static final Logger log = Logger.getLogger(BukkitDebugHandler.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) {
BukkitDebugHandler(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.
*
@@ -105,7 +71,8 @@ public class DebuggingCommands {
* @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 {
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)) {
@@ -128,7 +95,8 @@ public class DebuggingCommands {
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");
ActorCallbackPaste.pastebin(WorldGuard.getInstance().getSupervisor(), plugin.wrapCommandSender(receiver),
result, "Event debugging report: %s.txt");
} else {
receiver.sendMessage(result.replaceAll("(?m)^", ChatColor.AQUA.toString()));
@@ -217,4 +185,46 @@ public class DebuggingCommands {
throw new CommandException("Not currently looking at an entity that is close enough.");
}
@Override
public void testBreak(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK BREAK at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingBlockBreakEvent event = new LoggingBlockBreakEvent(block, bukkitTarget);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testPlace(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK PLACE at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingBlockPlaceEvent event = new LoggingBlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), bukkitTarget.getItemInHand(), bukkitTarget, true);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testInteract(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK INTERACT at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingPlayerInteractEvent event = new LoggingPlayerInteractEvent(bukkitTarget, Action.RIGHT_CLICK_BLOCK, bukkitTarget.getItemInHand(), block, BlockFace.SOUTH);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testDamage(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Entity entity = traceEntity(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing ENTITY DAMAGE at ", TextColor.AQUA).append(TextComponent.of(entity.toString(), TextColor.DARK_AQUA)));
LoggingEntityDamageByEntityEvent event = new LoggingEntityDamageByEntityEvent(bukkitTarget, entity, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
}
@@ -0,0 +1,241 @@
/*
* 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.blocks.BaseItemStack;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.session.SessionKey;
import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.weather.WeatherType;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
import javax.annotation.Nullable;
class BukkitOfflinePlayer extends BukkitPlayer {
private final OfflinePlayer player;
BukkitOfflinePlayer(WorldGuardPlugin plugin, OfflinePlayer offlinePlayer) {
super(plugin, offlinePlayer.getPlayer()); // null if they are offline
this.player = offlinePlayer;
}
/// ========================================
/// These are checked for RegionAssociable
/// (to see if a player belongs to a region)
/// ========================================
@Override
public String getName() {
return player.getName();
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(player, group);
}
@Override
public String[] getGroups() {
return plugin.getGroups(player);
}
/// ==========================================
/// None of the following should ever be used.
/// ==========================================
@Override
public boolean hasPermission(String perm) {
throw new UnsupportedOperationException();
}
@Override
public void kick(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void ban(String msg) {
throw new UnsupportedOperationException();
}
@Override
public double getHealth() {
throw new UnsupportedOperationException();
}
@Override
public void setHealth(double health) {
throw new UnsupportedOperationException();
}
@Override
public double getMaxHealth() {
throw new UnsupportedOperationException();
}
@Override
public double getFoodLevel() {
throw new UnsupportedOperationException();
}
@Override
public void setFoodLevel(double foodLevel) {
throw new UnsupportedOperationException();
}
@Override
public double getSaturation() {
throw new UnsupportedOperationException();
}
@Override
public void setSaturation(double saturation) {
throw new UnsupportedOperationException();
}
@Override
public float getExhaustion() {
throw new UnsupportedOperationException();
}
@Override
public void setExhaustion(float exhaustion) {
throw new UnsupportedOperationException();
}
@Override
public WeatherType getPlayerWeather() {
throw new UnsupportedOperationException();
}
@Override
public void setPlayerWeather(WeatherType weather) {
throw new UnsupportedOperationException();
}
@Override
public void resetPlayerWeather() {
throw new UnsupportedOperationException();
}
@Override
public boolean isPlayerTimeRelative() {
throw new UnsupportedOperationException();
}
@Override
public long getPlayerTimeOffset() {
throw new UnsupportedOperationException();
}
@Override
public void setPlayerTime(long time, boolean relative) {
throw new UnsupportedOperationException();
}
@Override
public void resetPlayerTime() {
throw new UnsupportedOperationException();
}
@Override
public void printRaw(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void printDebug(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void print(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void printError(String msg) {
throw new UnsupportedOperationException();
}
@Override
public World getWorld() {
throw new UnsupportedOperationException();
}
@Override
public BaseItemStack getItemInHand(HandSide handSide) {
throw new UnsupportedOperationException();
}
@Override
public void giveItem(BaseItemStack itemStack) {
throw new UnsupportedOperationException();
}
@Override
public BlockBag getInventoryBlockBag() {
throw new UnsupportedOperationException();
}
@Override
public void setPosition(Vector3 pos, float pitch, float yaw) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public BaseEntity getState() {
throw new UnsupportedOperationException();
}
@Override
public Location getLocation() {
throw new UnsupportedOperationException();
}
@Override
public void setCompassTarget(Location location) {
throw new UnsupportedOperationException();
}
@Override
public SessionKey getSessionKey() {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public <T> T getFacet(Class<? extends T> cls) {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,221 @@
/*
* 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.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.util.MessagingUtil;
import io.papermc.lib.PaperLib;
import org.bukkit.BanList.Type;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class BukkitPlayer extends com.sk89q.worldedit.bukkit.BukkitPlayer implements LocalPlayer {
protected final WorldGuardPlugin plugin;
private final boolean silenced;
private String name;
public BukkitPlayer(WorldGuardPlugin plugin, Player player) {
this(plugin, player, false);
}
BukkitPlayer(WorldGuardPlugin plugin, Player player, boolean silenced) {
super(player);
this.plugin = plugin;
this.silenced = silenced;
}
@Override
public String getName() {
if (this.name == null) {
// getName() takes longer than before in newer versions of Minecraft
this.name = getPlayer().getName();
}
return name;
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(getPlayer(), group);
}
@Override
public void kick(String msg) {
if (!silenced) {
getPlayer().kickPlayer(msg);
}
}
@Override
public void ban(String msg) {
if (!silenced) {
Bukkit.getBanList(Type.NAME).addBan(getName(), null, null, null);
getPlayer().kickPlayer(msg);
}
}
@Override
public double getHealth() {
return getPlayer().getHealth();
}
@Override
public void setHealth(double health) {
getPlayer().setHealth(health);
}
@Override
public double getMaxHealth() {
return getPlayer().getMaxHealth();
}
@Override
public double getFoodLevel() {
return getPlayer().getFoodLevel();
}
@Override
public void setFoodLevel(double foodLevel) {
getPlayer().setFoodLevel((int) foodLevel);
}
@Override
public double getSaturation() {
return getPlayer().getSaturation();
}
@Override
public void setSaturation(double saturation) {
getPlayer().setSaturation((float) saturation);
}
@Override
public float getExhaustion() {
return getPlayer().getExhaustion();
}
@Override
public void setExhaustion(float exhaustion) {
getPlayer().setExhaustion(exhaustion);
}
@Override
public WeatherType getPlayerWeather() {
org.bukkit.WeatherType playerWeather = getPlayer().getPlayerWeather();
return playerWeather == null ? null : playerWeather == org.bukkit.WeatherType.CLEAR ? WeatherTypes.CLEAR : WeatherTypes.RAIN;
}
@Override
public void setPlayerWeather(WeatherType weather) {
getPlayer().setPlayerWeather(weather == WeatherTypes.CLEAR ? org.bukkit.WeatherType.CLEAR : org.bukkit.WeatherType.DOWNFALL);
}
@Override
public void resetPlayerWeather() {
getPlayer().resetPlayerWeather();
}
@Override
public boolean isPlayerTimeRelative() {
return getPlayer().isPlayerTimeRelative();
}
@Override
public long getPlayerTimeOffset() {
return getPlayer().getPlayerTimeOffset();
}
@Override
public void setPlayerTime(long time, boolean relative) {
getPlayer().setPlayerTime(time, relative);
}
@Override
public void resetPlayerTime() {
getPlayer().resetPlayerTime();
}
@Override
public int getFireTicks() {
return getPlayer().getFireTicks();
}
@Override
public void setFireTicks(int fireTicks) {
getPlayer().setFireTicks(fireTicks);
}
@Override
public void setCompassTarget(Location location) {
getPlayer().setCompassTarget(BukkitAdapter.adapt(location));
}
@Override
public void sendTitle(String title, String subtitle) {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(getWorld()).forceDefaultTitleTimes) {
getPlayer().sendTitle(title, subtitle, 10, 70, 20);
} else {
getPlayer().sendTitle(title, subtitle, -1, -1, -1);
}
}
@Override
public void resetFallDistance() {
getPlayer().setFallDistance(0);
}
@Override
public void teleport(Location location, String successMessage, String failMessage) {
PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location))
.thenApply(success -> {
if (success) {
// The success message can be cleared via flag
if (!successMessage.isEmpty()) {
MessagingUtil.sendStringToChat(this, successMessage);
}
} else {
printError(failMessage);
}
return success;
});
}
@Override
public String[] getGroups() {
return plugin.getGroups(getPlayer());
}
@Override
public void printRaw(String msg) {
if (!silenced) {
super.printRaw(msg);
}
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(getPlayer(), perm);
}
}
@@ -0,0 +1,132 @@
/*
* 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 static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
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 java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class BukkitRegionContainer extends RegionContainer {
/**
* Invalidation frequency in ticks.
*/
private static final int CACHE_INVALIDATION_INTERVAL = 2;
private final WorldGuardPlugin plugin;
/**
* Create a new instance.
*
* @param plugin the plugin
*/
public BukkitRegionContainer(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Override
public void initialize() {
super.initialize();
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
load(BukkitAdapter.adapt(event.getWorld()));
}
@EventHandler
public void onWorldUnload(WorldUnloadEvent event) {
unload(BukkitAdapter.adapt(event.getWorld()));
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
RegionManager manager = get(BukkitAdapter.adapt(event.getWorld()));
if (manager != null) {
Chunk chunk = event.getChunk();
manager.loadChunk(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
RegionManager manager = get(BukkitAdapter.adapt(event.getWorld()));
if (manager != null) {
Chunk chunk = event.getChunk();
manager.unloadChunk(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
}
}, plugin);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, cache::invalidateAll, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
}
public void shutdown() {
container.shutdown();
}
@Override
@Nullable
protected RegionManager load(World world) {
checkNotNull(world);
WorldConfiguration config = WorldGuard.getInstance().getPlatform().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<BlockVector2> positions = new ArrayList<>();
for (Chunk chunk : ((BukkitWorld) world).getWorld().getLoadedChunks()) {
positions.add(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
manager.loadChunks(positions);
}
}
return manager;
}
}
@@ -0,0 +1,246 @@
/*
* 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.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.internal.platform.StringMatcher;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class BukkitStringMatcher implements StringMatcher {
@Override
public World matchWorld(Actor sender, String filter) throws CommandException {
List<? extends World> worlds = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds();
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.NORMAL) {
return world;
}
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.NETHER) {
return world;
}
}
throw new CommandException("No nether world found.");
// #end for the first nether world
} else if (filter.equalsIgnoreCase("#end")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.THE_END) {
return world;
}
}
throw new CommandException("No end world found.");
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String[] parts = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
@Override
public List<LocalPlayer> matchPlayerNames(String filter) {
List<LocalPlayer> wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(Collectors.toList());
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (LocalPlayer player : wgPlayers) {
if (player.getName().equalsIgnoreCase(filter)) {
List<LocalPlayer> list = new ArrayList<>();
list.add(player);
return list;
}
}
return new ArrayList<>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<LocalPlayer> list = new ArrayList<>();
for (LocalPlayer player : wgPlayers) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<LocalPlayer> list = new ArrayList<>();
for (LocalPlayer player : wgPlayers) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
@Override
public Iterable<? extends LocalPlayer> matchPlayers(Actor source, String filter) throws CommandException {
if (Bukkit.getServer().getOnlinePlayers().isEmpty()) {
throw new CommandException("No players matched query.");
}
List<LocalPlayer> wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(Collectors.toList());
if (filter.equals("*")) {
return checkPlayerMatch(wgPlayers);
}
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// Handle #world, which matches player of the same world as the
// calling source
if (filter.equalsIgnoreCase("#world")) {
List<LocalPlayer> players = new ArrayList<>();
LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (LocalPlayer player : wgPlayers) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
}
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<LocalPlayer> players = new ArrayList<>();
LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
Vector3 sourceVector = sourcePlayer.getLocation().toVector();
for (LocalPlayer player : wgPlayers) {
if (player.getWorld().equals(sourceWorld) && player.getLocation().toVector().distanceSq(sourceVector) < 900) {
players.add(player);
}
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<LocalPlayer> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
@Override
public Actor matchPlayerOrConsole(Actor sender, String filter) throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return WorldGuardPlugin.inst().wrapCommandSender(Bukkit.getServer().getConsoleSender());
}
return matchSinglePlayer(sender, filter);
}
@Override
public World getWorldByName(String worldName) {
final org.bukkit.World bukkitW = Bukkit.getServer().getWorld(worldName);
if (bukkitW == null) {
return null;
}
return BukkitAdapter.adapt(bukkitW);
}
@Override
public String replaceMacros(Actor sender, String message) {
Collection<? extends Player> online = Bukkit.getServer().getOnlinePlayers();
message = message.replace("%name%", sender.getName());
message = message.replace("%id%", sender.getUniqueId().toString());
message = message.replace("%online%", String.valueOf(online.size()));
if (sender instanceof LocalPlayer) {
LocalPlayer player = (LocalPlayer) sender;
World world = (World) player.getExtent();
message = message.replace("%world%", world.getName());
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}
}
@@ -0,0 +1,113 @@
/*
* 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 static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.blacklist.target.BlockTarget;
import com.sk89q.worldguard.blacklist.target.ItemTarget;
import com.sk89q.worldguard.blacklist.target.Target;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
public class BukkitUtil {
private BukkitUtil() {
}
/**
* Checks if the given potion is a vial of water.
*
* @param item the item to check
* @return true if it's a water vial
*/
public static boolean isWaterPotion(ItemStack item) {
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;
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @param effectiveMaterial The effective material, if different
* @return a target
*/
public static Target createTarget(Block block, Material effectiveMaterial) {
checkNotNull(block);
checkNotNull(block.getType());
if (block.getType() == effectiveMaterial) {
return createTarget(block.getType());
} else {
return createTarget(effectiveMaterial);
}
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @return a target
*/
public static Target createTarget(Block block) {
checkNotNull(block);
checkNotNull(block.getType());
return createTarget(block.getType());
}
/**
* Get a blacklist target for the given item.
*
* @param item the item
* @return a target
*/
public static Target createTarget(ItemStack item) {
checkNotNull(item);
checkNotNull(item.getType());
return createTarget(item.getType()); // Delegate it, ItemStacks can contain both Blocks and Items in Spigot
}
/**
* Get a blacklist target for the given material.
*
* @param material the material
* @return a target
*/
public static Target createTarget(Material material) {
checkNotNull(material);
if (material.isBlock()) {
return new BlockTarget(BukkitAdapter.asBlockType(material));
} else {
return new ItemTarget(BukkitAdapter.asItemType(material));
}
}
}
@@ -21,6 +21,12 @@ package com.sk89q.worldguard.bukkit;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.report.Unreported;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.item.ItemTypes;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLoggerHandler;
import com.sk89q.worldguard.blacklist.logger.ConsoleHandler;
@@ -28,24 +34,23 @@ 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.chest.BukkitSignChestProtection;
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 com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.config.YamlWorldConfiguration;
import org.bukkit.potion.PotionEffectType;
import org.yaml.snakeyaml.parser.ParserException;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Holds the configuration for individual worlds.
@@ -53,154 +58,33 @@ import java.util.logging.Logger;
* @author sk89q
* @author Michael
*/
public class WorldConfiguration {
public class BukkitWorldConfiguration extends YamlWorldConfiguration {
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" +
"# This is a world configuration file. Anything placed into here will only\r\n" +
"# affect this world. If you don't put anything in this file, then the\r\n" +
"# settings will be inherited from the main configuration file.\r\n" +
"#\r\n" +
"# If you see {} below, that means that there are NO entries in this file.\r\n" +
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
@Unreported private WorldGuardPlugin plugin;
@Unreported private String worldName;
@Unreported private YAMLProcessor parentConfig;
@Unreported private YAMLProcessor config;
private File blacklistFile;
@Unreported private Blacklist blacklist;
@Unreported private ChestProtection chestProtection = new SignChestProtection();
@Unreported private ChestProtection chestProtection = new BukkitSignChestProtection();
/* Configuration data start */
public boolean summaryOnStart;
public boolean opPermissions;
public boolean buildPermissions;
public String buildPermissionDenyMessage = "";
public boolean fireSpreadDisableToggle;
public boolean itemDurability;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
public Set<PotionEffectType> blockPotions;
public boolean blockPotionsAlways;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean ropeLadders;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockLighter;
public boolean disableFireSpread;
public Set<Integer> disableFireSpreadBlocks;
public boolean preventLavaFire;
public Set<Integer> allowedLavaSpreadOver;
public boolean blockTNTExplosions;
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public boolean blockWitherExplosions;
public boolean blockWitherBlockDamage;
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;
public boolean disableFireDamage;
public boolean disableLightningDamage;
public boolean disableDrowningDamage;
public boolean disableSuffocationDamage;
public boolean teleportOnSuffocation;
public boolean disableVoidDamage;
public boolean teleportOnVoid;
public boolean disableExplosionDamage;
public boolean disableMobDamage;
public boolean useRegions;
public boolean highFreqFlags;
public boolean checkLiquidFlow;
public int regionWand;
public Set<EntityType> blockCreatureSpawn;
public boolean allowTamedSpawns;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
public int maxClaimVolume;
public boolean claimOnlyInsideExistingRegions;
public int maxRegionCountPerPlayer;
public boolean boundedLocationFlags;
public boolean antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
public boolean preventLightningFire;
public Set<Integer> disallowedLightningBlocks;
public boolean disableThunder;
public boolean disableWeather;
public boolean alwaysRaining;
public boolean alwaysThundering;
public boolean disablePigZap;
public boolean disableCreeperPower;
public boolean disableHealthRegain;
public boolean disableMushroomSpread;
public boolean disableIceMelting;
public boolean disableSnowMelting;
public boolean disableSnowFormation;
public boolean disableIceFormation;
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableMyceliumSpread;
public boolean disableVineGrowth;
public boolean disableEndermanGriefing;
public boolean disableSnowmanTrails;
public boolean disableSoilDehydration;
public Set<Integer> allowedSnowFallOver;
public boolean regionInvinciblityRemovesMobs;
public boolean regionNetherPortalProtection;
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;
public boolean usePaperEntityOrigin;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin The WorldGuardPlugin instance
* @param worldName The world name that this WorldConfiguration is for.
* @param worldName The world name that this BukkitWorldConfiguration is for.
* @param parentConfig The parent configuration to read defaults from
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
public BukkitWorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
File configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
this.plugin = plugin;
this.worldName = worldName;
this.parentConfig = parentConfig;
@@ -215,67 +99,19 @@ public class WorldConfiguration {
}
}
private boolean getBoolean(String node, boolean def) {
boolean val = parentConfig.getBoolean(node, def);
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return val;
}
}
private String getString(String node, String def) {
String val = parentConfig.getString(node, def);
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return val;
}
}
private int getInt(String node, int def) {
int val = parentConfig.getInt(node, def);
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return val;
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return val;
}
}
private List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res = parentConfig.getIntList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
}
return res;
}
private TargetMatcherSet getTargetMatchers(String node) {
TargetMatcherSet set = new TargetMatcherSet();
List<String> inputs = parentConfig.getStringList(node, null);
if (inputs == null || inputs.size() == 0) {
if (inputs == null || inputs.isEmpty()) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
inputs = config.getStringList(node, null);
}
if (inputs == null || inputs.isEmpty()) {
return set;
}
@@ -290,53 +126,16 @@ public class WorldConfiguration {
return set;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res = parentConfig.getStringList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
}
return res;
}
private List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
private Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
@Override
public void loadConfiguration() {
try {
config.load();
} catch (IOException e) {
log.severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
} catch (ParserException e) {
log.log(Level.SEVERE, "Error reading configuration for world " + worldName + ": ", e);
} catch (YAMLException e) {
log.severe("Error parsing configuration for world " + worldName + ". ");
throw e;
}
@@ -351,13 +150,19 @@ public class WorldConfiguration {
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");
ignoreHopperMoveEvents = getBoolean("event-handling.ignore-hopper-item-move-events", false);
breakDeniedHoppers = getBoolean("event-handling.break-hoppers-on-denied-move", true);
usePaperEntityOrigin = getBoolean("regions.use-paper-entity-origin", false);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
blockPotions = new HashSet<PotionEffectType>();
useMaxPriorityAssociation = getBoolean("protection.use-max-priority-association", false);
blockPotions = new HashSet<>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
PotionEffectType effect = PotionEffectType.getByName(potionName);
@@ -368,6 +173,7 @@ public class WorldConfiguration {
}
}
blockPotionsAlways = getBoolean("gameplay.block-potions-overly-reliably", false);
disableConduitEffects = getBoolean("gameplay.disable-conduit-effects", false);
simulateSponge = getBoolean("simulation.sponge.enable", false);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
@@ -380,16 +186,16 @@ public class WorldConfiguration {
noPhysicsSand = getBoolean("physics.no-physics-sand", false);
ropeLadders = getBoolean("physics.vine-like-rope-ladders", false);
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
preventWaterDamage = new HashSet<>(convertLegacyBlocks(getStringList("physics.disable-water-damage-blocks", null)));
blockTNTExplosions = getBoolean("ignition.block-tnt", false);
blockTNTBlockDamage = getBoolean("ignition.block-tnt-block-damage", false);
blockLighter = getBoolean("ignition.block-lighter", false);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", true);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", false);
disableFireSpread = getBoolean("fire.disable-all-fire-spread", false);
disableFireSpreadBlocks = new HashSet<Integer>(getIntList("fire.disable-fire-spread-blocks", null));
allowedLavaSpreadOver = new HashSet<Integer>(getIntList("fire.lava-spread-blocks", null));
disableFireSpreadBlocks = new HashSet<>(convertLegacyBlocks(getStringList("fire.disable-fire-spread-blocks", null)));
allowedLavaSpreadOver = new HashSet<>(convertLegacyBlocks(getStringList("fire.lava-spread-blocks", null)));
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
@@ -407,10 +213,12 @@ public class WorldConfiguration {
disableSnowmanTrails = getBoolean("mobs.disable-snowman-trails", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockEntityItemFrameDestroy = getBoolean("mobs.block-item-frame-destroy", false);
blockEntityArmorStandDestroy = getBoolean("mobs.block-armor-stand-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);
blockEntityVehicleEntry = getBoolean("mobs.block-vehicle-entry", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -422,6 +230,7 @@ public class WorldConfiguration {
teleportOnSuffocation = getBoolean("player-damage.teleport-on-suffocation", false);
disableVoidDamage = getBoolean("player-damage.disable-void-damage", false);
teleportOnVoid = getBoolean("player-damage.teleport-on-void-falling", false);
safeFallOnVoid = getBoolean("player-damage.reset-fall-on-void-teleport", false);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
disableDeathMessages = getBoolean("player-damage.disable-death-messages", false);
@@ -432,11 +241,15 @@ public class WorldConfiguration {
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<Integer>(getIntList("weather.prevent-lightning-strike-blocks", null));
disableCreatureTurtleEggTrampling = getBoolean("turtle-egg.disable-creature-trampling", false);
disablePlayerTurtleEggTrampling = getBoolean("turtle-egg.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<>(convertLegacyBlocks(getStringList("weather.prevent-lightning-strike-blocks", null)));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
disableWeather = getBoolean("weather.disable-weather", false);
disablePigZap = getBoolean("weather.disable-pig-zombification", false);
disableVillagerZap = getBoolean("weather.disable-villager-witchification", false);
disableCreeperPower = getBoolean("weather.disable-powered-creepers", false);
alwaysRaining = getBoolean("weather.always-raining", false);
alwaysThundering = getBoolean("weather.always-thundering", false);
@@ -450,29 +263,33 @@ public class WorldConfiguration {
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-growth", false);
disableCropGrowth = getBoolean("dynamics.disable-crop-growth", false);
disableSoilDehydration = getBoolean("dynamics.disable-soil-dehydration", false);
allowedSnowFallOver = new HashSet<Integer>(getIntList("dynamics.snow-fall-blocks", null));
disableCoralBlockFade = getBoolean("dynamics.disable-coral-block-fade", false);
allowedSnowFallOver = new HashSet<>(convertLegacyBlocks(getStringList("dynamics.snow-fall-blocks", null)));
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
regionNetherPortalProtection = getBoolean("regions.nether-portal-protection", false);
regionCancelEmptyChatEvents = getBoolean("regions.cancel-chat-without-recipients", true);
regionNetherPortalProtection = getBoolean("regions.nether-portal-protection", true);
forceDefaultTitleTimes = config.getBoolean("regions.titles-always-use-default-times", true); // note: technically not region-specific, but we only use it for the title flags
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);
regionWand = convertLegacyItem(getString("regions.wand", ItemTypes.LEATHER.getId()));
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
boundedLocationFlags = getBoolean("regions.location-flags-only-inside-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts = new HashMap<>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
if (val != null && val instanceof Number) {
if (val instanceof Number) {
maxRegionCounts.put(key, ((Number) val).intValue());
}
}
@@ -482,14 +299,12 @@ public class WorldConfiguration {
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<EntityType>();
blockCreatureSpawn = new HashSet<>();
for (String creatureName : getStringList("mobs.block-creature-spawn", null)) {
EntityType creature = EntityType.fromName(creatureName);
EntityType creature = EntityTypes.get(creatureName.toLowerCase());
if (creature == null) {
log.warning("Unknown mob type '" + creatureName + "'");
} else if (!creature.isAlive()) {
log.warning("Entity type '" + creatureName + "' is not a creature");
log.warning("Unknown entity type '" + creatureName + "'");
} else {
blockCreatureSpawn.add(creature);
}
@@ -520,7 +335,7 @@ public class WorldConfiguration {
}
// First load the blacklist data from worldguard-blacklist.txt
Blacklist blist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
Blacklist blist = new Blacklist(useBlacklistAsWhitelist);
blist.load(blacklistFile);
// If the blacklist is empty, then set the field to null
@@ -530,7 +345,8 @@ public class WorldConfiguration {
} else {
this.blacklist = blist;
if (summaryOnStart) {
log.log(Level.INFO, "Blacklist loaded.");
log.log(Level.INFO, "({0}) Blacklist loaded with {1} entries.",
new Object[]{worldName, blacklist.getItemCount()});
}
BlacklistLoggerHandler blacklistLogger = blist.getLogger();
@@ -571,7 +387,7 @@ public class WorldConfiguration {
if (disableFireSpread) {
log.log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
if (!disableFireSpreadBlocks.isEmpty()) {
log.log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
@@ -587,47 +403,39 @@ public class WorldConfiguration {
config.save();
}
public Blacklist getBlacklist() {
return this.blacklist;
}
public String getWorldName() {
return this.worldName;
}
public boolean isChestProtected(Block block, Player player) {
public boolean isChestProtected(Location block, LocalPlayer player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
if (player.hasPermission("worldguard.chest-protection.override")
|| player.hasPermission("worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtected(block, player);
}
public boolean isChestProtected(Block block) {
public boolean isChestProtected(Location block) {
return signChestProtection && chestProtection.isProtected(block, null);
}
public boolean isChestProtectedPlacement(Block block, Player player) {
public boolean isChestProtectedPlacement(Location block, LocalPlayer player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
if (player.hasPermission("worldguard.chest-protection.override")
|| player.hasPermission("worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isProtectedPlacement(block, player);
}
public boolean isAdjacentChestProtected(Block block, Player player) {
public boolean isAdjacentChestProtected(Location block, LocalPlayer player) {
if (!signChestProtection) {
return false;
}
if (plugin.hasPermission(player, "worldguard.chest-protection.override")
|| plugin.hasPermission(player, "worldguard.override.chest-protection")) {
if (player.hasPermission("worldguard.chest-protection.override")
|| player.hasPermission("worldguard.override.chest-protection")) {
return false;
}
return chestProtection.isAdjacentChestProtected(block, player);
@@ -637,19 +445,4 @@ public class WorldConfiguration {
return chestProtection;
}
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
if (maxRegionCounts.containsKey(group)) {
int groupMax = maxRegionCounts.get(group);
if (max < groupMax) {
max = groupMax;
}
}
}
if (max <= -1) {
max = maxRegionCountPerPlayer;
}
return max;
}
}
@@ -0,0 +1,280 @@
/*
* 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.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.report.ReportList;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.profile.resolver.PaperProfileService;
import com.sk89q.worldguard.bukkit.protection.events.flags.FlagContextCreateEvent;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.report.PerformanceReport;
import com.sk89q.worldguard.bukkit.util.report.PluginReport;
import com.sk89q.worldguard.bukkit.util.report.SchedulerReport;
import com.sk89q.worldguard.bukkit.util.report.ServerReport;
import com.sk89q.worldguard.bukkit.util.report.ServicesReport;
import com.sk89q.worldguard.bukkit.util.report.WorldReport;
import com.sk89q.worldguard.internal.platform.DebugHandler;
import com.sk89q.worldguard.internal.platform.StringMatcher;
import com.sk89q.worldguard.internal.platform.WorldGuardPlatform;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.session.SessionManager;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import com.sk89q.worldguard.util.profile.resolver.BukkitPlayerService;
import com.sk89q.worldguard.util.profile.resolver.CacheForwardingService;
import com.sk89q.worldguard.util.profile.resolver.CombinedProfileService;
import com.sk89q.worldguard.util.profile.resolver.HttpRepositoryService;
import com.sk89q.worldguard.util.profile.resolver.ProfileService;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permissible;
import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
private BukkitSessionManager sessionManager;
private BukkitConfigurationManager configuration;
private BukkitRegionContainer regionContainer;
private BukkitDebugHandler debugHandler;
private StringMatcher stringMatcher;
public BukkitWorldGuardPlatform() {
}
@Override
public String getPlatformName() {
return "Bukkit-Official";
}
@Override
public String getPlatformVersion() {
return WorldGuardPlugin.inst().getDescription().getVersion();
}
@Override
public void notifyFlagContextCreate(FlagContext.FlagContextBuilder flagContextBuilder) {
Bukkit.getServer().getPluginManager().callEvent(new FlagContextCreateEvent(flagContextBuilder));
}
@Override
public BukkitConfigurationManager getGlobalStateManager() {
return configuration;
}
@Override
public StringMatcher getMatcher() {
return stringMatcher;
}
@Override
public SessionManager getSessionManager() {
return this.sessionManager;
}
@Override
public void broadcastNotification(String message) {
Bukkit.broadcast(message, "worldguard.notify");
Set<Permissible> subs = Bukkit.getPluginManager().getPermissionSubscriptions("worldguard.notify");
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
if (!(subs.contains(player) && player.hasPermission("worldguard.notify")) &&
WorldGuardPlugin.inst().hasPermission(player, "worldguard.notify")) { // Make sure the player wasn't already broadcasted to.
player.sendMessage(message);
}
}
WorldGuard.logger.info(message);
}
@Override
public void broadcastNotification(TextComponent component) {
List<LocalPlayer>
wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(
Collectors.toList());
for (LocalPlayer player : wgPlayers) {
if (player.hasPermission("worldguard.notify")) {
player.print(component);
}
}
}
@Override
public void load() {
stringMatcher = new BukkitStringMatcher();
sessionManager = new BukkitSessionManager();
configuration = new BukkitConfigurationManager(WorldGuardPlugin.inst());
configuration.load();
sessionManager.setUsingTimings(configuration.timedSessionHandlers);
regionContainer = new BukkitRegionContainer(WorldGuardPlugin.inst());
regionContainer.initialize();
debugHandler = new BukkitDebugHandler(WorldGuardPlugin.inst());
}
@Override
public void unload() {
configuration.unload();
regionContainer.shutdown();
}
@Override
public RegionContainer getRegionContainer() {
return this.regionContainer;
}
@Override
public DebugHandler getDebugHandler() {
return debugHandler;
}
@Override
public GameMode getDefaultGameMode() {
return GameModes.get(Bukkit.getServer().getDefaultGameMode().name().toLowerCase());
}
@Override
public Path getConfigDir() {
return WorldGuardPlugin.inst().getDataFolder().toPath();
}
@Override
public void stackPlayerInventory(LocalPlayer localPlayer) {
boolean ignoreMax = localPlayer.hasPermission("worldguard.stack.illegitimate");
boolean ignoreDamaged = localPlayer.hasPermission("worldguard.stack.damaged");
Player player = ((BukkitPlayer) localPlayer).getPlayer();
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
int affected = 0;
for (int i = 0; i < len; i++) {
ItemStack item = items[i];
// Avoid infinite stacks and stacks with durability
if (item == null || item.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
int max = ignoreMax ? 64 : item.getMaxStackSize();
if (item.getAmount() < max) {
int needed = max - item.getAmount(); // Number of needed items until max
// Find another stack of the same type
for (int j = i + 1; j < len; j++) {
ItemStack item2 = items[j];
// Avoid infinite stacks and stacks with durability
if (item2 == null || item2.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
// Same type?
// Blocks store their color in the damage value
if (item2.getType() == item.getType() &&
(ignoreDamaged || item.getDurability() == item2.getDurability()) &&
((item.getItemMeta() == null && item2.getItemMeta() == null)
|| (item.getItemMeta() != null &&
item.getItemMeta().equals(item2.getItemMeta())))) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(max);
item2.setAmount(item2.getAmount() - needed);
break;
// This stack will
} else {
items[j] = null;
item.setAmount(item.getAmount() + item2.getAmount());
needed = max - item.getAmount();
}
affected++;
}
}
}
}
if (affected > 0) {
player.getInventory().setContents(items);
}
}
@Override
public void addPlatformReports(ReportList report) {
report.add(new ServerReport());
report.add(new PluginReport());
report.add(new SchedulerReport());
report.add(new ServicesReport());
report.add(new WorldReport());
report.add(new PerformanceReport());
}
@Override
public ProfileService createProfileService(ProfileCache profileCache) {
List<ProfileService> services = new ArrayList<>();
if (PaperLib.isPaper()) {
// Paper has a shared cache
services.add(PaperProfileService.getInstance());
} else {
services.add(BukkitPlayerService.getInstance());
}
services.add(HttpRepositoryService.forMinecraft());
return new CacheForwardingService(new CombinedProfileService(services),
profileCache);
}
@Nullable
@Override
public ProtectedRegion getSpawnProtection(World world) {
if (world instanceof BukkitWorld) {
org.bukkit.World bWorld = ((BukkitWorld) world).getWorld();
if (bWorld.getUID().equals(Bukkit.getServer().getWorlds().get(0).getUID())) {
int radius = Bukkit.getServer().getSpawnRadius();
if (radius > 0) {
BlockVector3 spawnLoc = BukkitAdapter.asBlockVector(bWorld.getSpawnLocation());
return new ProtectedCuboidRegion("__spawn_protection__",
spawnLoc.subtract(radius, 0, radius).withY(world.getMinimumPoint().getY()),
spawnLoc.add(radius, 0, radius).withY(world.getMaxY()));
}
}
}
return null;
}
}
@@ -0,0 +1,517 @@
/*
* 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.google.common.collect.ImmutableList;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.SimpleInjector;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitCommandSender;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.listener.BlacklistListener;
import com.sk89q.worldguard.bukkit.listener.BlockedPotionsListener;
import com.sk89q.worldguard.bukkit.listener.BuildPermissionListener;
import com.sk89q.worldguard.bukkit.listener.ChestProtectionListener;
import com.sk89q.worldguard.bukkit.listener.DebuggingListener;
import com.sk89q.worldguard.bukkit.listener.EventAbstractionListener;
import com.sk89q.worldguard.bukkit.listener.InvincibilityListener;
import com.sk89q.worldguard.bukkit.listener.PlayerModesListener;
import com.sk89q.worldguard.bukkit.listener.PlayerMoveListener;
import com.sk89q.worldguard.bukkit.listener.RegionFlagsListener;
import com.sk89q.worldguard.bukkit.listener.RegionProtectionListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardBlockListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardCommandBookListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardEntityListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardHangingListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardPlayerListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardServerListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardVehicleListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardWeatherListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardWorldListener;
import com.sk89q.worldguard.bukkit.listener.WorldRulesListener;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.logging.ClassSourceValidator;
import com.sk89q.worldguard.commands.GeneralCommands;
import com.sk89q.worldguard.commands.ProtectionCommands;
import com.sk89q.worldguard.commands.ToggleCommands;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
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.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The main class for WorldGuard as a Bukkit plugin.
*/
public class WorldGuardPlugin extends JavaPlugin {
private static WorldGuardPlugin inst;
private static BukkitWorldGuardPlatform platform;
private final CommandsManager<Actor> commands;
private PlayerMoveListener playerMoveListener;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
*/
public WorldGuardPlugin() {
inst = this;
commands = new CommandsManager<Actor>() {
@Override
public boolean hasPermission(Actor player, String perm) {
return player.hasPermission(perm);
}
};
}
/**
* Get the current instance of WorldGuard
* @return WorldGuardPlugin instance
*/
public static WorldGuardPlugin inst() {
return inst;
}
/**
* Called on plugin enable.
*/
@Override
public void onEnable() {
configureLogger();
getDataFolder().mkdirs(); // Need to create the plugins/WorldGuard folder
PermissionsResolverManager.initialize(this);
WorldGuard.getInstance().setPlatform(platform = new BukkitWorldGuardPlatform()); // Initialise WorldGuard
WorldGuard.getInstance().setup();
BukkitSessionManager sessionManager = (BukkitSessionManager) platform.getSessionManager();
// Set the proper command injector
commands.setInjector(new SimpleInjector(WorldGuard.getInstance()));
// Catch bad things being done by naughty plugins that include
// WorldGuard's classes
ClassSourceValidator verifier = new ClassSourceValidator(this);
verifier.reportMismatches(ImmutableList.of(ProtectedRegion.class, ProtectedCuboidRegion.class, Flag.class));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> {
if (!platform.getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
}, 0L);
getServer().getScheduler().scheduleSyncRepeatingTask(this, sessionManager, BukkitSessionManager.RUN_DELAY, BukkitSessionManager.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();
(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, WorldGuard.logger)).registerEvents();
}
platform.getGlobalStateManager().updateCommandBookGodMode();
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
getServer().getPluginManager().registerEvents(new WorldGuardCommandBookListener(this), this);
}
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
for (World world : getServer().getWorlds()) {
worldListener.initWorld(world);
}
worldListener.registerEvents();
Bukkit.getScheduler().runTask(this, () -> {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
ProcessPlayerEvent event = new ProcessPlayerEvent(player);
Events.fire(event);
}
});
((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).setInitialized(true);
// Enable metrics
final Metrics metrics = new Metrics(this, 3283); // bStats plugin id
if (metrics.isEnabled() && platform.getGlobalStateManager().extraStats) {
setupCustomCharts(metrics);
}
}
private void setupCustomCharts(Metrics metrics) {
metrics.addCustomChart(new Metrics.SingleLineChart("region_count", () ->
platform.getRegionContainer().getLoaded().stream().mapToInt(RegionManager::size).sum()));
metrics.addCustomChart(new Metrics.SimplePie("region_driver", () -> {
RegionDriver driver = platform.getGlobalStateManager().selectedRegionStoreDriver;
return driver instanceof DirectoryYamlDriver ? "yaml" : driver instanceof SQLDriver ? "sql" : "unknown";
}));
metrics.addCustomChart(new Metrics.DrilldownPie("blacklist", () -> {
int empty = 0;
Map<String, Integer> blacklistMap = new HashMap<>();
Map<String, Integer> whitelistMap = new HashMap<>();
for (BukkitWorldConfiguration worldConfig : platform.getGlobalStateManager().getWorldConfigs()) {
Blacklist blacklist = worldConfig.getBlacklist();
if (blacklist != null && !blacklist.isEmpty()) {
Map<String, Integer> target = blacklist.isWhitelist() ? whitelistMap : blacklistMap;
int floor = ((blacklist.getItemCount() - 1) / 10) * 10;
String range = floor >= 100 ? "101+" : (floor + 1) + " - " + (floor + 10);
target.merge(range, 1, Integer::sum);
} else {
empty++;
}
}
Map<String, Map<String, Integer>> blacklistCounts = new HashMap<>();
Map<String, Integer> emptyMap = new HashMap<>();
emptyMap.put("empty", empty);
blacklistCounts.put("empty", emptyMap);
blacklistCounts.put("blacklist", blacklistMap);
blacklistCounts.put("whitelist", whitelistMap);
return blacklistCounts;
}));
metrics.addCustomChart(new Metrics.SimplePie("chest_protection", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.signChestProtection)));
metrics.addCustomChart(new Metrics.SimplePie("build_permissions", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.buildPermissions)));
metrics.addCustomChart(new Metrics.SimplePie("custom_flags", () ->
"" + (WorldGuard.getInstance().getFlagRegistry().size() > Flags.INBUILT_FLAGS.size())));
metrics.addCustomChart(new Metrics.SimplePie("custom_handlers", () ->
"" + (WorldGuard.getInstance().getPlatform().getSessionManager().customHandlersRegistered())));
}
@Override
public void onDisable() {
WorldGuard.getInstance().disable();
this.getServer().getScheduler().cancelTasks(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
Actor actor = wrapCommandSender(sender);
try {
commands.execute(cmd.getName(), args, actor, actor);
} catch (Throwable t) {
Throwable next = t;
do {
try {
WorldGuard.getInstance().getExceptionConverter().convert(next);
} catch (org.enginehub.piston.exception.CommandException pce) {
if (pce.getCause() instanceof CommandException) {
throw ((CommandException) pce.getCause());
}
}
next = next.getCause();
} while (next != null);
throw t;
}
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getCause().getMessage());
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
/**
* Check whether a player is in a group.
* This calls the corresponding method in PermissionsResolverManager
*
* @param player The player to check
* @param group The group
* @return whether {@code player} is in {@code group}
*/
public boolean inGroup(OfflinePlayer player, String group) {
try {
return PermissionsResolverManager.getInstance().inGroup(player, group);
} catch (Throwable t) {
t.printStackTrace();
return false;
}
}
/**
* Get the groups of a player.
* This calls the corresponding method in PermissionsResolverManager.
* @param player The player to check
* @return The names of each group the playe is in.
*/
public String[] getGroups(OfflinePlayer player) {
try {
return PermissionsResolverManager.getInstance().getGroups(player);
} catch (Throwable t) {
t.printStackTrace();
return new String[0];
}
}
/**
* Checks permissions.
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @return whether {@code sender} has {@code perm}
*/
public boolean hasPermission(CommandSender sender, String perm) {
if (sender.isOp()) {
if (sender instanceof Player) {
if (platform.getGlobalStateManager().get(BukkitAdapter.adapt(((Player) sender).getWorld())).opPermissions) {
return true;
}
} else {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
Player player = (Player) sender;
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player, perm);
}
return false;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @throws CommandPermissionsException if {@code sender} doesn't have {@code perm}
*/
public void checkPermission(CommandSender sender, String perm)
throws CommandPermissionsException {
if (!hasPermission(sender, perm)) {
throw new CommandPermissionsException();
}
}
/**
* Gets a copy of the WorldEdit plugin.
*
* @return The WorldEditPlugin instance
* @throws CommandException If there is no WorldEditPlugin available
*/
public WorldEditPlugin getWorldEdit() throws CommandException {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
} else if (!worldEdit.isEnabled()) {
throw new CommandException("WorldEdit does not appear to be enabled.");
}
if (worldEdit instanceof WorldEditPlugin) {
return (WorldEditPlugin) worldEdit;
} else {
throw new CommandException("WorldEdit detection failed (report error).");
}
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player The player to wrap
* @return The wrapped player
*/
public LocalPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, player);
}
/**
* 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);
}
public Actor wrapCommandSender(CommandSender sender) {
if (sender instanceof Player) {
return wrapPlayer((Player) sender);
}
try {
return new BukkitCommandSender(getWorldEdit(), sender);
} catch (CommandException e) {
e.printStackTrace();
}
return null;
}
public CommandSender unwrapActor(Actor sender) {
if (sender instanceof BukkitPlayer) {
return ((BukkitPlayer) sender).getPlayer();
} else if (sender instanceof BukkitCommandSender) {
return Bukkit.getConsoleSender(); // TODO Fix
} else {
throw new IllegalArgumentException("Unknown actor type. Please report");
}
}
/**
* 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(this, 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.
*
* @param actual The destination file
* @param defaultName The name of the file inside the jar's defaults folder
*/
public void createDefaultConfiguration(File actual, String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (actual.exists()) {
return;
}
try (InputStream stream = getResource("defaults/" + defaultName)){
if (stream == null) throw new FileNotFoundException();
copyDefaultConfig(stream, actual, defaultName);
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
}
private void copyDefaultConfig(InputStream input, File actual, String name) {
try (FileOutputStream output = new FileOutputStream(actual)) {
byte[] buf = new byte[8192];
int length;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
getLogger().info("Default configuration file written: " + name);
} catch (IOException e) {
getLogger().log(Level.WARNING, "Failed to write default config file", e);
}
}
public PlayerMoveListener getPlayerMoveListener() {
return playerMoveListener;
}
}
@@ -22,15 +22,29 @@ 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 io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.metadata.Metadatable;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -76,26 +90,15 @@ public final class Cause {
}
/**
* 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 whether a cause is known. This method will return false if
* the list of causes is empty or the root cause is really not known
* (e.g. 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;
Object object = getRootCause();
return !(object == null || object instanceof TNTPrimed || object instanceof Vehicle);
}
@Nullable
@@ -224,6 +227,15 @@ public final class Cause {
WGMetadata.put(target, CAUSE_KEY, parent);
}
/**
* Remove a parent cause from a {@code Metadatable} object.
*
* @param target the target
*/
public static void untrackParentCause(Metadatable target) {
WGMetadata.remove(target, CAUSE_KEY);
}
/**
* Builds causes.
*/
@@ -233,7 +245,7 @@ public final class Cause {
private boolean indirect;
private Builder(int expectedSize) {
this.causes = new ArrayList<Object>(expectedSize);
this.causes = new ArrayList<>(expectedSize);
}
private void addAll(@Nullable Object... element) {
@@ -248,15 +260,30 @@ public final class Cause {
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
addAll(((Projectile) o).getShooter());
ProjectileSource shooter = ((Projectile) o).getShooter();
addAll(shooter);
if (shooter == null && o instanceof Firework && PaperLib.isPaper()) {
UUID spawningUUID = ((Firework) o).getSpawningEntity();
if (spawningUUID != null) {
Entity spawningEntity = Bukkit.getEntity(spawningUUID);
if (spawningEntity != null) {
addAll(spawningEntity);
}
}
}
} else if (o instanceof Vehicle) {
addAll(((Vehicle) o).getPassenger());
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
((Vehicle) o).getPassengers().forEach(this::addAll);
} else if (o instanceof AreaEffectCloud) {
indirect = true;
addAll(((Creature) o).getTarget());
addAll(((AreaEffectCloud) o).getSource());
} else if (o instanceof Tameable) {
indirect = true;
addAll(((Tameable) o).getOwner());
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
indirect = true;
addAll(((Creature) o).getTarget());
} else if (o instanceof BlockProjectileSource) {
addAll(((BlockProjectileSource) o).getBlock());
}
// Add manually tracked parent causes
@@ -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.bukkit.chest;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.chest.SignChestProtection;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
public class BukkitSignChestProtection extends SignChestProtection {
private Boolean isProtectedSign(Sign sign, LocalPlayer player) {
if (sign.getLine(0).equalsIgnoreCase("[Lock]")) {
if (player == null) { // No player, no access
return true;
}
String name = player.getName();
return !name.equalsIgnoreCase(sign.getLine(1).trim())
&& !name.equalsIgnoreCase(sign.getLine(2).trim())
&& !name.equalsIgnoreCase(sign.getLine(3).trim());
}
return null;
}
@Override
public Boolean isProtectedSign(Location block, LocalPlayer player) {
BlockState state = BukkitAdapter.adapt(block).getBlock().getState();
if (!(state instanceof Sign)) {
return null;
}
return isProtectedSign((Sign) state, player);
}
}
@@ -126,7 +126,7 @@ public abstract class DelegateEvent extends Event implements Cancellable, Handle
}
/**
* Set the event to {@link Result#ALLOW} if {@code allowed} is true.
* Set the event to {@link org.bukkit.event.Event.Result#ALLOW} if {@code allowed} is true.
*
* @param allowed true to set the result
* @return the same event
@@ -19,22 +19,27 @@
package com.sk89q.worldguard.bukkit.event.block;
import com.google.common.base.Predicate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.event.DelegateEvent;
import com.sk89q.worldguard.bukkit.event.BulkEvent;
import com.sk89q.worldguard.bukkit.event.DelegateEvent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
/**
* This event is an internal event. We do not recommend handling or throwing
@@ -43,7 +48,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
private final World world;
private final List<Block> blocks;
private List<Block> blocks;
private final List<BlockState> blockStates;
private final Material effectiveMaterial;
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<Block> blocks, Material effectiveMaterial) {
@@ -54,6 +60,18 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
this.world = world;
this.blocks = blocks;
this.effectiveMaterial = effectiveMaterial;
this.blockStates = null;
}
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<BlockState> blocks) {
super(originalEvent, cause);
checkNotNull(world);
checkNotNull(blocks);
checkArgument(!blocks.isEmpty());
this.world = world;
this.blockStates = blocks;
this.blocks = null;
this.effectiveMaterial = blocks.get(0).getType();
}
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, Block block) {
@@ -65,7 +83,7 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
}
private static List<Block> createList(Block block) {
List<Block> blocks = new ArrayList<Block>();
List<Block> blocks = new ArrayList<>();
blocks.add(block);
return blocks;
}
@@ -85,6 +103,9 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
* @return a list of affected block
*/
public List<Block> getBlocks() {
if (blocks == null) { // be lazy here because we often don't call getBlocks internally, just filter
blocks = blockStates.stream().map(BlockState::getBlock).collect(Collectors.toList());
}
return blocks;
}
@@ -98,15 +119,21 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
* @return true if one or more blocks were filtered out
*/
public boolean filter(Predicate<Location> predicate, boolean cancelEventOnFalse) {
boolean hasRemoval = false;
return blocks == null
? filterInternal(blockStates, BlockState::getLocation, predicate, cancelEventOnFalse)
: filterInternal(blocks, Block::getLocation, predicate, cancelEventOnFalse);
}
Iterator<Block> it = blocks.iterator();
private <B> boolean filterInternal(List<B> blockList, Function<B, Location> locFunc,
Predicate<Location> predicate, boolean cancelEventOnFalse) {
boolean hasRemoval = false;
Iterator<B> it = blockList.iterator();
while (it.hasNext()) {
if (!predicate.apply(it.next().getLocation())) {
if (!predicate.test(locFunc.apply(it.next()))) {
hasRemoval = true;
if (cancelEventOnFalse) {
getBlocks().clear();
blockList.clear();
setCancelled(true);
break;
} else {
@@ -114,7 +141,6 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
}
}
}
return hasRemoval;
}
@@ -146,7 +172,7 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
@Override
public Result getResult() {
if (blocks.isEmpty()) {
if (blocks == null ? blockStates.isEmpty() : blocks.isEmpty()) {
return Result.DENY;
}
return super.getResult();
@@ -24,6 +24,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -40,6 +41,10 @@ public class PlaceBlockEvent extends AbstractBlockEvent {
private static final HandlerList handlers = new HandlerList();
public PlaceBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<BlockState> blocks) {
super(originalEvent, cause, world, blocks);
}
public PlaceBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<Block> blocks, Material effectiveMaterial) {
super(originalEvent, cause, world, blocks, effectiveMaterial);
}
@@ -29,7 +29,7 @@ import java.util.List;
*/
public class CancelLogger {
private List<CancelAttempt> entries = new ArrayList<CancelAttempt>();
private List<CancelAttempt> entries = new ArrayList<>();
/**
* Log a call.
@@ -36,10 +36,23 @@ public class LoggingPlayerInteractEvent extends PlayerInteractEvent implements C
super(who, action, item, clickedBlock, clickedFace);
}
@Override
public List<CancelAttempt> getCancels() {
return logger.getCancels();
}
@Override
public void setUseInteractedBlock(Result useInteractedBlock) {
this.logger.log(useInteractedBlock() == Result.DENY, useInteractedBlock == Result.DENY, new Exception().getStackTrace());
super.setUseInteractedBlock(useInteractedBlock);
}
@Override
public void setUseItemInHand(Result useItemInHand) {
this.logger.log(useItemInHand() == Result.DENY, useItemInHand == Result.DENY, new Exception().getStackTrace());
super.setUseItemInHand(useItemInHand);
}
@Override
public void setCancelled(boolean cancel) {
this.logger.log(isCancelled(), cancel, new Exception().getStackTrace());
@@ -21,7 +21,9 @@ package com.sk89q.worldguard.bukkit.internal;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.sk89q.worldguard.blacklist.target.MaterialTarget;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.blacklist.target.BlockTarget;
import com.sk89q.worldguard.blacklist.target.ItemTarget;
import com.sk89q.worldguard.blacklist.target.Target;
import com.sk89q.worldguard.blacklist.target.TargetMatcher;
import org.bukkit.Material;
@@ -35,7 +37,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class TargetMatcherSet {
private final Multimap<Integer, TargetMatcher> entries = HashMultimap.create();
private final Multimap<String, TargetMatcher> entries = HashMultimap.create();
public boolean add(TargetMatcher matcher) {
checkNotNull(matcher);
@@ -55,19 +57,23 @@ public class TargetMatcherSet {
}
public boolean test(Material material) {
return test(new MaterialTarget(material.getId(), (short) 0));
if (material.isBlock()) {
return test(new BlockTarget(BukkitAdapter.asBlockType(material)));
} else {
return test(new ItemTarget(BukkitAdapter.asItemType(material)));
}
}
public boolean test(Block block) {
return test(new MaterialTarget(block.getTypeId(), block.getData()));
return test(new BlockTarget(BukkitAdapter.asBlockType(block.getType())));
}
public boolean test(BlockState state) {
return test(new MaterialTarget(state.getTypeId(), state.getRawData()));
return test(new BlockTarget(BukkitAdapter.asBlockType(state.getType())));
}
public boolean test(ItemStack itemStack) {
return test(new MaterialTarget(itemStack.getTypeId(), itemStack.getDurability()));
return test(new ItemTarget(BukkitAdapter.asItemType(itemStack.getType())));
}
@Override
@@ -75,4 +75,13 @@ public final class WGMetadata {
return null;
}
/**
* Removes metadata from the target.
*
* @param target the target
* @param key the key
*/
public static void remove(Metadatable target, String key) {
target.removeMetadata(key, WorldGuardPlugin.inst());
}
}
@@ -0,0 +1,152 @@
/*
* 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.listener;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
/**
* Abstract listener to ease creation of listeners.
*/
class AbstractListener implements Listener {
private final WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public AbstractListener(WorldGuardPlugin plugin) {
checkNotNull(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the plugin.
*
* @return the plugin
*/
protected WorldGuardPlugin getPlugin() {
return plugin;
}
/**
* Get the global configuration.
*
* @return the configuration
*/
protected static ConfigurationManager getConfig() {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager();
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected static WorldConfiguration getWorldConfig(World world) {
return getConfig().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected static WorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig((World) player.getExtent());
}
/**
* Return whether region support is enabled.
*
* @param world the world
* @return true if region support is enabled
*/
protected static boolean isRegionSupportEnabled(World world) {
return getWorldConfig(world).useRegions;
}
protected RegionAssociable createRegionAssociable(Cause cause) {
Object rootCause = cause.getRootCause();
if (!cause.isKnown()) {
return Associables.constant(Association.NON_MEMBER);
} else if (rootCause instanceof Player) {
return getPlugin().wrapPlayer((Player) rootCause);
} else if (rootCause instanceof OfflinePlayer) {
return getPlugin().wrapOfflinePlayer((OfflinePlayer) rootCause);
} else if (rootCause instanceof Entity) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final Entity entity = (Entity) rootCause;
BukkitWorldConfiguration config =
(BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(entity.getWorld()));
Location loc;
if (PaperLib.isPaper() && config.usePaperEntityOrigin) {
loc = entity.getOrigin();
if (loc == null) {
loc = entity.getLocation();
}
} else {
loc = entity.getLocation();
}
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
config.useMaxPriorityAssociation);
} else if (rootCause instanceof Block) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Location loc = ((Block) rootCause).getLocation();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
getWorldConfig(BukkitAdapter.adapt(loc.getWorld())).useMaxPriorityAssociation);
} else {
return Associables.constant(Association.NON_MEMBER);
}
}
}
@@ -0,0 +1,400 @@
/*
* 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.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.blacklist.event.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.BlockDispenseBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemDestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemEquipBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemUseBlacklistEvent;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
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.DestroyEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockDispenseArmorEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import static com.sk89q.worldguard.bukkit.BukkitUtil.createTarget;
/**
* Handle events that need to be processed by the blacklist.
*/
public class BlacklistListener extends AbstractListener {
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public BlacklistListener(WorldGuardPlugin plugin) {
super(plugin);
}
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false)) {
return false;
} else if (!wcfg.getBlacklist().check(
new ItemDestroyWithBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
createTarget(player.getInventory().getItemInMainHand())), false, false)) {
return false;
}
return true;
});
}
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Material material = Materials.getRelatedMaterial(event.getEffectiveType());
if (material != null) {
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(event.getTarget()), createTarget(material)), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Entity target = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (target instanceof Item) {
Item item = (Item) target;
if (!wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer,
BukkitAdapter.asBlockVector(target.getLocation()), createTarget(item.getItemStack())), false, true)) {
event.setCancelled(true);
return;
}
}
Material material = Materials.getRelatedMaterial(target.getType());
if (material != null) {
// Not really a block but we only have one on-break blacklist event
if (!wcfg.getBlacklist().check(new BlockBreakBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(event.getTarget()), createTarget(material)), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ItemStack target = event.getItemStack();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(target)), false, false)) {
event.setCancelled(true);
return;
}
if (Materials.isArmor(target.getType()) && !wcfg.getBlacklist().check(new ItemEquipBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(target)), false, false)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getPlayer().getWorld()));
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
if (!wcfg.getBlacklist().check(
new ItemDropBlacklistEvent(getPlugin().wrapPlayer(event.getPlayer()),
BukkitAdapter.asBlockVector(ci.getLocation()), createTarget(ci.getItemStack())), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getBlock().getWorld()));
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(new BlockDispenseBlacklistEvent(null, BukkitAdapter.asBlockVector(event.getBlock().getLocation()),
createTarget(event.getItem())), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player)) return;
Inventory inventory = event.getInventory();
ItemStack item = event.getCurrentItem();
if (item != null && inventory.getHolder() != null) {
Player player = (Player) entity;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(entity.getLocation()), createTarget(item)), false, false)) {
event.setCancelled(true);
if (inventory.getHolder().equals(player)) {
event.setCurrentItem(null);
}
}
ItemStack equipped = checkEquipped(event);
if (equipped != null) {
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(new ItemEquipBlacklistEvent(localPlayer,
BukkitAdapter.asBlockVector(player.getLocation()), createTarget(equipped)), false, false)) {
event.setCancelled(true);
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryDrag(InventoryDragEvent event) {
HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player)) return;
if (event.getInventory().getType() != InventoryType.PLAYER
&& event.getInventory().getType() != InventoryType.CRAFTING) return;
if (event.getRawSlots().stream().anyMatch(i -> i >= 5 && i <= 8)) { // dropped on armor slots
Player player = (Player) entity;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(new ItemEquipBlacklistEvent(localPlayer,
BukkitAdapter.asBlockVector(player.getLocation()), createTarget(event.getOldCursor())), false, false)) {
event.setCancelled(true);
}
}
}
private ItemStack checkEquipped(InventoryClickEvent event) {
final Inventory clickedInventory = event.getClickedInventory();
if (event.getSlotType() == InventoryType.SlotType.ARMOR) {
switch (event.getAction()) {
case PLACE_ONE:
case PLACE_SOME:
case PLACE_ALL:
case SWAP_WITH_CURSOR:
final ItemStack cursor = event.getCursor();
if (cursor != null) {
return cursor;
}
case HOTBAR_SWAP:
if (event.getClick() == ClickType.SWAP_OFFHAND) {
return clickedInventory == null ? null : ((PlayerInventory) clickedInventory).getItemInOffHand();
}
return clickedInventory == null ? null : clickedInventory.getItem(event.getHotbarButton());
default:
break;
}
} else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER
&& event.getView().getTopInventory().getType() == InventoryType.PLAYER
&& event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
return event.getCurrentItem();
}
return null;
}
@EventHandler(ignoreCancelled = true)
public void onInventoryCreative(InventoryCreativeEvent event) {
HumanEntity entity = event.getWhoClicked();
ItemStack item = event.getCursor();
if (item.getType() != Material.AIR && entity instanceof Player) {
Player player = (Player) entity;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(entity.getLocation()), createTarget(item)), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
Inventory inventory = player.getInventory();
ItemStack item = inventory.getItem(event.getNewSlot());
if (item != null) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(item)), false, false)) {
inventory.setItem(event.getNewSlot(), null);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockDispenseArmor(BlockDispenseArmorEvent event) {
if (!(event.getTargetEntity() instanceof Player)) return;
Player player = ((Player) event.getTargetEntity());
ItemStack stack = event.getItem();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemEquipBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(stack)), false, true)) {
event.setCancelled(true);
}
}
}
@@ -19,22 +19,23 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.DamageEntityEvent;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.config.ConfigurationManager;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.entity.SpectralArrow;
import org.bukkit.entity.TippedArrow;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
@@ -57,15 +58,15 @@ public class BlockedPotionsListener extends AbstractListener {
if (event.getOriginalEvent() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent originalEvent = (EntityDamageByEntityEvent) event.getOriginalEvent();
if (Entities.isPotionArrow(originalEvent.getDamager())) { // should take care of backcompat
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof TippedArrow) {
TippedArrow tippedArrow = (TippedArrow) originalEvent.getDamager();
} else if (originalEvent.getDamager() instanceof Arrow) {
Arrow tippedArrow = (Arrow) originalEvent.getDamager();
PotionEffectType baseEffect = tippedArrow.getBasePotionData().getType().getEffectType();
if (wcfg.blockPotions.contains(baseEffect)) {
blockedEffect = baseEffect;
@@ -95,28 +96,16 @@ public class BlockedPotionsListener extends AbstractListener {
@EventHandler
public void onItemInteract(UseItemEvent event) {
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
ItemStack item = event.getItemStack();
// We only care about potions
boolean oldPotions = false;
try {
if (item.getType() != Material.POTION
&& item.getType() != Material.SPLASH_POTION
&& item.getType() != Material.LINGERING_POTION) {
return;
}
} catch (NoSuchFieldError ignored) {
// PotionMeta technically has been around since 1.7, so the code below
// *should* work still. we just have different materials now.
if (item.getType() != Material.POTION) {
return;
}
oldPotions = true;
if (item.getType() != Material.POTION
&& item.getType() != Material.SPLASH_POTION
&& item.getType() != Material.LINGERING_POTION) {
return;
}
if (!wcfg.blockPotions.isEmpty()) {
PotionEffectType blockedEffect = null;
@@ -147,13 +136,8 @@ public class BlockedPotionsListener extends AbstractListener {
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
boolean isSplash = false;
try {
isSplash = (!oldPotions && (item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION));
} catch (NoSuchFieldError ignored) {
}
isSplash |= (oldPotions && (Potion.fromItemStack(item).isSplash()));
if (isSplash && wcfg.blockPotionsAlways) {
if (wcfg.blockPotionsAlways && (item.getType() == Material.SPLASH_POTION
|| item.getType() == Material.LINGERING_POTION)) {
player.sendMessage(ChatColor.RED + "Sorry, potions with " +
blockedEffect.getName() + " can't be thrown, " +
"even if you have a permission to bypass it, " +
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
@@ -51,7 +52,7 @@ public class BuildPermissionListener extends AbstractListener {
}
private void tellErrorMessage(CommandSender sender, World world) {
String message = getWorldConfig(world).buildPermissionDenyMessage;
String message = getWorldConfig(BukkitAdapter.adapt(world)).buildPermissionDenyMessage;
if (!message.isEmpty()) {
sender.sendMessage(message);
}
@@ -59,7 +60,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -77,7 +78,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -95,7 +96,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -113,7 +114,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -131,7 +132,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -149,7 +150,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -167,7 +168,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -185,7 +186,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -19,16 +19,17 @@
package com.sk89q.worldguard.bukkit.listener;
import com.google.common.base.Predicate;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.DelegateEvent;
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 org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.SignChangeEvent;
@@ -58,23 +59,21 @@ public class ChestProtectionListener extends AbstractListener {
final Player player = event.getCause().getFirstPlayer();
if (player != null) {
final WorldConfiguration wcfg = getWorldConfig(player);
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
// Early guard
if (!wcfg.signChestProtection) {
return;
}
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
if (wcfg.getChestProtection().isChest(event.getEffectiveMaterial().getId()) && wcfg.isChestProtected(target.getBlock(), player)) {
sendMessage(event, player, ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
return false;
}
return true;
event.filter(target -> {
if (wcfg.getChestProtection().isChest(BukkitAdapter.asBlockType(event.getEffectiveMaterial())) && wcfg.isChestProtected(BukkitAdapter.adapt(target.getBlock().getLocation()),
WorldGuardPlugin.inst().wrapPlayer(player))) {
sendMessage(event, player, ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
return false;
}
return true;
}, true);
}
}
@@ -83,7 +82,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
// Early guard
if (!wcfg.signChestProtection) {
@@ -91,25 +90,17 @@ public class ChestProtectionListener extends AbstractListener {
}
if (player != null) {
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
if (wcfg.isChestProtected(target.getBlock(), player)) {
sendMessage(event, player, ChatColor.DARK_RED + "This chest is protected.");
return false;
}
return true;
final LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
event.filter(target -> {
if (wcfg.isChestProtected(BukkitAdapter.adapt(target.getBlock().getLocation()), localPlayer)) {
sendMessage(event, player, ChatColor.DARK_RED + "This chest is protected.");
return false;
}
return true;
}, true);
} else {
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
return !wcfg.isChestProtected(target.getBlock());
}
});
event.filter(target -> !wcfg.isChestProtected(BukkitAdapter.adapt(target.getBlock().getLocation())));
}
}
@@ -117,7 +108,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onUseBlock(final UseBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
// Early guard
if (!wcfg.signChestProtection) {
@@ -125,43 +116,35 @@ public class ChestProtectionListener extends AbstractListener {
}
if (player != null) {
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
if (wcfg.isChestProtected(target.getBlock(), player)) {
sendMessage(event, player, ChatColor.DARK_RED + "This chest is protected.");
return false;
}
return true;
final LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
event.filter(target -> {
if (wcfg.isChestProtected(BukkitAdapter.adapt(target.getBlock().getLocation()), localPlayer)) {
sendMessage(event, player, ChatColor.DARK_RED + "This chest is protected.");
return false;
}
return true;
}, true);
} else {
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
return !wcfg.isChestProtected(target.getBlock());
}
});
event.filter(target -> !wcfg.isChestProtected(BukkitAdapter.adapt(target.getBlock().getLocation())));
}
}
@EventHandler(ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
if ("[Lock]".equalsIgnoreCase(event.getLine(0))) {
if (wcfg.isChestProtectedPlacement(BukkitAdapter.adapt(event.getBlock().getLocation()), WorldGuardPlugin.inst().wrapPlayer(player))) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
if (!Tag.STANDING_SIGNS.isTagged(event.getBlock().getType())) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
@@ -170,7 +153,7 @@ public class ChestProtectionListener extends AbstractListener {
return;
}
if (!event.getLine(1).equalsIgnoreCase(player.getName())) {
if (!player.getName().equalsIgnoreCase(event.getLine(1))) {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
@@ -179,10 +162,10 @@ public class ChestProtectionListener extends AbstractListener {
return;
}
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
Material below = event.getBlock().getRelative(0, -1, 0).getType();
if (below == BlockID.TNT || below == BlockID.SAND
|| below == BlockID.GRAVEL || below == BlockID.SIGN_POST) {
if (below == Material.TNT || below == Material.SAND
|| below == Material.GRAVEL || Tag.STANDING_SIGNS.isTagged(below)) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
@@ -196,7 +179,7 @@ public class ChestProtectionListener extends AbstractListener {
+ "A chest or double chest above is now protected.");
}
} else if (!wcfg.disableSignChestProtectionCheck) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if ("[Lock]".equalsIgnoreCase(event.getLine(0))) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
@@ -23,6 +23,7 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
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.DestroyEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.UseEntityEvent;
@@ -33,6 +34,7 @@ import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractEvent;
import javax.annotation.Nullable;
import java.util.List;
@@ -61,13 +63,13 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("PLACE");
builder.append(" ");
builder.append("").append(event.getEffectiveMaterial());
builder.append(event.getEffectiveMaterial());
builder.append(" ");
builder.append("@").append(toBlockString(event.getBlocks()));
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -79,13 +81,13 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("DIG");
builder.append(" ");
builder.append("").append(event.getEffectiveMaterial());
builder.append(event.getEffectiveMaterial());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getBlocks()));
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -97,13 +99,16 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("INTERACT");
builder.append(" ");
builder.append("").append(event.getEffectiveMaterial());
builder.append(event.getEffectiveMaterial());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getBlocks()));
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getOriginalEvent() instanceof PlayerInteractEvent) {
builder.append(".").append(((PlayerInteractEvent) event.getOriginalEvent()).getAction());
}
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -115,13 +120,13 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("SPAWN");
builder.append(" ");
builder.append("").append(event.getEffectiveType());
builder.append(event.getEffectiveType());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getTarget()));
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -133,13 +138,13 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("DESTROY");
builder.append(" ");
builder.append("").append(event.getEntity().getType());
builder.append(event.getEntity().getType());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getTarget()));
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -151,13 +156,31 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("INTERACT");
builder.append(" ");
builder.append("").append(event.getEntity().getType());
builder.append(event.getEntity().getType());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getTarget()));
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
logger.info(builder.toString());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onDamageEntity(DamageEntityEvent event) {
StringBuilder builder = new StringBuilder();
builder.append("DAMAGE");
builder.append(" ");
builder.append(event.getEntity().getType());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(toBlockString(event.getTarget()));
builder.append(" ");
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -169,13 +192,13 @@ public class DebuggingListener extends AbstractListener {
StringBuilder builder = new StringBuilder();
builder.append("USE");
builder.append(" ");
builder.append("").append(event.getItemStack().getType());
builder.append(event.getItemStack().getType());
builder.append(" ");
builder.append("[").append(event.getCause()).append("]");
builder.append(" ");
builder.append("@").append(event.getWorld().getName());
builder.append(" ");
builder.append(":").append(getEventName(event.getOriginalEvent()));
builder.append(": ").append(getEventName(event.getOriginalEvent()));
if (event.getResult() != Result.DEFAULT) {
builder.append(" [").append(event.getResult()).append("]");
}
@@ -19,11 +19,15 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityCombustEvent;
@@ -48,19 +52,22 @@ public class InvincibilityListener extends AbstractListener {
* @param player The player
* @return True if invincible
*/
private boolean isInvincible(Player player) {
return getPlugin().getSessionManager().get(player).isInvincible(player);
private boolean isInvincible(LocalPlayer player) {
return WorldGuard.getInstance().getPlatform().getSessionManager().get(player).isInvincible(player);
}
@EventHandler(ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity victim = event.getEntity();
WorldConfiguration worldConfig = getPlugin().getGlobalStateManager().get(victim.getWorld());
if (victim instanceof Player) {
Player player = (Player) victim;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(player)) {
BukkitWorldConfiguration worldConfig =
(BukkitWorldConfiguration) WorldGuard.getInstance().getPlatform().getGlobalStateManager().get((World) localPlayer.getExtent());
if (isInvincible(localPlayer)) {
player.setFireTicks(0);
event.setCancelled(true);
@@ -68,6 +75,10 @@ public class InvincibilityListener extends AbstractListener {
EntityDamageByEntityEvent byEntityEvent = (EntityDamageByEntityEvent) event;
Entity attacker = byEntityEvent.getDamager();
if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Entity) {
attacker = (Entity) ((Projectile) attacker).getShooter();
}
if (worldConfig.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
@@ -84,8 +95,9 @@ public class InvincibilityListener extends AbstractListener {
if (entity instanceof Player) {
Player player = (Player) entity;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(player)) {
if (isInvincible(localPlayer)) {
event.setCancelled(true);
}
}
@@ -95,8 +107,9 @@ public class InvincibilityListener extends AbstractListener {
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(localPlayer)) {
event.setCancelled(true);
}
}
@@ -19,7 +19,8 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.session.Session;
@@ -62,18 +63,18 @@ public class PlayerModesListener extends AbstractListener {
@EventHandler
public void onProcessPlayer(ProcessPlayerEvent event) {
ConfigurationManager config = getConfig();
Player player = event.getPlayer();
Session session = getPlugin().getSessionManager().get(player);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
if (hasGodModeGroup(player) || hasGodModePermission(player)) {
if (GodMode.set(player, session, true)) {
if (GodMode.set(localPlayer, session, true)) {
log.log(Level.INFO, "Enabled auto-god mode for " + player.getName());
}
}
if (hasAmphibiousGroup(player)) {
if (WaterBreathing.set(player, session, true)) {
if (WaterBreathing.set(localPlayer, session, true)) {
log.log(Level.INFO, "Enabled water breathing mode for " + player.getName() + " (player is in group 'wg-amphibious')");
}
}
@@ -0,0 +1,167 @@
/*
* 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.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.Vector;
import org.spigotmc.event.entity.EntityMountEvent;
public class PlayerMoveListener implements Listener {
private final WorldGuardPlugin plugin;
public PlayerMoveListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().usePlayerMove) {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
if (PaperLib.isSpigot()) {
pm.registerEvents(new EntityMountListener(), plugin);
}
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
LocalPlayer player = plugin.wrapPlayer(event.getPlayer());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
session.testMoveTo(player, BukkitAdapter.adapt(event.getRespawnLocation()), MoveType.RESPAWN, true);
}
@EventHandler
public void onVehicleEnter(VehicleEnterEvent event) {
Entity entity = event.getEntered();
if (entity instanceof Player) {
LocalPlayer player = plugin.wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getVehicle().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(PlayerMoveEvent event) {
Location from = event.getFrom();
Location to = event.getTo();
if (from.getBlockX() == to.getBlockX()
&& from.getBlockY() == to.getBlockY()
&& from.getBlockZ() == to.getBlockZ()) {
return;
}
final Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
MoveType moveType = MoveType.MOVE;
if (event.getPlayer().isGliding()) {
moveType = MoveType.GLIDE;
} else if (event.getPlayer().isSwimming()) {
moveType = MoveType.SWIM;
} else if (event.getPlayer().getVehicle() != null && event.getPlayer().getVehicle() instanceof Horse) {
moveType = MoveType.RIDE;
}
com.sk89q.worldedit.util.Location weLocation = session.testMoveTo(localPlayer, BukkitAdapter.adapt(to), moveType);
if (weLocation != null) {
final Location override = BukkitAdapter.adapt(weLocation);
override.setX(override.getBlockX() + 0.5);
override.setY(override.getBlockY());
override.setZ(override.getBlockZ() + 0.5);
override.setPitch(to.getPitch());
override.setYaw(to.getYaw());
event.setTo(override.clone());
Entity vehicle = player.getVehicle();
if (vehicle != null) {
vehicle.eject();
Entity current = vehicle;
while (current != null) {
current.eject();
vehicle.setVelocity(new Vector());
if (vehicle instanceof LivingEntity) {
vehicle.teleport(override.clone());
} else {
vehicle.teleport(override.clone().add(0, 1, 0));
}
current = current.getVehicle();
}
player.teleport(override.clone().add(0, 1, 0));
Bukkit.getScheduler().runTaskLater(plugin, () -> player.teleport(override.clone().add(0, 1, 0)), 1);
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
final Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
com.sk89q.worldedit.util.Location loc = session.testMoveTo(localPlayer,
BukkitAdapter.adapt(event.getPlayer().getLocation()), MoveType.OTHER_CANCELLABLE); // white lie
if (loc != null) {
player.teleport(BukkitAdapter.adapt(loc));
}
}
private class EntityMountListener implements Listener {
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = plugin.wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getMount().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
}
}
@@ -19,17 +19,18 @@
package com.sk89q.worldguard.bukkit.listener;
import com.google.common.base.Predicate;
import com.sk89q.worldguard.bukkit.RegionQuery;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
@@ -41,7 +42,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import javax.annotation.Nullable;
import java.util.function.Predicate;
public class RegionFlagsListener extends AbstractListener {
@@ -56,42 +57,60 @@ public class RegionFlagsListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
event.filter(testState(query, Flags.PISTONS), false);
}
}
if (event.getCause().find(EntityType.SNOWMAN) != null) {
event.filter(testState(query, Flags.SNOWMAN_TRAILS), false);
}
if (event.getCause().find(EntityType.ENDERMAN) != null) {
event.filter(testState(query, Flags.ENDER_BUILD), false);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
WorldConfiguration config = getWorldConfig(event.getWorld());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
WorldConfiguration config = getWorldConfig(weWorld);
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
event.filter(testState(query, Flags.PISTONS), false);
}
}
if (event.getCause().find(EntityType.CREEPER) != null) { // Creeper
event.filter(testState(query, DefaultFlag.CREEPER_EXPLOSION), config.explosionFlagCancellation);
event.filter(testState(query, Flags.CREEPER_EXPLOSION), config.explosionFlagCancellation);
}
if (event.getCause().find(EntityType.ENDER_DRAGON) != null) { // Enderdragon
event.filter(testState(query, DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE), config.explosionFlagCancellation);
event.filter(testState(query, Flags.ENDERDRAGON_BLOCK_DAMAGE), config.explosionFlagCancellation);
}
if (event.getCause().find(Entities.enderCrystalType) != null) { // should be nullsafe even if enderCrystalType field is null
event.filter(testState(query, DefaultFlag.OTHER_EXPLOSION), config.explosionFlagCancellation);
if (event.getCause().find(EntityType.ENDER_CRYSTAL) != null) { // EnderCrystal
event.filter(testState(query, Flags.OTHER_EXPLOSION), config.explosionFlagCancellation);
}
if (event.getCause().find(EntityType.ENDERMAN) != null) {
event.filter(testState(query, Flags.ENDER_BUILD), false);
}
if (event.getCause().find(EntityType.RAVAGER) != null) {
event.filter(testState(query, Flags.RAVAGER_RAVAGE), false);
}
}
@@ -100,23 +119,25 @@ public class RegionFlagsListener extends AbstractListener {
Entity entity = event.getEntity();
World world = entity.getWorld();
if (!isRegionSupportEnabled(world)) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
if (!isRegionSupportEnabled(BukkitAdapter.adapt(world))) return; // Region support disabled
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (entity instanceof Player && event.getCause() == DamageCause.FALL) {
if (!query.testState(entity.getLocation(), (Player) entity, DefaultFlag.FALL_DAMAGE)) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer((Player) entity);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
}
} else {
try {
if (entity instanceof Player && event.getCause() == DamageCause.FLY_INTO_WALL) {
if (!query.testState(entity.getLocation(), (Player) entity, DefaultFlag.FALL_DAMAGE)) {
event.setCancelled(true);
}
if (entity instanceof Player && event.getCause() == DamageCause.FLY_INTO_WALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer((Player) entity);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
}
} catch (NoSuchFieldError ignored) {
}
}
}
/**
@@ -127,12 +148,7 @@ public class RegionFlagsListener extends AbstractListener {
* @return a predicate
*/
private Predicate<Location> testState(final RegionQuery query, final StateFlag flag) {
return new Predicate<Location>() {
@Override
public boolean apply(@Nullable Location location) {
return query.testState(location, (RegionAssociable) null, flag);
}
};
return location -> query.testState(BukkitAdapter.adapt(location), (RegionAssociable) null, flag);
}
@@ -20,8 +20,9 @@
package com.sk89q.worldguard.bukkit.listener;
import com.google.common.base.Predicate;
import com.sk89q.worldguard.bukkit.RegionQuery;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.event.DelegateEvent;
@@ -33,33 +34,34 @@ import com.sk89q.worldguard.bukkit.event.entity.DestroyEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.bukkit.event.entity.UseEntityEvent;
import com.sk89q.worldguard.bukkit.internal.WGMetadata;
import com.sk89q.worldguard.bukkit.permission.RegionPermissionModel;
import com.sk89q.worldguard.bukkit.protection.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.bukkit.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.InteropUtils;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import java.util.ArrayList;
@@ -105,16 +107,22 @@ public class RegionProtectionListener extends AbstractListener {
long now = System.currentTimeMillis();
Long lastTime = WGMetadata.getIfPresent(player, DENY_MESSAGE_KEY, Long.class);
if (lastTime == null || now - lastTime >= LAST_MESSAGE_DELAY) {
RegionQuery query = getPlugin().getRegionContainer().createQuery();
String message = query.queryValue(location, player, DefaultFlag.DENY_MESSAGE);
if (message != null && !message.isEmpty()) {
player.sendMessage(message.replace("%what%", what));
}
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
String message = query.queryValue(BukkitAdapter.adapt(location), localPlayer, Flags.DENY_MESSAGE);
formatAndSendDenyMessage(what, localPlayer, message);
WGMetadata.put(player, DENY_MESSAGE_KEY, now);
}
}
}
static void formatAndSendDenyMessage(String what, LocalPlayer localPlayer, String message) {
if (message == null || message.isEmpty()) return;
message = WorldGuard.getInstance().getPlatform().getMatcher().replaceMacros(localPlayer, message);
message = CommandUtils.replaceColorMacros(message);
localPlayer.printRaw(message.replace("%what%", what));
}
/**
* Return whether the given cause is whitelist (should be ignored).
*
@@ -126,133 +134,107 @@ public class RegionProtectionListener extends AbstractListener {
private boolean isWhitelisted(Cause cause, World world, boolean pvp) {
Object rootCause = cause.getRootCause();
if (rootCause instanceof Block) {
Material type = ((Block) rootCause).getType();
return type == Material.HOPPER || type == Material.DROPPER;
} else if (rootCause instanceof Player) {
if (rootCause instanceof Player) {
Player player = (Player) rootCause;
WorldConfiguration config = getWorldConfig(world);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
com.sk89q.worldedit.world.World localWorld = BukkitAdapter.adapt(world);
WorldConfiguration config = getWorldConfig(localWorld);
if (config.fakePlayerBuildOverride && InteropUtils.isFakePlayer(player)) {
return true;
}
return !pvp && new RegionPermissionModel(getPlugin(), player).mayIgnoreRegionProtection(world);
return !pvp && WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localWorld);
} else {
return false;
}
}
private RegionAssociable createRegionAssociable(Cause cause) {
Object rootCause = cause.getRootCause();
if (!cause.isKnown()) {
return Associables.constant(Association.NON_MEMBER);
} else if (rootCause instanceof Player) {
return getPlugin().wrapPlayer((Player) rootCause);
} else if (rootCause instanceof OfflinePlayer) {
return getPlugin().wrapOfflinePlayer((OfflinePlayer) rootCause);
} else if (rootCause instanceof Entity) {
RegionQuery query = getPlugin().getRegionContainer().createQuery();
return new DelayedRegionOverlapAssociation(query, ((Entity) rootCause).getLocation());
} else if (rootCause instanceof Block) {
RegionQuery query = getPlugin().getRegionContainer().createQuery();
return new DelayedRegionOverlapAssociation(query, ((Block) rootCause).getLocation());
} else {
return Associables.constant(Association.NON_MEMBER);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
final RegionQuery query = getPlugin().getRegionContainer().createQuery();
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final RegionAssociable associable = createRegionAssociable(event.getCause());
// Don't check liquid flow unless it's enabled
if (event.getCause().getRootCause() instanceof Block
&& Materials.isLiquid(type)
&& !getWorldConfig(event.getWorld()).checkLiquidFlow) {
&& !getWorldConfig(BukkitAdapter.adapt(event.getWorld())).checkLiquidFlow) {
return;
}
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
boolean canPlace;
String what;
event.filter((Predicate<Location>) target -> {
boolean canPlace;
String what;
/* Flint and steel, fire charge, etc. */
if (type == Material.FIRE) {
Block block = event.getCause().getFirstBlock();
boolean fire = block != null && block.getType() == Material.FIRE;
boolean lava = block != null && Materials.isLava(block.getType());
List<StateFlag> flags = new ArrayList<StateFlag>();
flags.add(DefaultFlag.BLOCK_PLACE);
flags.add(DefaultFlag.LIGHTER);
if (fire) flags.add(DefaultFlag.FIRE_SPREAD);
if (lava) flags.add(DefaultFlag.LAVA_FIRE);
canPlace = query.testBuild(target, associable, combine(event, flags.toArray(new StateFlag[flags.size()])));
what = "place fire";
/* Flint and steel, fire charge, etc. */
if (Materials.isFire(type)) {
Block block = event.getCause().getFirstBlock();
boolean fire = block != null && Materials.isFire(type);
boolean lava = block != null && Materials.isLava(block.getType());
List<StateFlag> flags = new ArrayList<>();
flags.add(Flags.BLOCK_PLACE);
flags.add(Flags.LIGHTER);
if (fire) flags.add(Flags.FIRE_SPREAD);
if (lava) flags.add(Flags.LAVA_FIRE);
canPlace = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, flags.toArray(new StateFlag[flags.size()])));
what = "place fire";
/* Everything else */
} else {
canPlace = query.testBuild(target, associable, combine(event, DefaultFlag.BLOCK_PLACE));
try {
event.setSilent(type == Material.FROSTED_ICE);
} catch (NoSuchFieldError ignored) {} // back compat
what = "place that block";
}
if (!canPlace) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
return true;
} else if (type == Material.FROSTED_ICE) {
event.setSilent(true); // gets spammy
canPlace = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_PLACE, Flags.FROSTED_ICE_FORM));
what = "use frostwalker"; // hidden anyway
/* Everything else */
} else {
canPlace = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_PLACE));
what = "place that block";
}
if (!canPlace) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
return true;
});
}
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final RegionQuery query = getPlugin().getRegionContainer().createQuery();
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (!event.isCancelled()) {
final RegionAssociable associable = createRegionAssociable(event.getCause());
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
boolean canBreak;
String what;
event.filter((Predicate<Location>) target -> {
boolean canBreak;
String what;
/* TNT */
if (event.getCause().find(EntityType.PRIMED_TNT, EntityType.MINECART_TNT) != null) {
canBreak = query.testBuild(target, associable, combine(event, DefaultFlag.BLOCK_BREAK, DefaultFlag.TNT));
what = "use dynamite";
/* TNT */
if (event.getCause().find(EntityType.PRIMED_TNT, EntityType.MINECART_TNT) != null) {
canBreak = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_BREAK, Flags.TNT));
what = "use dynamite";
/* Everything else */
} else {
canBreak = query.testBuild(target, associable, combine(event, DefaultFlag.BLOCK_BREAK));
what = "break that block";
}
if (!canBreak) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
return true;
/* Everything else */
} else {
canBreak = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_BREAK));
what = "break that block";
}
if (!canBreak) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
return true;
});
}
}
@@ -260,70 +242,82 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
final RegionQuery query = getPlugin().getRegionContainer().createQuery();
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final RegionAssociable associable = createRegionAssociable(event.getCause());
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
boolean canUse;
String what;
event.filter((Predicate<Location>) target -> {
boolean canUse;
String what;
/* Saplings, etc. */
if (Materials.isConsideredBuildingIfUsed(type)) {
canUse = query.testBuild(target, associable, combine(event));
what = "use that";
/* Saplings, etc. */
if (Materials.isConsideredBuildingIfUsed(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "use that";
/* Inventory */
} else if (Materials.isInventoryBlock(type)) {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT, DefaultFlag.CHEST_ACCESS));
what = "open that";
/* Inventory */
} else if (Materials.isInventoryBlock(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "open that";
/* Beds */
} else if (type == Material.BED_BLOCK) {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT, DefaultFlag.SLEEP));
what = "sleep";
/* Inventory for blocks with the possibility to be only use, e.g. lectern */
} else if (handleAsInventoryUsage(event.getOriginalEvent())) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "take that";
/* TNT */
} else if (type == Material.TNT) {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT, DefaultFlag.TNT));
what = "use explosives";
/* Anvils */
} else if (Materials.isAnvil(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.USE_ANVIL));
what = "use that";
/* Legacy USE flag */
} else if (Materials.isUseFlagApplicable(type)) {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT, DefaultFlag.USE));
what = "use that";
/* Beds */
} else if (Materials.isBed(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.SLEEP));
what = "sleep";
/* Everything else */
} else {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT));
what = "use that";
}
/* Respawn Anchors */
} else if(type == Material.RESPAWN_ANCHOR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.RESPAWN_ANCHORS));
what = "use anchors";
if (!canUse) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
/* TNT */
} else if (type == Material.TNT) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.TNT));
what = "use explosives";
return true;
/* Legacy USE flag */
} else if (Materials.isUseFlagApplicable(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.USE));
what = "use that";
/* Everything else */
} else {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT));
what = "use that";
}
if (!canUse) {
tellErrorMessage(event, event.getCause(), target, what);
return false;
}
return true;
});
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
EntityType type = event.getEffectiveType();
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
RegionAssociable associable = createRegionAssociable(event.getCause());
boolean canSpawn;
@@ -331,32 +325,27 @@ public class RegionProtectionListener extends AbstractListener {
/* Vehicles */
if (Entities.isVehicle(type)) {
canSpawn = query.testBuild(target, associable, combine(event, DefaultFlag.PLACE_VEHICLE));
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.PLACE_VEHICLE));
what = "place vehicles";
/* Item pickup */
} else if (event.getEntity() instanceof Item) {
canSpawn = query.testBuild(target, associable, combine(event, DefaultFlag.ITEM_DROP));
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_DROP));
what = "drop items";
/* XP drops */
} else if (type == EntityType.EXPERIENCE_ORB) {
canSpawn = query.testBuild(target, associable, combine(event, DefaultFlag.EXP_DROPS));
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.EXP_DROPS));
what = "drop XP";
} else if (Entities.isAoECloud(type)) {
canSpawn = query.testBuild(target, associable, combine(event, DefaultFlag.POTION_SPLASH));
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.POTION_SPLASH));
what = "use lingering potions";
/* Everything else */
} else {
canSpawn = query.testBuild(target, associable, combine(event));
if (event.getEntity() instanceof Item) {
what = "drop items";
} else {
what = "place things";
}
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "place things";
}
if (!canSpawn) {
@@ -368,30 +357,30 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
EntityType type = event.getEntity().getType();
RegionAssociable associable = createRegionAssociable(event.getCause());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
boolean canDestroy;
String what;
/* Vehicles */
if (Entities.isVehicle(type)) {
canDestroy = query.testBuild(target, associable, combine(event, DefaultFlag.DESTROY_VEHICLE));
canDestroy = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.DESTROY_VEHICLE));
what = "break vehicles";
/* Item pickup */
} else if (event.getEntity() instanceof Item || event.getEntity() instanceof ExperienceOrb) {
canDestroy = query.testBuild(target, associable, combine(event, DefaultFlag.ITEM_PICKUP));
canDestroy = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_PICKUP));
what = "pick up items";
/* Everything else */
} else {
canDestroy = query.testBuild(target, associable, combine(event));
canDestroy = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "break things";
}
@@ -404,35 +393,44 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
RegionAssociable associable = createRegionAssociable(event.getCause());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
boolean canUse;
String what;
/* Hostile / ambient mob override */
if (Entities.isHostile(event.getEntity()) || Entities.isAmbient(event.getEntity())
|| Entities.isNPC(event.getEntity()) || Entities.isVehicle(event.getEntity().getType())) {
canUse = event.getRelevantFlags().isEmpty() || query.queryState(target, associable, combine(event)) != State.DENY;
final Entity entity = event.getEntity();
final EntityType type = entity.getType();
if (Entities.isHostile(entity) || Entities.isAmbient(entity)
|| Entities.isNPC(entity) || entity instanceof Player) {
canUse = event.getRelevantFlags().isEmpty() || query.queryState(BukkitAdapter.adapt(target), associable, combine(event)) != State.DENY;
what = "use that";
/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(event.getEntity())) {
canUse = query.testBuild(target, associable, combine(event));
what = "change that";
} else if (Entities.isConsideredBuildingIfUsed(entity)) {
if (type == EntityType.ITEM_FRAME && event.getCause().getFirstPlayer() != null
&& ((ItemFrame) entity).getItem().getType() != Material.AIR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_FRAME_ROTATE));
what = "change that";
} else if (Entities.isMinecart(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "open that";
} else {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "change that";
}
/* Ridden on use */
} else if (Entities.isRiddenOnUse(event.getEntity())) {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.RIDE, DefaultFlag.INTERACT));
} else if (Entities.isRiddenOnUse(entity)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.RIDE, Flags.INTERACT));
what = "ride that";
/* Everything else */
} else {
canUse = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT));
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT));
what = "use that";
}
@@ -445,13 +443,13 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
// Whitelist check is below
Location target = event.getTarget();
com.sk89q.worldedit.util.Location target = BukkitAdapter.adapt(event.getTarget());
RegionAssociable associable = createRegionAssociable(event.getCause());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Player playerAttacker = event.getCause().getFirstPlayer();
boolean canDamage;
String what;
@@ -477,11 +475,17 @@ public class RegionProtectionListener extends AbstractListener {
/* PVP */
} else if (pvp) {
LocalPlayer localAttacker = WorldGuardPlugin.inst().wrapPlayer(playerAttacker);
Player defender = (Player) event.getEntity();
canDamage = query.testBuild(target, associable, combine(event, DefaultFlag.PVP))
&& query.queryState(playerAttacker.getLocation(), playerAttacker, combine(event, DefaultFlag.PVP)) != State.DENY
&& query.queryState(target, playerAttacker, combine(event, DefaultFlag.PVP)) != State.DENY;
// if defender is an NPC
if (Entities.isNPC(defender)) {
return;
}
canDamage = query.testBuild(target, associable, combine(event, Flags.PVP))
&& query.queryState(localAttacker.getLocation(), localAttacker, combine(event, Flags.PVP)) != State.DENY
&& query.queryState(target, localAttacker, combine(event, Flags.PVP)) != State.DENY;
// Fire the disallow PVP event
if (!canDamage && Events.fireAndTestCancel(new DisallowedPVPEvent(playerAttacker, defender, event.getOriginalEvent()))) {
@@ -497,17 +501,17 @@ public class RegionProtectionListener extends AbstractListener {
/* damage to non-hostile mobs (e.g. animals) */
} else if (Entities.isNonHostile(event.getEntity())) {
canDamage = query.testBuild(target, associable, combine(event, DefaultFlag.DAMAGE_ANIMALS));
canDamage = query.testBuild(target, associable, combine(event, Flags.DAMAGE_ANIMALS));
what = "harm that";
/* Everything else */
} else {
canDamage = query.testBuild(target, associable, combine(event, DefaultFlag.INTERACT));
canDamage = query.testBuild(target, associable, combine(event, Flags.INTERACT));
what = "hit that";
}
if (!canDamage) {
tellErrorMessage(event, event.getCause(), target, what);
tellErrorMessage(event, event.getCause(), event.getTarget(), what);
event.setCancelled(true);
}
}
@@ -515,14 +519,16 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) {
Entity vehicle = event.getVehicle();
if (!isRegionSupportEnabled(BukkitAdapter.adapt(vehicle.getWorld()))) return; // Region support disabled
Entity exited = event.getExited();
if (vehicle instanceof Tameable && exited instanceof Player) {
Player player = (Player) exited;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (!isWhitelisted(Cause.create(player), vehicle.getWorld(), false)) {
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Location location = vehicle.getLocation();
if (!query.testBuild(location, player, DefaultFlag.RIDE, DefaultFlag.INTERACT)) {
if (!query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.RIDE, Flags.INTERACT)) {
long now = System.currentTimeMillis();
Long lastTime = WGMetadata.getIfPresent(player, DISEMBARK_MESSAGE_KEY, Long.class);
if (lastTime == null || now - lastTime >= LAST_MESSAGE_DELAY) {
@@ -558,4 +564,14 @@ public class RegionProtectionListener extends AbstractListener {
return flags;
}
/**
* Check if that event should be handled as inventory usage, e.g. if a player takes a book from a lectern
*
* @param event the event to handle
* @return whether it should be handled as inventory usage
*/
private static boolean handleAsInventoryUsage(Event event) {
return event instanceof PlayerTakeLecternBookEvent;
}
}
@@ -19,27 +19,36 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.util.SpongeUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowman;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockPhysicsEvent;
@@ -49,6 +58,8 @@ import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
/**
* The listener for block events.
@@ -81,17 +92,17 @@ public class WorldGuardBlockListener implements Listener {
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
private WorldConfiguration getWorldConfig(World world) {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(world));
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
* @return The {@link BukkitWorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
private WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
@@ -101,14 +112,15 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block target = event.getBlock();
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getType() != Material.AIR && !(ItemType.usesDamageValue(held.getTypeId())|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) 0);
player.setItemInHand(held);
ItemStack held = player.getInventory().getItemInMainHand();
ItemMeta meta = held.getItemMeta();
if (meta != null) {
((Damageable) meta).setDamage(0);
held.setItemMeta(meta);
player.getInventory().setItemInMainHand(held);
}
}
}
@@ -122,12 +134,13 @@ public class WorldGuardBlockListener implements Listener {
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
boolean isAir = blockFrom.getTypeId() == 0;
Material fromType = blockFrom.getType();
boolean isWater = Materials.isWater(fromType);
boolean isLava = fromType == Material.LAVA;
boolean isAir = fromType == Material.AIR;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -143,7 +156,7 @@ public class WorldGuardBlockListener implements Listener {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
if (sponge.getType() == Material.SPONGE
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
@@ -166,45 +179,36 @@ public class WorldGuardBlockListener implements Listener {
// Check the fluid block (from) whether it is air.
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
if (!wcfg.preventWaterDamage.isEmpty()) {
Material targetId = blockTo.getType();
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
wcfg.preventWaterDamage.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.isEmpty() && isLava) {
Material targetId = blockTo.getRelative(0, -1, 0).getType();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
if (!wcfg.allowedLavaSpreadOver.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
if (wcfg.highFreqFlags && isWater
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.WATER_FLOW,
blockFrom.getLocation())) {
if (wcfg.highFreqFlags && (isWater || blockFrom.getBlockData() instanceof Waterlogged)
&& WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(blockFrom.getLocation()), (RegionAssociable) null, Flags.WATER_FLOW) == StateFlag.State.DENY) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && isLava
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.LAVA_FLOW,
blockFrom.getLocation())) {
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(blockFrom.getLocation()), (RegionAssociable) null, Flags.LAVA_FLOW))) {
event.setCancelled(true);
return;
}
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& (blockTo.getTypeId() == BlockID.REDSTONE_WIRE
|| blockTo.getTypeId() == BlockID.TRIPWIRE)) {
blockTo.setTypeId(BlockID.AIR);
return;
}
}
/*
@@ -216,8 +220,8 @@ public class WorldGuardBlockListener implements Listener {
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(world);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -252,45 +256,46 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
if (!wcfg.disableFireSpreadBlocks.isEmpty() && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
if (wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(world.getBlockAt(x, y - 1, z).getType()).getId())
|| wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(world.getBlockAt(x + 1, y, z).getType()).getId())
|| wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(world.getBlockAt(x - 1, y, z).getType()).getId())
|| wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(world.getBlockAt(x, y, z - 1).getType()).getId())
|| wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(world.getBlockAt(x, y, z + 1).getType()).getId())) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (wcfg.highFreqFlags && isFireSpread
&& !set.allows(DefaultFlag.FIRE_SPREAD)) {
&& !set.testState(null, Flags.FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && cause == IgniteCause.LAVA
&& !set.allows(DefaultFlag.LAVA_FIRE)) {
&& !set.testState(null, Flags.LAVA_FIRE)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FIREBALL && event.getPlayer() == null) {
// wtf bukkit, FIREBALL is supposed to be reserved to players
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
if (!set.testState(null, Flags.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
if (cause == IgniteCause.LIGHTNING && !set.testState(null, Flags.LIGHTNING)) {
event.setCancelled(true);
return;
}
@@ -302,8 +307,8 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -318,21 +323,21 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
if (!wcfg.disableFireSpreadBlocks.isEmpty()) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
if (wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(block.getType()).getId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
}
if (wcfg.isChestProtected(event.getBlock())) {
if (wcfg.isChestProtected(BukkitAdapter.adapt(event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
@@ -342,28 +347,29 @@ public class WorldGuardBlockListener implements Listener {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, BlockID.FIRE);
if (!set.testState(null, Flags.FIRE_SPREAD)) {
checkAndDestroyFireAround(block.getWorld(), x, y, z);
event.setCancelled(true);
}
}
}
private void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
private void checkAndDestroyFireAround(World world, int x, int y, int z) {
checkAndDestroyFire(world, x, y, z + 1);
checkAndDestroyFire(world, x, y, z - 1);
checkAndDestroyFire(world, x, y + 1, z);
checkAndDestroyFire(world, x, y - 1, z);
checkAndDestroyFire(world, x + 1, y, z);
checkAndDestroyFire(world, x - 1, y, z);
}
private void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
private void checkAndDestroyFire(World world, int x, int y, int z) {
if (Materials.isFire(world.getBlockAt(x, y, z).getType())) {
world.getBlockAt(x, y, z).setType(Material.AIR);
}
}
@@ -372,27 +378,27 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int id = event.getBlock().getTypeId();
Material id = event.getBlock().getType();
if (id == 13 && wcfg.noPhysicsGravel) {
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && wcfg.noPhysicsSand) {
if (id == Material.SAND && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && wcfg.allowPortalAnywhere) {
if (id == Material.NETHER_PORTAL && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
@@ -413,8 +419,7 @@ public class WorldGuardBlockListener implements Listener {
Block target = event.getBlock();
World world = target.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && target.getType() == Material.SPONGE) {
if (wcfg.redstoneSponges && target.isBlockIndirectlyPowered()) {
@@ -425,7 +430,7 @@ public class WorldGuardBlockListener implements Listener {
int oy = target.getY();
int oz = target.getZ();
SpongeUtil.clearSpongeWater(plugin, world, ox, oy, oz);
SpongeUtil.clearSpongeWater(BukkitAdapter.adapt(world), ox, oy, oz);
}
}
@@ -437,8 +442,7 @@ public class WorldGuardBlockListener implements Listener {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
@@ -449,12 +453,12 @@ public class WorldGuardBlockListener implements Listener {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
if (sponge.getType() == Material.SPONGE
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
SpongeUtil.clearSpongeWater(BukkitAdapter.adapt(world), ox + cx, oy + cy, oz + cz);
} else if (sponge.getType() == Material.SPONGE
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
SpongeUtil.addSpongeWater(BukkitAdapter.adapt(world), ox + cx, oy + cy, oz + cz);
}
}
}
@@ -466,8 +470,8 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -480,8 +484,7 @@ public class WorldGuardBlockListener implements Listener {
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY,
event.getBlock().getLocation())) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.LEAF_DECAY))) {
event.setCancelled(true);
}
}
@@ -492,15 +495,15 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int type = event.getNewState().getTypeId();
Material type = event.getNewState().getType();
if (event instanceof EntityBlockFormEvent) {
if (((EntityBlockFormEvent) event).getEntity() instanceof Snowman) {
@@ -512,33 +515,33 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (type == BlockID.ICE) {
if (type == Material.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_FORM, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.ICE_FORM))) {
event.setCancelled(true);
return;
}
}
if (type == BlockID.SNOW) {
if (type == Material.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.allowedSnowFallOver.size() > 0) {
int targetId = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedSnowFallOver.isEmpty()) {
Material targetId = event.getBlock().getRelative(0, -1, 0).getType();
if (!wcfg.allowedSnowFallOver.contains(targetId)) {
if (!wcfg.allowedSnowFallOver.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_FALL, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SNOW_FALL))) {
event.setCancelled(true);
return;
}
@@ -550,63 +553,87 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int fromType = event.getSource().getTypeId();
Material newType = event.getNewState().getType(); // craftbukkit randomly gives AIR as event.getSource even if that block is not air
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (Materials.isMushroom(newType)) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.MUSHROOMS, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.MUSHROOMS))) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.GRASS) {
if (newType == Material.GRASS_BLOCK) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.GRASS_SPREAD, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.GRASS_SPREAD))) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.MYCELIUM) {
if (newType == Material.MYCELIUM) {
if (wcfg.disableMyceliumSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.MYCELIUM_SPREAD, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.MYCELIUM_SPREAD))) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.VINE) {
if (Materials.isVine(newType)) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.VINE_GROWTH, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.VINE_GROWTH))) {
event.setCancelled(true);
return;
}
}
handleGrow(event, event.getBlock().getLocation(), newType);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) {
Location loc = event.getBlock().getLocation();
final Material type = event.getNewState().getType();
handleGrow(event, loc, type);
}
private void handleGrow(Cancellable event, Location loc, Material type) {
WorldConfiguration wcfg = getWorldConfig(loc.getWorld());
if (Materials.isCrop(type)) {
if (wcfg.disableCropGrowth) {
event.setCancelled(false);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(loc), (RegionAssociable) null, Flags.CROP_GROWTH))) {
event.setCancelled(true);
return;
}
@@ -619,49 +646,72 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
switch (event.getBlock().getTypeId()) {
case BlockID.ICE:
if (event.getBlock().getType() == Material.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_MELT, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.ICE_MELT))) {
event.setCancelled(true);
return;
}
break;
case BlockID.SNOW:
} else if (event.getBlock().getType() == Material.FROSTED_ICE) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.FROSTED_ICE_MELT))) {
event.setCancelled(true);
return;
}
} else if (event.getBlock().getType() == Material.SNOW) {
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_MELT, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SNOW_MELT))) {
event.setCancelled(true);
return;
}
break;
case BlockID.SOIL:
} else if (event.getBlock().getType() == Material.FARMLAND) {
if (wcfg.disableSoilDehydration) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SOIL_DRY, event.getBlock().getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SOIL_DRY))) {
event.setCancelled(true);
return;
}
break;
} else if (Materials.isCoral(event.getBlock().getType())) {
if (wcfg.disableCoralBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.CORAL_FADE))) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.blockOtherExplosions) {
event.setCancelled(true);
}
}
}
@@ -21,8 +21,10 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.commandbook.InfoComponent;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -43,8 +45,9 @@ public class WorldGuardCommandBookListener implements Listener {
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (plugin.getGlobalStateManager().get(player.getWorld()).useRegions) {
ApplicableRegionSet regions = plugin.getRegionContainer().createQuery().getApplicableRegions(player.getLocation());
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld()).useRegions) {
ApplicableRegionSet regions =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
// Current regions
StringBuilder regionStr = new StringBuilder();
@@ -69,7 +72,7 @@ public class WorldGuardCommandBookListener implements Listener {
if (regions.size() > 0) {
event.addWhoisInformation("Current Regions", regionStr);
}
event.addWhoisInformation("Can build", regions.canBuild(localPlayer));
event.addWhoisInformation("Can build", regions.testState(localPlayer, Flags.BUILD));
}
}
}
@@ -19,24 +19,71 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.*;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.block.BlockState;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wither;
import org.bukkit.entity.WitherSkull;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.minecart.ExplosiveMinecart;
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;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityBreakDoorEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.EntityTransformEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
@@ -72,20 +119,23 @@ public class WorldGuardEntityListener implements Listener {
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
if (block.getTypeId() == BlockID.SOIL) {
if (/* entity instanceof Creature && // catch for any entity (not thrown for players) */
wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
if (block.getType() == Material.FARMLAND && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
return;
}
if (block.getType() == Material.TURTLE_EGG && wcfg.disableCreatureTurtleEggTrampling) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
@@ -96,8 +146,8 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
@@ -106,6 +156,7 @@ public class WorldGuardEntityListener implements Listener {
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
@@ -119,7 +170,10 @@ public class WorldGuardEntityListener implements Listener {
}
if (wcfg.teleportOnVoid && type == DamageCause.VOID) {
BukkitUtil.findFreePosition(player);
localPlayer.findFreePosition();
if (wcfg.safeFallOnVoid) {
localPlayer.resetFallDistance();
}
event.setCancelled(true);
return;
}
@@ -132,7 +186,8 @@ public class WorldGuardEntityListener implements Listener {
if (type == DamageCause.BLOCK_EXPLOSION
&& (wcfg.disableExplosionDamage || wcfg.blockOtherExplosions
|| (wcfg.explosionFlagCancellation
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.OTHER_EXPLOSION, player.getLocation())))) {
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(localPlayer.getLocation(), (RegionAssociable) null, Flags.OTHER_EXPLOSION))))) {
event.setCancelled(true);
return;
}
@@ -143,9 +198,11 @@ public class WorldGuardEntityListener implements Listener {
if (type == DamageCause.BLOCK_EXPLOSION
&& (wcfg.blockOtherExplosions
|| (wcfg.explosionFlagCancellation
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.OTHER_EXPLOSION, defender.getLocation())))) {
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(defender.getLocation()), (RegionAssociable) null, Flags.OTHER_EXPLOSION))))) {
event.setCancelled(true);
return;
}
}
}
@@ -160,20 +217,27 @@ public class WorldGuardEntityListener implements Listener {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof ItemFrame) {
if (checkItemFrameProtection(attacker, (ItemFrame) defender)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof ArmorStand && !(attacker instanceof Player)) {
if (wcfg.blockEntityArmorStandDestroy) {
event.setCancelled(true);
return;
}
}
if (attacker.getType() == Entities.enderCrystalType) {
if (attacker instanceof EnderCrystal) {
// this isn't handled elsewhere because ender crystal explosions don't carry a player cause
// in the same way that creepers or tnt can
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(defender.getWorld());
if (wcfg.useRegions && wcfg.explosionFlagCancellation) {
if (!plugin.getRegionContainer().createQuery().getApplicableRegions(defender.getLocation())
.testState(null, DefaultFlag.OTHER_EXPLOSION)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(defender.getLocation()))
.testState(null, Flags.OTHER_EXPLOSION)) {
event.setCancelled(true);
return;
}
@@ -184,9 +248,6 @@ public class WorldGuardEntityListener implements Listener {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
@@ -222,20 +283,12 @@ public class WorldGuardEntityListener implements Listener {
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(defender.getLocation());
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer) && !(attacker instanceof Tameable)) {
if (!set.testState(localPlayer, Flags.MOB_DAMAGE) && !(attacker instanceof Tameable)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
}
}
}
}
@@ -252,21 +305,21 @@ public class WorldGuardEntityListener implements Listener {
return;
}
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
// Check Mob
if (attacker != null && !(attacker instanceof Player)) {
if (!(attacker instanceof Player)) {
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getRegionContainer().createQuery().getApplicableRegions(defender.getLocation()).allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation()).testState(localPlayer, Flags.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
@@ -285,8 +338,8 @@ public class WorldGuardEntityListener implements Listener {
}
}
if (wcfg.useRegions) {
RegionQuery query = plugin.getRegionContainer().createQuery();
if (!query.testState(defender.getLocation(), (Player) defender, DefaultFlag.GHAST_FIREBALL) && wcfg.explosionFlagCancellation) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (!query.testState(localPlayer.getLocation(), localPlayer, Flags.GHAST_FIREBALL) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
@@ -299,6 +352,10 @@ public class WorldGuardEntityListener implements Listener {
event.setCancelled(true);
return;
}
} else if (defender instanceof ArmorStand && Entities.isNonPlayerCreature(attacker)) {
if (wcfg.blockEntityArmorStandDestroy) {
event.setCancelled(true);
}
}
}
@@ -317,8 +374,8 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
@@ -327,6 +384,7 @@ public class WorldGuardEntityListener implements Listener {
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (type == DamageCause.WITHER) {
// wither boss DoT tick
@@ -336,16 +394,16 @@ public class WorldGuardEntityListener implements Listener {
}
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(defender.getLocation());
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
if (!set.allows(DefaultFlag.MOB_DAMAGE, plugin.wrapPlayer(player))) {
if (!set.testState(plugin.wrapPlayer(player), Flags.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(player)) {
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(localPlayer)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -355,8 +413,8 @@ public class WorldGuardEntityListener implements Listener {
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& helmet != null
&& (helmet.getTypeId() == BlockID.PUMPKIN
|| helmet.getTypeId() == BlockID.JACKOLANTERN)) {
&& (helmet.getType() == Material.CARVED_PUMPKIN
|| helmet.getType() == Material.JACK_O_LANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -380,7 +438,7 @@ public class WorldGuardEntityListener implements Listener {
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
localPlayer.findFreePosition();
event.setCancelled(true);
return;
}
@@ -397,16 +455,14 @@ public class WorldGuardEntityListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(world));
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
if (ent != null) {
ent.remove();
}
ent.remove();
event.setCancelled(true);
return;
}
@@ -456,10 +512,8 @@ public class WorldGuardEntityListener implements Listener {
}
// allow wither skull blocking since there is no dedicated flag atm
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation()).allows(DefaultFlag.GHAST_FIREBALL)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.GHAST_FIREBALL)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -475,6 +529,16 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(block.getLocation()),
(RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.blockList().clear();
event.setCancelled(true);
return;
}
}
}
} else {
// unhandled entity
if (wcfg.blockOtherExplosions) {
@@ -482,9 +546,8 @@ public class WorldGuardEntityListener implements Listener {
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation()).allows(DefaultFlag.OTHER_EXPLOSION)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.OTHER_EXPLOSION)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -496,7 +559,7 @@ public class WorldGuardEntityListener implements Listener {
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
if (wcfg.isChestProtected(BukkitAdapter.adapt(block.getLocation()))) {
event.blockList().clear();
return;
}
@@ -510,8 +573,8 @@ public class WorldGuardEntityListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -551,14 +614,14 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
@@ -578,7 +641,9 @@ public class WorldGuardEntityListener implements Listener {
EntityType entityType = event.getEntityType();
if (wcfg.blockCreatureSpawn.contains(entityType)) {
com.sk89q.worldedit.world.entity.EntityType weEntityType = BukkitAdapter.adapt(entityType);
if (weEntityType != null && wcfg.blockCreatureSpawn.contains(weEntityType)) {
event.setCancelled(true);
return;
}
@@ -586,15 +651,16 @@ public class WorldGuardEntityListener implements Listener {
Location eventLoc = event.getLocation();
if (wcfg.useRegions && cfg.useRegionsCreatureSpawnEvent) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(eventLoc);
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(eventLoc));
if (!set.allows(DefaultFlag.MOB_SPAWNING)) {
if (!set.testState(null, Flags.MOB_SPAWNING)) {
event.setCancelled(true);
return;
}
Set<EntityType> entityTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (entityTypes != null && entityTypes.contains(entityType)) {
Set<com.sk89q.worldedit.world.entity.EntityType> entityTypes = set.queryValue(null, Flags.DENY_SPAWN);
if (entityTypes != null && weEntityType != null && entityTypes.contains(weEntityType)) {
event.setCancelled(true);
return;
}
@@ -609,21 +675,68 @@ public class WorldGuardEntityListener implements Listener {
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatePortal(EntityCreatePortalEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
public void onCreatePortal(PortalCreateEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getWorld());
WorldConfiguration wcfg = cfg.get(world);
switch (event.getEntityType()) {
case ENDER_DRAGON:
if (wcfg.blockEnderDragonPortalCreation) event.setCancelled(true);
break;
if (wcfg.regionNetherPortalProtection
&& event.getReason() == PortalCreateEvent.CreateReason.NETHER_PAIR
&& !event.getBlocks().isEmpty()) {
final RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer()
.get(world);
if (regionManager == null) return;
LocalPlayer associable = null;
if (event.getEntity() instanceof Player) {
associable = plugin.wrapPlayer(((Player) event.getEntity()));
if (WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(associable, world)) {
return;
}
}
BlockVector3 min = null;
BlockVector3 max = null;
for (BlockState block : event.getBlocks()) {
BlockVector3 loc = BlockVector3.at(block.getX(), block.getY(), block.getZ());
min = min == null ? loc : loc.getMinimum(min);
max = max == null ? loc : loc.getMaximum(max);
}
ProtectedCuboidRegion target = new ProtectedCuboidRegion("__portal_check", true, min, max);
final ApplicableRegionSet regions = regionManager.getApplicableRegions(target);
if (!regions.testState(associable, Flags.BUILD, Flags.BLOCK_PLACE)) {
if (associable != null) {
// NB there is no way to cancel the teleport without PTA (since PlayerPortal doesn't have block info)
// removing PTA was a mistake
associable.print("Destination is an a protected area.");
}
event.setCancelled(true);
}
}
// NOTE: as of right now, bukkit doesn't fire this event for this (despite deprecating EntityCreatePortalEvent for it)
// maybe one day this code will be useful
if (event.getEntity() instanceof EnderDragon && wcfg.blockEnderDragonPortalCreation) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityTransform(EntityTransformEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
final EntityType type = entity.getType();
if (wcfg.disableVillagerZap && type == EntityType.VILLAGER
&& event.getTransformReason() == EntityTransformEvent.TransformReason.LIGHTNING) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
if (wcfg.disablePigZap) {
event.setCancelled(true);
@@ -632,8 +745,8 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
@@ -642,17 +755,46 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
RegainReason regainReason = event.getRegainReason();
if (regainReason != RegainReason.REGEN && regainReason != RegainReason.SATIATED) {
return;
}
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && ent instanceof Player
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
BukkitAdapter.adapt(ent.getLocation()),
WorldGuardPlugin.inst().wrapPlayer((Player) ent),
Flags.HEALTH_REGEN)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onFoodChange(FoodLevelChangeEvent event) {
if (event.getItem() != null) return;
HumanEntity ent = event.getEntity();
if (!(ent instanceof Player)) return;
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer((Player) ent);
if (event.getFoodLevel() > player.getFoodLevel()) return;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.useRegions
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
player.getLocation(), player, Flags.HUNGER_DRAIN)) {
event.setCancelled(true);
}
}
/**
@@ -666,25 +808,36 @@ public class WorldGuardEntityListener implements Listener {
Block block = event.getBlock();
Location location = block.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (ent instanceof Enderman) {
if (wcfg.disableEndermanGriefing) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(ent.getWorld()));
if (ent instanceof FallingBlock) {
Material id = event.getBlock().getType();
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
if (id == Material.SAND && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
} else if (ent instanceof Enderman) {
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
} else if (ent.getType() == EntityType.WITHER) {
if (wcfg.blockWitherBlockDamage || wcfg.blockWitherExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(location), (RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.setCancelled(true);
return;
}
}
} else if (/*ent instanceof Zombie && */event instanceof EntityBreakDoorEvent) {
if (wcfg.blockZombieDoorDestruction) {
event.setCancelled(true);
@@ -693,6 +846,16 @@ public class WorldGuardEntityListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntered().getWorld()));
if (wcfg.blockEntityVehicleEntry && !(event.getEntered() instanceof Player)) {
event.setCancelled(true);
}
}
/**
* Checks regions and config settings to protect items from being knocked
* out of item frames.
@@ -702,14 +865,12 @@ public class WorldGuardEntityListener implements Listener {
*/
private boolean checkItemFrameProtection(Entity attacker, ItemFrame defender) {
World world = attacker.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.useRegions) {
// bukkit throws this event when a player attempts to remove an item from a frame
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
// bukkit throws this event when a player attempts to remove an item from a frame
if (!(attacker instanceof Player)) {
if (!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, defender.getLocation())) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(defender.getLocation()), (RegionAssociable) null, Flags.ENTITY_ITEM_FRAME_DESTROY))) {
return true;
}
}
@@ -19,10 +19,14 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.World;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
@@ -69,8 +73,8 @@ public class WorldGuardHangingListener implements Listener {
public void onHangingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
@@ -87,7 +91,7 @@ public class WorldGuardHangingListener implements Listener {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, hanging.getLocation())) {
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(hanging.getLocation()), (RegionAssociable) null, Flags.CREEPER_EXPLOSION))) {
event.setCancelled(true);
return;
}
@@ -98,12 +102,12 @@ public class WorldGuardHangingListener implements Listener {
if (hanging instanceof Painting
&& (wcfg.blockEntityPaintingDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, hanging.getLocation())))) {
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(hanging.getLocation()), (RegionAssociable) null, Flags.ENTITY_PAINTING_DESTROY))))) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame
&& (wcfg.blockEntityItemFrameDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, hanging.getLocation())))) {
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(hanging.getLocation()), (RegionAssociable) null, Flags.ENTITY_ITEM_FRAME_DESTROY))))) {
event.setCancelled(true);
}
}
@@ -19,31 +19,33 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
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.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.GameModeFlag;
import com.sk89q.worldguard.util.Entities;
import com.sk89q.worldguard.util.command.CommandFilter;
import com.sk89q.worldguard.util.profile.Profile;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.TravelAgent;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -55,7 +57,6 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
@@ -74,7 +75,7 @@ import java.util.regex.Pattern;
public class WorldGuardPlayerListener implements Listener {
private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName());
private static final Pattern opPattern = Pattern.compile("^/(?:bukkit:)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private static final Pattern opPattern = Pattern.compile("^/(?:minecraft:)?(?:bukkit:)?(?:de)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private WorldGuardPlugin plugin;
/**
@@ -97,13 +98,15 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
Session session = plugin.getSessionManager().getIfPresent(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().getIfPresent(localPlayer);
if (session != null) {
GameModeFlag handler = session.getHandler(GameModeFlag.class);
if (handler != null && wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(player, player.getWorld())) {
if (handler != null && wcfg.useRegions && !WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer,
localPlayer.getWorld())) {
GameMode expected = handler.getSetGameMode();
if (handler.getOriginalGameMode() != null && expected != null && expected != event.getNewGameMode()) {
if (handler.getOriginalGameMode() != null && expected != null && expected != BukkitAdapter.adapt(event.getNewGameMode())) {
log.info("Game mode change on " + player.getName() + " has been blocked due to the region GAMEMODE flag");
event.setCancelled(true);
}
@@ -114,10 +117,11 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (cfg.activityHaltToggle) {
player.sendMessage(ChatColor.YELLOW
@@ -126,7 +130,7 @@ public class WorldGuardPlayerListener implements Listener {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
if (Entities.isIntensiveEntity(BukkitAdapter.adapt(entity))) {
entity.remove();
removed++;
}
@@ -134,7 +138,7 @@ public class WorldGuardPlayerListener implements Listener {
if (removed > 10) {
log.info("Halt-Act: " + removed + " entities (>10) auto-removed from "
+ player.getWorld().toString());
+ player.getWorld());
}
}
@@ -144,27 +148,37 @@ public class WorldGuardPlayerListener implements Listener {
}
Events.fire(new ProcessPlayerEvent(player));
plugin.getSessionManager().get(player); // Initializes a session
WorldGuard.getInstance().getExecutorService().submit(() ->
WorldGuard.getInstance().getProfileCache().put(new Profile(player.getUniqueId(), player.getName())));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.SEND_CHAT, player.getLocation())) {
player.sendMessage(ChatColor.RED + "You don't have permission to chat in this region!");
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet chatFrom = query.getApplicableRegions(localPlayer.getLocation());
if (!chatFrom.testState(localPlayer, Flags.SEND_CHAT)) {
String message = chatFrom.queryValue(localPlayer, Flags.DENY_MESSAGE);
RegionProtectionListener.formatAndSendDenyMessage("chat", localPlayer, message);
event.setCancelled(true);
return;
}
boolean anyRemoved = false;
for (Iterator<Player> i = event.getRecipients().iterator(); i.hasNext();) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.RECEIVE_CHAT, i.next().getLocation())) {
Player rPlayer = i.next();
LocalPlayer rLocal = plugin.wrapPlayer(rPlayer);
if (!query.testState(rLocal.getLocation(), rLocal, Flags.RECEIVE_CHAT)) {
i.remove();
anyRemoved = true;
}
}
if (event.getRecipients().size() == 0) {
if (anyRemoved && event.getRecipients().isEmpty() && wcfg.regionCancelEmptyChatEvents) {
event.setCancelled(true);
}
}
@@ -173,9 +187,13 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
String hostKey = cfg.hostKeys.get(player.getUniqueId().toString());
if (hostKey == null) {
hostKey = cfg.hostKeys.get(player.getName().toLowerCase());
}
String hostKey = cfg.hostKeys.get(player.getName().toLowerCase());
if (hostKey != null) {
String hostname = event.getHostname();
int colonIndex = hostname.indexOf(':');
@@ -183,7 +201,9 @@ public class WorldGuardPlayerListener implements Listener {
hostname = hostname.substring(0, colonIndex);
}
if (!hostname.equals(hostKey)) {
if (!hostname.equals(hostKey)
&& !(cfg.hostKeysAllowFMLClients &&
(hostname.equals(hostKey + "\u0000FML\u0000") || hostname.equals(hostKey + "\u0000FML2\u0000")))) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"You did not join with the valid host key!");
log.warning("WorldGuard host key check: " +
@@ -209,8 +229,8 @@ public class WorldGuardPlayerListener implements Listener {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
@@ -229,27 +249,21 @@ public class WorldGuardPlayerListener implements Listener {
* @param event Thrown event
*/
private void handleBlockRightClick(PlayerInteractEvent event) {
if (event.isCancelled()) {
if (event.useItemInHand() == Event.Result.DENY) {
return;
}
Block block = event.getClickedBlock();
World world = block.getWorld();
int type = block.getTypeId();
Material type = block.getType();
Player player = event.getPlayer();
@Nullable ItemStack item = event.getItem();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
// Infinite stack removal
if ((type == BlockID.CHEST
|| type == BlockID.JUKEBOX
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.BREWING_STAND
|| type == BlockID.ENCHANTMENT_TABLE)
if (Materials.isInventoryBlock(type)
&& wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
for (int slot = 0; slot < 40; slot++) {
@@ -263,14 +277,14 @@ public class WorldGuardPlayerListener implements Listener {
if (wcfg.useRegions) {
//Block placedIn = block.getRelative(event.getBlockFace());
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
//ApplicableRegionSet placedInSet = plugin.getRegionContainer().createQuery().getApplicableRegions(placedIn.getLocation());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (item != null && item.getTypeId() == wcfg.regionWand && plugin.hasPermission(player, "worldguard.region.wand")) {
if (item != null && item.getType().getKey().toString().equals(wcfg.regionWand) && plugin.hasPermission(player, "worldguard.region.wand")) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (set.canBuild(localPlayer) ? "Yes" : "No"));
player.sendMessage(ChatColor.YELLOW + "Can you build? " + (set.testState(localPlayer, Flags.BUILD) ? "Yes" : "No"));
StringBuilder str = new StringBuilder();
for (Iterator<ProtectedRegion> it = set.iterator(); it.hasNext();) {
@@ -280,12 +294,12 @@ public class WorldGuardPlayerListener implements Listener {
}
}
player.sendMessage(ChatColor.YELLOW + "Applicable regions: " + str.toString());
localPlayer.print("Applicable regions: " + str);
} else {
player.sendMessage(ChatColor.YELLOW + "WorldGuard: No defined regions here!");
localPlayer.print("WorldGuard: No defined regions here!");
}
event.setCancelled(true);
event.setUseItemInHand(Event.Result.DENY);
}
}
}
@@ -296,17 +310,21 @@ public class WorldGuardPlayerListener implements Listener {
* @param event Thrown event
*/
private void handlePhysicalInteract(PlayerInteractEvent event) {
if (event.isCancelled()) return;
if (event.useInteractedBlock() == Event.Result.DENY) return;
Player player = event.getPlayer();
Block block = event.getClickedBlock(); //not actually clicked but whatever
//int type = block.getTypeId();
Material type = block.getType();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (block.getTypeId() == BlockID.SOIL && wcfg.disablePlayerCropTrampling) {
if (type == Material.FARMLAND && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
if (type == Material.TURTLE_EGG && wcfg.disablePlayerTurtleEggTrampling) {
event.setCancelled(true);
return;
}
@@ -315,19 +333,19 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(location);
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
com.sk89q.worldedit.Location spawn = set.getFlag(DefaultFlag.SPAWN_LOC, localPlayer);
com.sk89q.worldedit.util.Location spawn = set.queryValue(localPlayer, Flags.SPAWN_LOC);
if (spawn != null) {
event.setRespawnLocation(com.sk89q.worldedit.bukkit.BukkitUtil.toLocation(spawn));
event.setRespawnLocation(BukkitAdapter.adapt(spawn));
}
}
}
@@ -336,8 +354,8 @@ public class WorldGuardPlayerListener implements Listener {
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
@@ -352,87 +370,58 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
World world = event.getFrom().getWorld();
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(event.getTo());
ApplicableRegionSet setFrom = plugin.getRegionContainer().createQuery().getApplicableRegions(event.getFrom());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (cfg.usePlayerTeleports) {
if (null != plugin.getSessionManager().get(player).testMoveTo(player, event.getTo(), MoveType.TELEPORT)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions && cfg.usePlayerTeleports) {
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getFrom()));
if (event.getCause() == TeleportCause.ENDER_PEARL) {
if (!plugin.getGlobalRegionManager().hasBypass(localPlayer, world)
&& !(set.allows(DefaultFlag.ENDERPEARL, localPlayer)
&& setFrom.allows(DefaultFlag.ENDERPEARL, localPlayer))) {
player.sendMessage(ChatColor.DARK_RED + "You're not allowed to go there.");
event.setCancelled(true);
return;
}
}
try {
if (event.getCause() == TeleportCause.CHORUS_FRUIT) {
if (!plugin.getGlobalRegionManager().hasBypass(localPlayer, world)) {
boolean allowFrom = setFrom.allows(DefaultFlag.CHORUS_TELEPORT, localPlayer);
boolean allowTo = set.allows(DefaultFlag.CHORUS_TELEPORT, localPlayer);
if (!allowFrom || !allowTo) {
player.sendMessage(ChatColor.DARK_RED + "You're not allowed to teleport " +
(!allowFrom ? "from here." : "there."));
event.setCancelled(true);
return;
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
boolean cancel = false;
String message = null;
if (!setFrom.testState(localPlayer, Flags.ENDERPEARL)) {
cancel = true;
message = setFrom.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
} else if (!set.testState(localPlayer, Flags.ENDERPEARL)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
event.setCancelled(true);
return;
}
}
} catch (NoSuchFieldError ignored) {}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPortal(PlayerPortalEvent event) {
if (event.getTo() == null) { // apparently this counts as a cancelled event, implementation specific though
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getTo().getWorld());
if (!wcfg.regionNetherPortalProtection) return;
if (event.getCause() != TeleportCause.NETHER_PORTAL) {
return;
}
if (!event.useTravelAgent()) { // either end travel (even though we checked cause) or another plugin is fucking with us, shouldn't create a portal though
return;
}
TravelAgent pta = event.getPortalTravelAgent();
if (pta == null) { // possible, but shouldn't create a portal
return;
}
if (pta.findPortal(event.getTo()) != null) {
return; // portal exists...it shouldn't make a new one
}
// HOPEFULLY covered everything the server can throw at us...proceed protection checking
// a lot of that is implementation specific though
// hackily estimate the area that could be effected by this event, since the server refuses to tell us
int radius = pta.getCreationRadius();
Location min = event.getTo().clone().subtract(radius, radius, radius);
Location max = event.getTo().clone().add(radius, radius, radius);
World world = event.getTo().getWorld();
ProtectedRegion check = new ProtectedCuboidRegion("__portalcheck__", BukkitUtil.toVector(min.getBlock()), BukkitUtil.toVector(max.getBlock()));
if (wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(event.getPlayer(), world)) {
RegionManager mgr = plugin.getRegionContainer().get(event.getTo().getWorld());
if (mgr == null) return;
ApplicableRegionSet set = mgr.getApplicableRegions(check);
if (!set.testState(plugin.wrapPlayer(event.getPlayer()), DefaultFlag.BUILD)) {
event.getPlayer().sendMessage(ChatColor.RED + "Destination is in a protected area.");
} else if (event.getCause() == TeleportCause.CHORUS_FRUIT) {
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
boolean cancel = false;
String message = null;
if (!setFrom.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = setFrom.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
} else if (!set.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
event.setCancelled(true);
return;
}
}
}
if (null != WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer)
.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), MoveType.TELEPORT)) {
event.setCancelled(true);
return;
}
@@ -443,19 +432,20 @@ public class WorldGuardPlayerListener implements Listener {
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(player, world)) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(player.getLocation());
if (wcfg.useRegions && !WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
Set<String> allowedCommands = set.queryValue(localPlayer, DefaultFlag.ALLOWED_CMDS);
Set<String> blockedCommands = set.queryValue(localPlayer, DefaultFlag.BLOCKED_CMDS);
Set<String> allowedCommands = set.queryValue(localPlayer, Flags.ALLOWED_CMDS);
Set<String> blockedCommands = set.queryValue(localPlayer, Flags.BLOCKED_CMDS);
CommandFilter test = new CommandFilter(allowedCommands, blockedCommands);
if (!test.apply(event.getMessage())) {
player.sendMessage(ChatColor.RED + event.getMessage() + " is not allowed in this area.");
String message = set.queryValue(localPlayer, Flags.DENY_MESSAGE);
RegionProtectionListener.formatAndSendDenyMessage("use " + event.getMessage(), localPlayer, message);
event.setCancelled(true);
return;
}
@@ -463,7 +453,7 @@ public class WorldGuardPlayerListener implements Listener {
if (cfg.blockInGameOp) {
if (opPattern.matcher(event.getMessage()).matches()) {
player.sendMessage(ChatColor.RED + "/op can only be used in console (as set by a WG setting).");
player.sendMessage(ChatColor.RED + "/op and /deop can only be used in console (as set by a WG setting).");
event.setCancelled(true);
return;
}
@@ -19,6 +19,8 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -45,14 +47,14 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
}
}
}
@@ -19,11 +19,15 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Locations;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.util.Locations;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
@@ -32,6 +36,9 @@ import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.stream.Collectors;
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
@@ -55,18 +62,32 @@ public class WorldGuardVehicleListener implements Listener {
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
if (vehicle.getPassenger() == null || !(vehicle.getPassenger() instanceof Player)) return;
Player player = (Player) vehicle.getPassenger();
if (vehicle.getPassengers().isEmpty()) return;
List<Player> playerPassengers = vehicle.getPassengers().stream()
.filter(ent -> ent instanceof Player).map(ent -> (Player) ent).collect(Collectors.toList());
if (playerPassengers.isEmpty()) {
return;
}
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.useRegions) {
// Did we move a block?
if (Locations.isDifferentBlock(event.getFrom(), event.getTo())) {
if (null != plugin.getSessionManager().get(player).testMoveTo(player, event.getTo(), MoveType.RIDE)) {
vehicle.setVelocity(new Vector(0,0,0));
vehicle.teleport(event.getFrom());
if (Locations.isDifferentBlock(BukkitAdapter.adapt(event.getFrom()), BukkitAdapter.adapt(event.getTo()))) {
for (Player player : playerPassengers) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
Location lastValid;
if ((lastValid = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer)
.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), MoveType.RIDE)) != null) {
vehicle.setVelocity(new Vector(0, 0, 0));
vehicle.teleport(event.getFrom());
if (Locations.isDifferentBlock(lastValid, BukkitAdapter.adapt(event.getFrom()))) {
Vector dir = player.getLocation().getDirection();
player.teleport(BukkitAdapter.adapt(lastValid).setDirection(dir));
}
return;
}
}
}
}
@@ -19,12 +19,18 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -54,8 +60,8 @@ public class WorldGuardWeatherListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
@@ -70,8 +76,8 @@ public class WorldGuardWeatherListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (event.toThunderState()) {
if (wcfg.disableThunder) {
@@ -86,21 +92,23 @@ public class WorldGuardWeatherListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (wcfg.disallowedLightningBlocks.size() > 0) {
int targetId = event.getLightning().getLocation().getBlock().getTypeId();
if (wcfg.disallowedLightningBlocks.contains(targetId)) {
if (!wcfg.disallowedLightningBlocks.isEmpty()) {
final Block target = event.getLightning().getLocation().getBlock();
Material targetId = target.getType();
if (targetId == Material.AIR) {
targetId = target.getRelative(BlockFace.DOWN).getType();
}
if (wcfg.disallowedLightningBlocks.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
}
}
Location loc = event.getLightning().getLocation();
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(loc);
if (!set.allows(DefaultFlag.LIGHTNING)) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(loc), (RegionAssociable) null, Flags.LIGHTNING))) {
event.setCancelled(true);
}
}
@@ -19,10 +19,12 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.util.Entities;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
@@ -55,13 +57,13 @@ public class WorldGuardWorldListener implements Listener {
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
int removed = 0;
for (Entity entity : event.getChunk().getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
if (Entities.isIntensiveEntity(BukkitAdapter.adapt(entity))) {
entity.remove();
removed++;
}
@@ -87,8 +89,8 @@ public class WorldGuardWorldListener implements Listener {
* @param world The specified world
*/
public void initWorld(World world) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
@@ -19,12 +19,14 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.config.WorldConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityPotionEffectEvent;
public class WorldRulesListener extends AbstractListener {
@@ -39,17 +41,24 @@ public class WorldRulesListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onSpawnEntity(final SpawnEntityEvent event) {
WorldConfiguration config = getWorldConfig(event.getWorld());
// ================================================================
// EXP_DROPS flag
// ================================================================
if (event.getEffectiveType() == EntityType.EXPERIENCE_ORB) {
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
if (config.disableExpDrops) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionEffect(EntityPotionEffectEvent event) {
if (event.getCause() == EntityPotionEffectEvent.Cause.CONDUIT) {
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (config.disableConduitEffects) {
event.setCancelled(true);
}
}
}
}
@@ -20,9 +20,9 @@
package com.sk89q.worldguard.bukkit.listener.debounce;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.guavabackport.cache.CacheBuilder;
import com.sk89q.guavabackport.cache.CacheLoader;
import com.sk89q.guavabackport.cache.LoadingCache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
@@ -75,7 +75,7 @@ public class EventDebounce<K> {
}
public static <K> EventDebounce<K> create(int debounceTime) {
return new EventDebounce<K>(debounceTime);
return new EventDebounce<>(debounceTime);
}
public static class Entry {
@@ -20,9 +20,9 @@
package com.sk89q.worldguard.bukkit.listener.debounce.legacy;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.guavabackport.cache.CacheBuilder;
import com.sk89q.guavabackport.cache.CacheLoader;
import com.sk89q.guavabackport.cache.LoadingCache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
Loaded 100 of 442 files, more files were not shown because too many files have changed in this diff. Show more