Compare commits

...
658 Commits
Author SHA1 Message Date
Joo200 ab48a66237 Merge branch 'refs/heads/version/7.0.x'
# Conflicts:
#	buildSrc/src/main/kotlin/GradleExtras.kt
#	buildSrc/src/main/kotlin/LibsConfig.kt
#	buildSrc/src/main/kotlin/PlatformConfig.kt
#	gradle.properties
#	worldguard-libs/bukkit/build.gradle.kts
2024-09-16 20:08:34 +02:00
wizjany d9716a5bd8 Ignore arrow combustion.
Closes #2144.
2024-09-13 14:29:18 -04:00
wizjany a0e397e57f Use more snapshot-less holders on Paper.
This is already past the debounce so in theory it's not getting hit *often*, but I guess if it's really slow it'll still show up.
2024-09-13 14:15:32 -04:00
wizjany 02dc89b224 Bump to snapshot. 2024-09-13 11:58:55 -04:00
wizjany 829a4a42df Release 7.0.12. 2024-09-13 11:58:22 -04:00
wizjany 830472d36e Revert previous changes to explosion event handling.
Event abstraction sucks and everything needs rewriting.
2024-09-13 11:46:06 -04:00
wizjany 03aac83f4c Match explosion flag coverage with EntityListener. 2024-09-13 10:00:48 -04:00
wizjany fb88d56646 Bump to SNAPSHOT for dev.
Also update the changelog.
2024-09-09 16:56:05 -04:00
wizjany 068ad680fc Release 7.0.11. 2024-09-09 16:24:43 -04:00
ploppypersonandwizjany cb011a88cf Add moisture-change flag (#1879) (#2096)
* Create and implement moisture-change flag

* Fix imports

* Add comment

* Actually read the value from config.

Closes #1879 

---------

Co-authored-by: wizjany <wizjany@gmail.com>
2024-09-09 15:43:58 -04:00
wizjany 0f3ea5045e Merge pull request #2115 from EngineHub/feature/fix-breeze-stuff
Optimize and cleanup explosion events from entities

Fixes #2099 and #2097
2024-09-08 17:26:31 -04:00
wizjany 679b56948f Split wind charge into breeze/player flags.
Player flag is build-checked (default false) and breeze flag is not (default true).

Having multiple flags is ugly but if we need every bit of behavior to be manipulable this is the only way.
2024-09-08 16:46:50 -04:00
Joo200 9dd7d7c03e Fix wind-charge-burst flag for player knockback 2024-09-08 14:56:08 -04:00
Joo200 afb619d2ac Fix breeze damage flags 2024-09-08 14:56:04 -04:00
wizjany b73a0a7179 Check mob-damage for potion splashes from e.g. witches.
Note that bypass bypasses this if the player with bypass is the target of the potion, but only for the player with bypass.

Fixes #2134.
2024-09-08 13:40:13 -04:00
wizjany 2ea50689b9 Workaround books no longer sending change block for lecterns.
Fixes #2124.
2024-09-08 12:51:00 -04:00
wizjany 70d225ef2f Split chest boat ride/open. 2024-09-08 12:45:08 -04:00
wizjany aa46529ecb Extend use flag to all (trap)doors.
There's no tag which has wood+copper, but iron are not interactable anyway.

Relates to #2130.
2024-09-08 12:45:07 -04:00
Joo200 8ffc81ad74 Fix NPE for teleport events without target location
Fixes #2111
2024-07-22 21:42:44 +02:00
wizjany 16ea4625c9 Merge pull request #2100 from aurorasmiles/feat/buildlogic
Port buildlogic from WorldEdit
2024-07-21 23:30:40 -04:00
wizjany ca49458a44 A bit of cleanup.
Definitely did not accidentally make a 40MB jar halfway through.
2024-07-21 23:26:45 -04:00
aurora 574921089b Port build-logic from WorldEdit 2024-07-21 23:17:21 -04:00
CyberFlame c6fbfb87a3 remove double space 2024-07-05 17:02:51 +02:00
wizjany fa357f4681 Back to snapshot.
Idk why we even to this for betas, they're not getting a maven release.
2024-06-26 18:58:10 -04:00
wizjany a801a9d67a Release 7.0.11-beta1. 2024-06-26 18:50:12 -04:00
1bfae45484 Merge pull request #2089 from EngineHub/feat/mc-1.21
* Fix compilation for MC 1.21. Nothing tested yet.

* Update Materials.java with 1.21 tags and materials

* Fix ItemStack conversion on block place on MC 1.21 (#2093)

* Fix ItemStack conversion on block place

This issue is present in 1.21 because some materials do not convert 1:1 to item types.
This throws an exception in the ItemStack constructor.
Example: WALL_TORCH is a valid block but not a valid item, only TORCH is a valid item.

So, use the item in hand instead, creating a copy with quantity set to 1, for issueing the
use item event.

* Use ItemStack as-is.

Closes #2092.

* Fix ItemStack conversion for spigot compatibility

* Special handling for WindCharges

* Do not call as a bulk event, because it has to check every blocks type

* WindCharge -> AbstractWindCharge

* Fix UseBlockFlag for multiple uses at the same time, add windburst-flag

* Cleanup code

* Handle vaults as use, crafters as chest-access.

---------

Co-authored-by: Joo200 <github@joo200.de>
Co-authored-by: Lennart <1535717+lenis0012@users.noreply.github.com>
Co-authored-by: Brokkonaut <hannos17@gmx.de>
2024-06-26 18:48:35 -04:00
wizjany b269d7e264 Handle vaults as use, crafters as chest-access. 2024-06-26 18:17:55 -04:00
Joo200 af645ea2e4 Cleanup code 2024-06-26 22:34:29 +02:00
Joo200 a5ea5115f9 Fix UseBlockFlag for multiple uses at the same time, add windburst-flag 2024-06-26 22:30:33 +02:00
Brokkonaut 83298796ab WindCharge -> AbstractWindCharge 2024-06-26 21:39:21 +02:00
Brokkonaut 8aa37e389d Do not call as a bulk event, because it has to check every blocks type 2024-06-26 21:39:21 +02:00
Brokkonaut 887f3bfaec Special handling for WindCharges 2024-06-26 21:39:21 +02:00
Joo200 6898ad8674 Fix ItemStack conversion for spigot compatibility 2024-06-22 15:08:10 +02:00
Lennartandwizjany 7783e9ae3b Fix ItemStack conversion on block place on MC 1.21 (#2093)
* Fix ItemStack conversion on block place

This issue is present in 1.21 because some materials do not convert 1:1 to item types.
This throws an exception in the ItemStack constructor.
Example: WALL_TORCH is a valid block but not a valid item, only TORCH is a valid item.

So, use the item in hand instead, creating a copy with quantity set to 1, for issueing the
use item event.

* Use ItemStack as-is.

Closes #2092.

---------

Co-authored-by: wizjany <wizjany@gmail.com>
2024-06-19 12:00:35 -04:00
Joo200 2bd426baf8 Update Materials.java with 1.21 tags and materials 2024-06-17 20:00:03 +02:00
wizjany 27f009594a Fix compilation for MC 1.21. Nothing tested yet. 2024-06-16 21:48:35 -04:00
Joni Aromaa ead1e1b77c Fix checking bypass on initialize (#2082)
* Fix checking bypass on initialize

* Add SessionManager#createSession back as deprecated
2024-05-24 10:48:08 -04:00
auroraandWyatt Childers 8b7729e0e8 Fix silent flag for gameplay commands (#2081)
* Fix silent flag for gameplay commands

This issue has been fixed in CommandBook with
https://github.com/EngineHub/CommandBook/commit/644803182ed1765a9862d0a0cd0d3763d399efee
but never in WorldGuard.

Co-authored-by: Wyatt Childers <DarkArc@users.noreply.github.com>

* codestyle
2024-05-23 13:05:29 -04:00
Joo200 d6ef5e9398 Remove adventure snapshot repository 2024-05-17 18:05:37 +02:00
wizjany 6f5501f7be Bump to snapshot. 2024-05-14 18:14:06 -04:00
wizjany d9424b1c71 Release 7.0.10. 2024-05-14 18:11:53 -04:00
aurora 65431c7df8 Fix fire placement by blocks when fire-spread is set to deny
Fixes #2070
2024-05-13 20:27:34 +02:00
Joo200 aa254c80e0 Merge branch 'refs/heads/version/7.0.x'
# Conflicts:
#	buildSrc/build.gradle.kts
2024-05-03 19:57:42 +02:00
Joo200 2f93b26be0 Update dependencies to 1.20.6 2024-05-03 19:57:10 +02:00
wizjany 6bbf49314d Merge pull request #2075 from EngineHub/feature/1.20.5
Update WorldGuard to 1.20.5
2024-05-02 12:12:15 -04:00
Madeline Miller f6a0a0b415 Add outline to logo SVG akin to WorldEdit and CraftBook 2024-05-01 23:08:16 +10:00
Joo200 4ad11151fe Fix compilation for 1.20.5 2024-04-28 15:39:15 +02:00
Joo200 c29edf7467 Fix Deprecations from WorldEdit 7.3.0 2024-04-28 15:36:52 +02:00
Joo200 da3c81a88d Update dependencies to 1.20.5 and jdk 21 2024-04-28 15:32:32 +02:00
Joo200 c65dd83a7e Don't show particles for denied interact events with dripleaf and redstone ores 2024-04-07 22:04:00 +02:00
Joo200 694195435d Bump Versions 2024-04-07 22:02:57 +02:00
Madeline Miller 0d824d375b Add a Paper fast-path for DoubleChest#getLeftSide when possible 2024-03-31 12:28:53 -04:00
aromaa c7319f10dc Bump up respawn event priority to monitor 2023-09-11 21:25:47 -04:00
Joo200 c2b95f59a8 Paper only: Protect sign modifications as building 2023-08-22 14:34:52 +02:00
Joo200 5fa6f2a858 Update paper-api and spigot-api dependencies to 1.20.1 2023-08-22 14:34:26 +02:00
Joo200 0a9eb447d6 store custom domains thread safe, improve api usability 2023-08-20 11:06:36 +02:00
Joo200 02a8fd4c17 Merge remote-tracking branch 'origin/version/7.0.x'
# Conflicts:
#	gradle.properties
2023-08-14 14:21:50 +02:00
wizjany 3201cee1b7 Bump to snapshot. 2023-07-31 20:12:56 -04:00
wizjany 16a3c85005 Release 7.0.9. 2023-07-31 20:11:06 -04:00
Joo200 5934e49489 Fix changed event for copper-fade flag 2023-07-30 18:34:12 +02:00
Joo200 58fbb6f008 Remove Support for 1.19 2023-07-30 18:20:02 +02:00
Joo200 fba8333de3 Fix backwards compatibility with 1.19.4 2023-06-21 22:20:42 +02:00
Joo200 8cbce96a2c Merge branch 'version/7.0.x' 2023-06-18 18:47:29 +02:00
Madeline Miller fffb0c1f98 Bump to snapshot 2023-06-16 21:01:49 +10:00
Madeline Miller 223b80c590 Release 7.0.9-beta1 2023-06-16 20:59:43 +10:00
Joo200 853631139d Update Protections to 1.20
* add new materials
* add protections for sniffer eggs
* add protection for signs
2023-06-16 09:50:37 +02:00
Joo200 c61e9f1fe0 Update Readme to use https and Java 17 2023-06-16 09:50:37 +02:00
Joo200 64ccda4615 deps: Update WorldEdit to 7.2.14 2023-06-16 09:50:37 +02:00
Joo200 16887c8540 deps: Update Paper to 1.20, snakeyml to 2.0 2023-06-16 09:50:37 +02:00
Joo200 2c448f1ba2 deps: Update gradle to 8.1.1 2023-06-16 09:50:37 +02:00
wizjany c0cbe27efc yaml ctors 2023-06-08 15:08:05 -04:00
Joo200 bb3fdcc880 Renamed InvalidFlagFormat to InvalidFlagFormatException 2023-06-04 18:55:01 +02:00
JOO200 8d5953a550 apidomains: Added custom domains to WorldGuard
This change allows third party plugins to dynamically add custom domains to WorldGuard.
2023-06-04 18:55:01 +02:00
Joo200 4a26e306b6 Consider the summon command as plugin spawning 2023-05-31 13:26:05 +02:00
wizjany 129ae6c971 Merge branch 'version/7.0.x'
# Conflicts:
#	gradle.properties
2023-05-27 13:49:05 -04:00
wizjany 44d0735412 Bump to snapshot. 2023-05-27 13:41:49 -04:00
wizjany 33cdb4a6a8 Release 7.0.8 2023-05-27 13:39:01 -04:00
wizjany feb548aa84 Check movement on AbstractHorse instead of Horse.
Not tested cuz I don't know how to enable camels, but in theory this should work for that.
2023-05-16 17:04:28 -04:00
wizjany 961461c23c Protect against allay pickups and modification.
Closes #1923.
2023-05-16 17:02:19 -04:00
wizjany ad6d5af592 Treat tameables with offline owners as unknown causes.
Paper-only.

Closes #1900.
2023-05-16 16:15:57 -04:00
wizjany 7ae7a04721 Make region wand act more like /rg info.
Addresses the part that #1534 and #1817 missed.
2023-05-16 15:25:52 -04:00
wizjany 40adfe9cef Add dragon egg teleporting to build protection.
Closes #1977.
2023-05-16 14:22:47 -04:00
Joo200 78498491dd Remove timings for third-party session handlers
Reverted MR #1717
2023-04-09 21:27:13 -04:00
stonar96 ca636d20af Fix NPE when non-player entities create new nether portals (#1995)
* Fix NPE when non-player entities create new nether portals

* Fix flag checking for portal create event

* Use failed load region set

* Clean up
2023-04-09 21:25:44 -04:00
Joo200 b67fd01ebd Merge branch 'version/7.0.x'
# Conflicts:
#	buildSrc/src/main/kotlin/Versions.kt
#	gradle/wrapper/gradle-wrapper.jar
#	gradle/wrapper/gradle-wrapper.properties
#	gradlew.bat
#	worldguard-core/build.gradle.kts
2023-03-26 15:17:06 +02:00
Joo200 bddfbdd353 gradle: updated wrapper to gradle 8.0.2 2023-03-26 15:14:10 +02:00
JOO200 ece376a69e Improve NPC handling in WorldGuard's listeners (#1988)
* fix: added more npc checks in listeners
* Do not listen to events from NPCs such as Citizens. Don't handle NPCs as players.
* replaced hasMetaData calls by Entities utilities class
2023-03-23 18:58:48 +01:00
wizjany 1e81a91d4d Bump squirrelid, remove workaround. 2023-03-23 11:47:02 -04:00
JOO200 216f95f87c Merge pull request #1989 from EngineHub/feature/copper-fade-flag
Add copper-fade flag to WorldGuard
2023-03-23 15:05:53 +01:00
JOO200 ca6e228f61 Merge pull request #1973 from EngineHub/feat/datapackreport
Add DataPack Report to track active DataPacks
2023-03-23 14:53:06 +01:00
Joo200 fd1cb1e4bd flags: added copper-fade flag to prevent oxidizing copper 2023-03-19 16:56:46 +01:00
Joo200 8c8a8092b5 deps: updated Paper repository to new url, updated bstats to 3.0.1 2023-03-12 16:50:21 +01:00
Maddy Miller 1729e5e3d6 Add additional holder snapshot bypasses for performance (#1978)
* Add additional holder snapshot bypasses for performance

* Extra optimisation - cuts lookups of block data in the world by half
2023-01-19 20:28:54 +10:00
Madeline Miller 46dfb69fb1 Use updated PaperLib for InventoryHolder optimisation 2023-01-05 21:28:13 +10:00
Joo200 9ceecf5d3a Add DataPack Report to track active DataPacks 2022-12-27 13:39:35 +01:00
Maddy Miller 20044a72d3 fix: re-enable no snapshot inventories (#1972) 2022-12-26 10:29:26 +10:00
JOO200 8bc7ff49ab Merge pull request #1971 from EngineHub/version/1.19.3
Update to Minecraft 1.19.3
2022-12-19 11:01:20 +01:00
Joo200 6f749b058b Restore 1.19.2 compatibility 2022-12-09 16:37:04 +01:00
Joo200 91380a8316 Updated wrapper 2022-12-09 13:26:02 +01:00
Joo200 ba55cc79c2 Update to Minecraft 1.19.3 2022-12-09 13:23:57 +01:00
Joo200 62be386626 Merge branch 'version/7.0.x' 2022-11-27 10:52:54 +01:00
aromaa cb100bb797 Improve compatibility with the new onClearValue 2022-09-20 09:07:27 -04:00
Joo200 741f9e231b Merge branch 'version/7.0.x'
# Conflicts:
#	buildSrc/build.gradle.kts
#	buildSrc/src/main/kotlin/PlatformConfig.kt
#	buildSrc/src/main/kotlin/Versions.kt
2022-09-19 11:56:50 +02:00
Joni Aromaa bd1d772faa Introduce uninitialize for sessions (#1940)
* Introduce uninitialize for sessions

* Add FlagValueChangeHandler#onClearValue
2022-09-18 11:18:08 -04:00
wizjany f1f1e8aa7d Remove command reg delay for CommandBook compat.
This may break said compat but I doubt anyone is using it anyway.

Fixes #1943.
2022-08-28 10:15:49 -04:00
wizjany 598c441718 Back to snapshot.
Also update changelog
2022-07-27 21:28:09 -04:00
wizjany cbb2ba7216 Release 7.0.8 beta 1. 2022-07-27 21:15:21 -04:00
dordsor21 e756d127c5 Account for possible world nullability for Entity#getOrigin Location 2022-07-27 21:15:31 -04:00
Joo200 0d2ed8205f Properly protect chest_boats as vehicles 2022-07-07 21:04:44 +02:00
JOO200 6efdb1089e Fix Report for Spigot based servers
Bukkit.spigot().getSpigotConfig() is the paper implementation, it's not available on Non-Paper servers
2022-06-21 20:44:30 +02:00
wizjany 4a21bf43e7 Check if InventoryHolder BlockState is placed.
Closes #1903.
2022-06-14 11:31:24 -04:00
JOO200 3a181a230f Tidy up Materials.java, added missing effect type, removed todo for paper only 2022-06-14 11:25:06 -04:00
JOO200 857f7468d8 Add Sculk Growth Flag and options to disable sculk growths 2022-06-14 11:25:06 -04:00
JOO200 f8e8d0f01e Plugin Version to 1.19, cleanup from Materials, added 1.19 Materials 2022-06-14 11:25:06 -04:00
JOO200 23521858fd Bumped versions: Minecraft to 1.19 and JDK 17 2022-06-14 11:25:06 -04:00
JOO200 0fddd2a573 Fixed Typo in CommandException 2022-04-26 18:26:07 +02:00
JOO200 85dd012b85 Improvement and Cleanup Domain view for /region info
* Don't suggest the uuids to the command line, copy them to the clipboard instead
* Tidy up the hover events and added hints to copy uuids
2022-04-09 11:46:54 +02:00
wizjany dc23af7947 Skip lookups on claim.
Claim hasn't allowed user-input for ages, so no need to resolve anything.
2022-04-05 12:23:32 -04:00
JOO200 b698941378 Append OnlineMode server information to ServerReport (#1891) 2022-04-03 16:35:34 -04:00
wizjany 271b32aa1d Default chest-protection.disable-off-check to true.
Fixes #1890.
2022-03-24 10:01:17 -04:00
wizjany 938f0c3b66 Handle all the amethyst growth.
Fixes #1889.
2022-03-20 08:26:41 -04:00
wizjany bc63119373 Fix publish. 2022-03-12 17:32:40 -05:00
wizjany 3549f04a33 Build script updates.
Bump gradle. Copy a bunch from WE. Hopefully nothing breaks.
2022-03-12 17:21:50 -05:00
wizjany 216b061172 Fix class source validator on spigot. 2022-03-06 08:59:44 -05:00
wizjany 27dca2b506 Bump to snapshot. 2022-03-03 15:05:52 -05:00
wizjany 79a3b70d8d Release 7.0.7. 2022-03-03 14:21:45 -05:00
wizjany cf69425153 Don't cancel potion splashes with no targets. 2022-03-03 07:59:00 -05:00
wizjany e2fe770e6f Disregard that, definitely need to duplicate. 2022-03-01 18:27:45 -05:00
wizjany 7e06088c1a Switch to WE's ClassSourceValidator.
Since it's (being) fixed there and no need to duplicate any more.
2022-02-27 19:25:58 -05:00
wizjany f9d1c2d4e0 Fix some errors in config loading.
Technically removing a nonexistant property should be fixed in WE's yaml utils but eh.
2022-02-27 17:51:52 -05:00
wizjany f883899cfe Add deprecation warnings.
Also remove the nodes from config if unused.
2022-02-27 16:34:27 -05:00
wizjany de386fb4d8 Provisional changelog for 7.0.7. 2022-02-26 19:04:13 -05:00
wizjany 660f9ffa0d Use deny-message for nether portal protection.
Closes #1882.
2022-02-26 18:49:35 -05:00
wizjany e05d42371f Protect modification of candles and cake as building.
Closes #1880.
2022-02-26 18:43:04 -05:00
JOO200 dca0515104 Optimize Region List and Region Teleport commands (#1868)
* Optimized command usage for /rg list and /rg teleport:
* added a flag to the teleport command to teleport the actor to the center of the region
* added a flag to the list command to filter the regions for special ids
* added a flag to the list command to get regions intersecting your selection

* Fixed wrong pagination in RegionLister
2022-01-23 13:03:40 -05:00
wizjany 4abf971cf6 Add red sand to sand physics.
This option is still at the mercy of bukkit api and might still not work ¯\_(ツ)_/¯
2022-01-16 11:13:18 -05:00
wizjany 875a6fc827 Add space in an error message. 2022-01-16 11:13:15 -05:00
JOO200 3cb4abdbf7 Updated amount of modules, Windows command prompt and outdated hints 2022-01-08 21:23:11 +01:00
JOO200 4caf0afb38 Add COMPILING.md and set Java Version to 16 2022-01-08 21:03:11 +01:00
JOO200 054a73416b Update Java-Version in README.md to Java 17 2022-01-07 13:17:54 +01:00
Cristobal Lopez b59da5992f Allows claimed regions to inherit from a template region (#1864)
* Allows claimed regions to inherit from a template region

* Replace template-when-claiming with set-parent-on-claim

* Make the set-parent-on-claim option check secure
2022-01-02 10:07:00 -05:00
wizjany 46251f5ffa Don't check bypass for offline players.
This is someone else's problem now (╯°□°)╯︵ ┻━┻
2022-01-01 20:08:16 -05:00
wizjany 98bef4e0ab Remove extra import. 2021-12-31 10:55:51 -05:00
JOO200 f1c8649f9a Improve Checks for LightningStrikes (fixes #1845) 2021-12-31 10:55:51 -05:00
JOO200 aad698af84 Update Paper and Spigot to 1.17.1 2021-12-31 10:55:51 -05:00
JOO200 ad7ecbaefe Exclude paper-api from squirrelid dependency (Compilefix for removed maven mirrors) 2021-12-30 20:41:57 +01:00
wizjany 81750e191d Add /rg migrateheights. (#1857)
Closes #1856.
2021-12-02 15:44:25 -05:00
wizjany 703146bc18 Update guava to match MC 1.18 guava. 2021-11-30 20:42:54 -05:00
JOO200 2541483ebc Fixed invalid label 2021-11-25 22:00:40 +01:00
JOO200 0a601dbc28 Improved Bug Report and Feature Request Template 2021-11-25 21:59:46 +01:00
stonar96 f55802c176 Make cause known if origin can be used (#1838) 2021-11-25 12:33:43 -05:00
wizjany a0922cb467 Add rock-growth flag.
Handles amethyst and dripstone.

Closes #1855.
2021-11-25 12:32:24 -05:00
wizjany fb9705e4f0 Update gradle.
Getting ready for java 17.
2021-11-25 11:27:00 -05:00
JOO200 9b665136d0 Fix Blacklist log entry not by player results in NPE (#1837) 2021-09-25 13:22:33 +02:00
wizjany efac79fd38 Bump to 7.0.7-SNAPSHOT. 2021-09-16 18:51:54 -04:00
wizjany 1cff55f355 Release 7.0.6. 2021-09-16 18:45:05 -04:00
wizjany f4fb78c7f5 Changelog for 7.0.6. 2021-09-16 18:44:42 -04:00
wizjany 56086b0878 Protect light from everything.
Thanks Mojang.
2021-09-16 14:54:36 -04:00
wizjany 51fa25dd03 Protect light from light.
Closes #1828.
2021-09-13 19:12:54 -04:00
wizjany 5b0fdb6801 Include GLOW_ITEM_FRAME in item-frame-rotation flag.
Closes #1832.
2021-09-13 18:57:33 -04:00
stonar96 cb69ab73a7 Fix perms NPE 2021-08-31 16:49:40 -04:00
stonar96 5a6b6eb81b Use QueryOption.SORT for region commands (#1817) 2021-08-22 10:14:40 -04:00
stonar96 75774dbbb0 Fix redefinition of parent regions (#1814) 2021-08-15 17:19:01 -04:00
wizjany fe0fd17d37 Cover additional case for blacklist on-equip. 2021-08-15 11:06:27 -04:00
stonar96 5e702f80a6 Add inheritance for all flags (#1787) 2021-08-08 23:00:02 -04:00
Wyatt Childers 0165175a2e Additionally block other explosion if the defender is a block like entity to be consitent with "block" explosion protections (#1812) 2021-08-08 22:58:34 -04:00
wizjany 821c3e689e Convert listeners to use AbstractListener and add shortcuts to get config. (#1808)
Closes #1780.
2021-08-08 22:58:22 -04:00
stonar96andwizjany 4644268214 Fix member inheritance for non-player associables (#1804)
* Add options to query region sets unsorted and without parents

* Fix member inheritance for non-player associables

* Add member inheritance for non-player associables

* Rename Option to QueryOption, remove functional definitions, bit of cleanup.

Co-authored-by: wizjany <wizjany@gmail.com>
2021-08-08 22:58:09 -04:00
wizjany c81f5892eb Add jsr305 back for annotations.
Blame those pesky WorldEdit devs breaking our builds :^)
2021-08-02 13:21:33 -04:00
LoaiDev 88854592ce Fix handlers order when registering one with after.
I am not sure exactly if this is the source of the problem, but when i tried registering my handlers using ExitFlag.FACTORY as "after" like how the javadocs said it, it seemed that my handler was running before the ExitFlag handler which means mine will run even if ExitFlag returns false. I used null as after and it worked then. Maybe i understand the "after" incorrectly but in my mind my customHandler should run after the "after" not the other way around if that makes sense. Let me know if I didn't undertstand it correctly.
Sorry for my english!
2021-08-01 16:59:56 -04:00
wizjany 8efc2e6539 Revert "Add member inheritance for non-player associables"
This reverts commit b1cd1303d1.
2021-07-25 23:31:44 -04:00
stonar96 b1cd1303d1 Add member inheritance for non-player associables 2021-07-25 10:06:09 -04:00
wizjany c98f9eda7e Check all effects for lingering potion clouds.
Fixes #1797.
2021-07-24 11:36:25 -04:00
JOO200 682942b965 Added NPE error message and javadoc hint for WorldGuard.getPlatform 2021-07-15 19:48:34 +02:00
JOO200 7e817c3330 Protect signs against usage of (glowing) ink sac 2021-07-10 11:09:05 +02:00
wizjany 5302bcb132 Changelog for 7.0.6 beta 1. 2021-07-07 10:17:08 -04:00
stonar96 bcac63dcaa Fix regions in negative heights (#1792) 2021-07-07 10:17:08 -04:00
JOO200 37906c0fc4 Added use-dripleaf flag, Handle Deepslate Redstone Ore correctly 2021-07-07 10:17:08 -04:00
wizjany 6879f10de6 Fix crop growth config option. 2021-07-07 10:17:08 -04:00
JOO200 7155ef5833 Protect cave vines and glow berries correctly 2021-07-07 10:17:08 -04:00
JOO200 e2f775c952 Fixed wrong dependencies, removed not needed repository 2021-07-07 10:17:08 -04:00
JOO200 c5dad7476d Compare items for /stack with ItemStack.isSimilar 2021-07-07 10:17:08 -04:00
JOO200 4dfb9bea38 Switch back dependency from Spigot to Paper 2021-07-07 10:17:08 -04:00
JOO200 7436d5064e Fixed incorrectly shaded squirrelid 2021-07-07 10:17:08 -04:00
JOO200 621c1289b3 Bump squirrelid to 0.3.0, Deprecated PaperProfileServer (replaced by squirrelid) 2021-07-07 10:17:08 -04:00
JOO200 093e282e13 relocate bstats like worldedit 2021-07-07 10:17:08 -04:00
JOO200 2958c2526c Shade correctly bstats 2021-07-07 10:17:08 -04:00
wizjany d21ee98624 Re-add shade config, fix some other gradle black magic. 2021-07-07 10:17:08 -04:00
wizjany dd90fa21c7 Cover item dispense behaviors.
Depends on spigot throwing events.
2021-07-07 10:17:08 -04:00
JOO200 34ed6175e5 Bump api version to 1.17 2021-07-07 10:17:08 -04:00
JOO200 0818b3c262 Update to Java 16, Gradle 7.0.2 and Bstats 2.1.0 2021-07-07 10:17:08 -04:00
JOO200 04541ed5a6 Updated build environment, switched to Jupiter Unit Tests 2021-07-07 10:17:08 -04:00
JOO200 f17f1fc8c8 bump travis-ci to jdk11 2021-07-07 10:17:08 -04:00
JOO200 9defab65d1 Fix protections for copper and rooted dirt 2021-07-07 10:17:08 -04:00
JOO200 a225d1b2d3 Added 1.17 materials 2021-07-07 10:17:08 -04:00
JOO200 bcab33c12c Updated dependencies and gradle 2021-07-07 10:17:08 -04:00
JOO200 3cb83465d1 Update dependencies to 1.17 2021-07-07 10:17:08 -04:00
wizjany 32d16a7eaa Bump to snapshot. 2021-06-07 23:03:37 -04:00
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
wizjany f147402d30 Release 6.2 and bump. 2016-11-30 14:12:18 -05:00
wizjany 8e35db0f35 Retain backwards compatibility for the LingeringPotion event listener. 2016-11-29 01:35:21 -05:00
wizjany 9b2eff0a71 Really remove construct flag. 2016-11-27 20:04:43 -05:00
wizjany 104cdc023d Add a method to unregister handlers. 2016-11-27 20:00:46 -05:00
wizjany deb283c44b Remove construct flag.
It's been deprecated for ages and is a strict subset of build flag functionality.
Also deprecate unused flags. They can be re-added by plugins that need them now.
2016-11-27 18:42:22 -05:00
wizjany 324e90c68a Add 1.11 materials. 2016-11-23 22:17:26 -05:00
wizjany c60502ffd8 Fix entity combustion in regions always getting cancelled.
Note that this technically might lead to some inaccuracies if
entity is on a region boundary, but requires server fix.
Fixes WORLDGUARD-3758, WORLDGUARD-3770.
2016-11-20 02:32:42 -05:00
wizjany 26e59955ed Handle LingeringPotions as their own event.
potion-splash flag should now filter them when denied.
Fixes WORLDGUARD-3765.
2016-11-15 21:21:23 -05:00
filoghost 4746e95249 Fix Materials.ARMOR_STAND being null in 1.8. (#356)
In 1.8 Materials.ARMOR_STAND is null because END_CRYSTAL throws NoSuchFieldError and in the catch block ARMOR_STAND is set to null. This causes side effects such as players being able to place armor stands in protected regions.
2016-11-10 23:32:25 -05:00
wizjany 9cafb07e4d Protect entities from endercrystal explosions using explosionFlagCancellation setting.
Should be more consistent with other explosion flags (tnt, creepers) now.
Improves fix for WORLDGUARD-2620.
2016-08-24 18:22:43 -04:00
wizjany b2b0fe65c6 Revert "Add frosted ice to ice-melt flag."
Re-Un-Fixes WORLDGUARD-3745 because apparently this isn't what was
requested.
2016-08-18 03:50:31 -04:00
wizjany 06e6ce589b Add frosted ice to ice-melt flag.
Fixes WORLDGUARD-3745.
2016-08-13 16:57:26 -04:00
wizjany 12fc1438c2 Add explicit ender crystal protection.
Fixes WORLDGUARD-2620.
2016-08-08 10:39:40 -04:00
wizjany e5e1f71a2a Birch boats are also vehicles.
Fixes WORLDGUARD-3740.
2016-07-29 13:32:51 -04:00
wizjany 2aaa14261b Actually add 1.10 blocks. 2016-07-05 19:22:32 -04:00
wizjany f006a9584c Fix Location flag bounding.
Fixes WORLDGUARD-3716.
2016-06-22 14:52:19 -04:00
wizjany 03cf9a668b Actually fix unmarshalling of region group flags. 2016-06-15 23:47:59 -04:00
Weasel_Squeezer db70e6f346 Add transientRegion property to ProtectedRegion as a flag to only be stored in memory and not saved (#355) 2016-06-13 22:31:10 -04:00
wizjany e0df194ff2 Fix unmarshalling of region group flags.
Fixes WORLDGUARD-3708.
2016-06-13 22:31:09 -04:00
wizjany ab55137f59 Allow FlagContext to be added to by plugins. 2016-06-13 22:31:09 -04:00
ZephireNZ bbb79526b2 Make RegionPrintoutBuilder use the FlagRegistry to print flags 2016-06-13 22:31:08 -04:00
wizjany cde9a403f7 Allow plugins to register session handlers. 2016-06-13 22:31:08 -04:00
wizjany 43a9228304 Add config setting to allow clamping of location flags.
Prevents players from setting locations (teleport, spawn) to point outside of the region.
The permission to override this is "worldguard.region.locationoverride.(own/member/.)regionid".
Also prevents location flags from being set to under the map or over the max world height.
Fixes WORLDGUARD-2775, WORLDGUARD-3370.
2016-06-13 22:31:07 -04:00
wizjany c1b8d12d05 Add FlagContext. 2016-06-13 22:31:00 -04:00
sk89q a25674e9a5 Add preliminary custom flags support. 2016-06-13 22:27:53 -04:00
wizjany 778ec404ff Prevent fishing rod PvP.
Fixes WORLDGUARD-3707.
2016-06-13 21:29:26 -04:00
wizjany 4ab38e5b89 Bump version to 6.1.3-SNAPSHOT for development. 2016-06-11 12:38:45 -04:00
468 changed files with 24174 additions and 18593 deletions

No files matched your search

+34 -2
View File
@@ -1,2 +1,34 @@
*.java diff=java
* text=auto eol=lf
# Force Batch files to CRLF
*.bat eol=crlf -text
# Java sources
*.java text diff=java
*.kt text diff=java
*.gradle text diff=java
*.gradle.kts text diff=java
# These files are text and should be normalized (Convert crlf => lf)
*.css text diff=css
*.df text
*.htm text diff=html
*.html text diff=html
*.js text
*.jsp text
*.jspf text
*.jspx text
*.properties text
*.tld text
*.tag text
*.tagx text
*.xml text
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.dll binary
*.ear binary
*.jar binary
*.so binary
*.war binary
*.jks binary
+1
View File
@@ -0,0 +1 @@
github: enginehub
+93
View File
@@ -0,0 +1,93 @@
name: Bug report
description: Report a way in which WorldGuard is not working as intended
labels: ['type:bug', 'status:pending']
body:
- type: markdown
attributes:
value: |
Please note that this is only for bugs, help with installation or other types of support should
be taken to the Discord Guild instead.
- type: input
attributes:
label: WorldEdit Version
description: The full version of WorldEdit, can be found by using `/we version`.
placeholder: e.g. 7.2.3 or 7.3.0-SNAPSHOT
validations:
required: true
- type: input
attributes:
label: WorldGuard Version
description: The full version of WorldGuard, can be found by using `/wg version`.
placeholder: e.g. 7.0.5 or 7.0.6-SNAPSHOT
validations:
required: true
- type: input
attributes:
label: Platform Version
description: |
The version of the platform you are on, i.e. Spigot or Paper.
Please ensure you are running up-to-date software before making a bug report.
Old versions, paper forks or hybrids will receive little to no support.
placeholder: e.g. git-Spigot-21fe707-e1ebe52, git-Paper-463
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Confirmations
description: Please confirm the following before submitting the bug. Your report will be closed if you are running hybrids or old software.
options:
- label: I am using the most recent Minecraft release.
required: true
- label: I am using a version of WorldEdit compatible with my Minecraft version.
required: true
- label: I am using a version of WorldGuard compatible with my Minecraft version.
required: true
- label: I am using the latest or recommended version of my platform software.
required: true
- label: I am NOT using a hybrid server, e.g. a server that combines Bukkit and Forge. Examples include Arclight, Mohist, and Cardboard.
required: true
- label: I am NOT using a fork of WorldEdit, such as FastAsyncWorldEdit (FAWE) or AsyncWorldEdit (AWE)
required: true
- type: textarea
attributes:
label: Bug Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: The behavior that you expected, instead of the bugged behavior that occurs.
validations:
required: true
- type: textarea
attributes:
label: Reproduction Steps
description: Steps to reproduce the behavior.
value: |
1. ...
2. ...
validations:
required: true
- type: input
attributes:
label: Optional WorldGuard-Report
description: Link to WorldGuard Region report for bugs with regions, received with `/wg report -p`
validations:
required: false
- type: textarea
attributes:
label: Anything Else?
description: Add any additional context you can provide below.
+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.
@@ -0,0 +1,35 @@
name: Feature request
description: Suggest an idea for WorldGuard
labels: ['type:feature-request', 'status:pending']
body:
- type: textarea
attributes:
label: The Problem
description: >
What is making your WorldGuard experience sub-optimal? This should be something that
cannot be easily solved by existing WorldGuard features.
placeholder: It's hard to ... ; I'm unable to ...
validations:
required: true
- type: textarea
attributes:
label: A Solution
description: What is your proposed solution to the above problem?
validations:
required: true
- type: textarea
attributes:
label: Alternatives
description: |
Alternative solutions or workarounds to the problem.
You should also describe why these are not preferable to the given solution.
validations:
required: false
- type: textarea
attributes:
label: Anything Else?
description: Add any additional context you can provide below.
+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/
-7
View File
@@ -1,7 +0,0 @@
language: java
jdk:
- oraclejdk8
notifications:
email: false
before_install: chmod +x gradlew
script: ./gradlew build -S
+223
View File
@@ -1,5 +1,228 @@
# Changelog
## 7.0.12
* Fix a change in the default behavior of explosion flag handling.
## 7.0.11
* Add support for MC 1.21.
* Add wind-charge-burst flag which is checked along with `use` (for the interaction) or `pvp` (for the knockback).
* Add breeze-charge-explosion flag for breeze charges (i.e. from the mob, not player wind charges).
* Add moisture-change flag and config options.
* Fix an error if a player logged in to an unloaded world.
* Fix chest boat usage always being counted as ride.
* Consider potions thrown by mobs as mob-damage.
* Workaround spigot no longer sending block change events when a book is placed on a lectern.
* Improve accuracy of target blocks in blacklist/build-perms events.
## 7.0.10
* Add support for MC 1.20.5 and 1.20.6, drop support for other 1.20 versions
## 7.0.9
* Add support for MC 1.20, drop support for MC 1.19
* Made entities spawned via the `/summon` command get treated as plugin-spawned entities
* Add sniffer egg trample protection options
## 7.0.8
* Add support for MC 1.19
* Add skulk-growth flag and config option
* Add copper-fade flag
* Add data packs to report output
* Add protection for allay inventory slot
* Categorize allay item pickups under item-pickup flag
* Categorize dragon egg interaction (teleporting) as building
* Ignore most NPC-based actions for Player events
* Optimize handling of tamed animals where the owner was offline (Paper only)
* Optimize additional InventoryHolder accesses (Paper only)
* Fix an exception that occurred when plugins created portals with non-player entities
* Fix possible error when using Paper's entity origin API
* Update bstats and squirrelid libs
## 7.0.7
* Add rock-growth flag for budding amethyst and pointed dripstone.
* Add /rg migrateheights command. See https://worldguard.enginehub.org/en/latest/regions/commands/#migrate-region-heights
* Add regions.set-parent-on-claim config (set to a region id for /rg claim to automatically assign the parent region).
* Add `-i search` and `-s` flags to /rg list, -c to /rg teleport.
* Fix an error in blacklist logging caused by non-player actions (eg on-dispense)
* Treat unknown causes as known if using paper-entity-origin config option.
* Improve lightning strike handling from channeling tridents (PaperMC only).
* Ignore an error caused by lingering player references of offline players.
* Add red sand to no-physics-sand.
* Fix potion splash events being cancelled if no entities were affected.
## 7.0.6
* Add support for 1.17 blocks/items, drop support for 1.16.
* Add use-dripleaf flag for "toggling" big dripleaf blocks.
* Fix support for fully negative-height regions.
* Fix crop-growth config option.
* Be more rigorous with protecting blocks against dispenser behaviors.
* Fix handling of lingering splash potion effects.
* Handle other-explosion flag consistently for block-like entities (armor frames etc.)
* Allow inheriting values for all flags (previously wasn't used for things like teleport.)
* Region commands that defaulted to the region the player was standing in no longer check parents.
* Fix child regions being unlinked when redefining a parent region.
## 7.0.5
* Add a use-anvil flag and exclude it from the use flag (since they can break on use.)
* Add nonplayer-protection-domains flag which allows merging region borders from the perspective of pistons, saplings, etc.
* 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`).
+39
View File
@@ -0,0 +1,39 @@
Compiling
=========
You can compile WorldGuard as long as you have some version of Java greater than or equal to 21 installed.
Gradle will download JDK 21 specifically if needed, but it needs some version of Java to bootstrap from.
The build process uses Gradle, which you do *not* need to download. WorldGuard is a multi-module project with three modules:
* `worldguard-core` contains the WorldGuard API
* `worldguard-bukkit` is the Bukkit plugin
* `worldguard-libs` contains library relocations
## To compile...
### On Windows
1. **Shift** + **right click** the folder with WorldGuard's files and click "Open PowerShell window here".
2. `gradlew build`
### On Linux, BSD, or Mac OS X
1. In your terminal, navigate to the folder with WorldGuard's files (`cd /folder/of/worldguard/files`)
2. `./gradlew build`
## Then you will find...
You will find:
* The core WorldGuard API in **worldguard-core/build/libs**
* WorldGuard for Bukkit in **worldguard-bukkit/build/libs**
If you want to use WorldGuard, use the `-dist` version.
(The -dist version includes WorldGuard + necessary libraries.)
## Other commands
* `gradlew idea` will generate an [IntelliJ IDEA](http://www.jetbrains.com/idea/) module for each folder.
* `gradlew eclipse` will generate an [Eclipse](https://www.eclipse.org/downloads/) project for each folder.
+2 -4
View File
@@ -4,12 +4,10 @@ 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
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
* **Target Java 16 for source and compilation.**
* **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 17 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](https://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](https://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/)
+29
View File
@@ -0,0 +1,29 @@
plugins {
`kotlin-dsl`
}
repositories {
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation(libs.licenser)
implementation(libs.grgit)
implementation(libs.shadow)
implementation(libs.jfrog.buildinfo)
implementation(libs.gson)
constraints {
val asmVersion = "[${libs.versions.minimumAsm.get()},)"
implementation("org.ow2.asm:asm:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.ow2.asm:asm-commons:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.vafer:jdependency:[${libs.versions.minimumJdependency.get()},)") {
because("Need Java 21 support in shadow")
}
}
}
+9
View File
@@ -0,0 +1,9 @@
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}
rootProject.name = "build-logic"
@@ -0,0 +1,32 @@
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
plugins {
id("com.jfrog.artifactory")
}
val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
val ARTIFACTORY_USER = "artifactory_user"
val ARTIFACTORY_PASSWORD = "artifactory_password"
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] = ""
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
}
@@ -0,0 +1,10 @@
plugins {
id("com.jfrog.artifactory")
}
// Artifactory eagerly evaluates publications, so this must run after all changes to artifacts are done
afterEvaluate {
tasks.named<org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
@@ -0,0 +1,65 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
plugins {
id("eclipse")
id("idea")
id("checkstyle")
id("buildlogic.common")
}
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial", "overloads",
)
options.release.set(21)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
//options.compilerArgs.add("-Werror")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "10.16.0"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"(stringyLibs.getLibrary("jsr305"))
"testImplementation"(platform(stringyLibs.getLibrary("junit-bom")))
"testImplementation"(stringyLibs.getLibrary("junit-jupiter-api"))
"testImplementation"(stringyLibs.getLibrary("junit-jupiter-params"))
"testRuntimeOnly"(stringyLibs.getLibrary("junit-jupiter-engine"))
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
//addBooleanOption("Werror", true)
addBooleanOption("Xdoclint:all", true)
addBooleanOption("Xdoclint:-missing", true)
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
withJavadocJar()
withSourcesJar()
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
@@ -0,0 +1,69 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
import org.gradle.plugins.ide.idea.model.IdeaModel
plugins {
id("org.cadixdev.licenser")
}
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven {
name = "EngineHub"
url = uri("https://maven.enginehub.org/repo/")
}
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(1, TimeUnit.DAYS)
}
}
plugins.withId("java") {
the<JavaPluginExtension>().toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
dependencies {
for (conf in listOf("implementation", "api")) {
if (!configurations.names.contains(conf)) {
continue
}
add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map {
val dep = create(it)
dep.because("Mojang provides Log4j")
dep
})
constraints {
add(conf, stringyLibs.getLibrary("guava")) {
because("Mojang provides Guava")
}
add(conf, stringyLibs.getLibrary("gson")) {
because("Mojang provides Gson")
}
add(conf, stringyLibs.getLibrary("fastutil")) {
because("Mojang provides FastUtil")
}
}
}
}
license {
header(rootProject.file("HEADER.txt"))
include("**/*.java")
include("**/*.kt")
}
plugins.withId("idea") {
configure<IdeaModel> {
module {
isDownloadSources = true
isDownloadJavadoc = true
}
}
}
@@ -0,0 +1,23 @@
plugins {
id("java")
id("maven-publish")
id("buildlogic.common-java")
id("buildlogic.artifactory-sub")
}
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
publishing {
publications {
register<MavenPublication>("maven") {
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
@@ -0,0 +1,179 @@
plugins {
id("java-base")
id("maven-publish")
id("com.github.johnrengelman.shadow")
id("com.jfrog.artifactory")
id("buildlogic.common")
id("buildlogic.artifactory-sub")
}
// A horrible hack because `softwareComponentFactory` has to be gotten via plugin
// gradle why
internal open class LibsConfigPluginHack @Inject constructor(
private val softwareComponentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(project: Project) {
val libsComponents = softwareComponentFactory.adhoc("libs")
project.components.add(libsComponents)
}
}
configurations {
create("shade")
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile",
)
tasks.register<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
// Yeet module-info's
exclude("module-info.class")
dependencies {
exclude(dependency("com.google.guava:guava"))
exclude(dependency("com.google.code.gson:gson"))
exclude(dependency("com.google.errorprone:error_prone_annotations"))
exclude(dependency("com.google.guava:failureaccess"))
exclude(dependency("org.checkerframework:checker-qual"))
exclude(dependency("org.jetbrains:annotations"))
exclude(dependency("org.apache.logging.log4j:log4j-api"))
exclude(dependency("com.google.code.findbugs:jsr305"))
exclude {
it.moduleGroup == "org.jetbrains.kotlin"
}
}
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
val category = dependency.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name
if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) {
return@map dependency
}
try {
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
} catch (e: Exception) {
throw RuntimeException("Failed to add artifact to dependency: $dependency", e)
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
// Yeet module-info's
exclude("module-info.java")
relocations.forEach { (from, to) ->
val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)")
val textPattern = Regex.fromLiteral(from)
eachFile {
filter {
it.replaceFirst(textPattern, to)
}
path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2")
}
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
project.apply<LibsConfigPluginHack>()
val libsComponent = project.components["libs"] as AdhocComponentWithVariants
val apiElements = project.configurations.register("apiElements") {
isVisible = false
description = "API elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 21)
}
outgoing.artifact(tasks.named("jar"))
}
val runtimeElements = project.configurations.register("runtimeElements") {
isVisible = false
description = "Runtime elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 21)
}
outgoing.artifact(tasks.named("jar"))
}
val sourcesElements = project.configurations.register("sourcesElements") {
isVisible = false
description = "Source elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES))
}
outgoing.artifact(tasks.named("sourcesJar"))
}
libsComponent.addVariantsFromConfiguration(apiElements.get()) {
mapToMavenScope("compile")
}
libsComponent.addVariantsFromConfiguration(runtimeElements.get()) {
mapToMavenScope("runtime")
}
libsComponent.addVariantsFromConfiguration(sourcesElements.get()) {
mapToMavenScope("runtime")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(libsComponent)
}
}
}
if (project != project(":worldguard-libs:core")) {
evaluationDependsOn(":worldguard-libs:core")
configurations["shade"].shouldResolveConsistentlyWith(project(":worldguard-libs:core").configurations["shade"])
}
@@ -0,0 +1,39 @@
plugins {
id("com.github.johnrengelman.shadow")
id("buildlogic.core-and-platform")
}
tasks.named<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core"))
}
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
exclude("META-INF/maven/**")
minimize()
}
val javaComponent = components["java"] as AdhocComponentWithVariants
// I don't think we want this published (it's the shadow jar)
javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) {
skip()
}
afterEvaluate {
tasks.named<Jar>("jar") {
val version = project(":worldguard-core").version
inputs.property("version", version)
val attributes = mutableMapOf(
"Implementation-Version" to version,
"WorldGuard-Version" to version,
)
manifest.attributes(attributes)
}
}
@@ -0,0 +1,24 @@
package buildlogic
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.artifacts.VersionConstraint
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.provider.Provider
import org.gradle.kotlin.dsl.getByType
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.stringyLibs: VersionCatalog
get() = extensions.getByType<VersionCatalogsExtension>().named("libs")
fun VersionCatalog.getLibrary(name: String): Provider<MinimalExternalModuleDependency> = findLibrary(name).orElseThrow {
error("Library $name not found in version catalog")
}
fun VersionCatalog.getVersion(name: String): VersionConstraint = findVersion(name).orElseThrow {
error("Version $name not found in version catalog")
}
-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
}
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import org.ajoberstar.grgit.Grgit
plugins {
id("buildlogic.common")
id("buildlogic.artifactory-root")
}
if (!project.hasProperty("gitCommitHash")) {
apply(plugin = "org.ajoberstar.grgit")
ext["gitCommitHash"] = try {
extensions.getByName<Grgit>("grgit").head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no.git.id"
}
}
@@ -0,0 +1,86 @@
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
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.withType
fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, javaRelease: Int = 8, banSlf4j: Boolean = true) {
applyCommonConfiguration()
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "checkstyle")
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial"
)
options.release.set(javaRelease)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "9.1"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:${Versions.FINDBUGS}")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
disableAutoTargetJvm()
withJavadocJar()
if (sourcesJar) {
withSourcesJar()
}
}
if (banSlf4j) {
configurations["compileClasspath"].apply {
resolutionStrategy.componentSelection {
withModule("org.slf4j:slf4j-api") {
reject("No SLF4J allowed on compile classpath")
}
}
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
}
+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/>.
*/
+15 -11
View File
@@ -7,28 +7,32 @@
<allow pkg="javax"/>
<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="org.bstats.charts"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
<allow pkg="io.papermc.paper"/>
<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>
+4
View File
@@ -0,0 +1,4 @@
group=com.sk89q.worldguard
version=7.1.0-SNAPSHOT
org.gradle.parallel=true
+2
View File
@@ -0,0 +1,2 @@
#This file is generated by updateDaemonJvm
toolchainVersion=21
+66
View File
@@ -0,0 +1,66 @@
[versions]
worldedit = "7.3.0"
# Minimum versions we apply to make dependencies support newer Java
minimumAsm = "9.7"
minimumJdependency = "2.10"
minimumTinyRemapper = "0.8.11"
# lang-version = ""
[libraries]
licenser = "gradle.plugin.org.cadixdev.gradle:licenser:0.6.1"
grgit = "org.ajoberstar.grgit:grgit-gradle:5.2.2"
shadow = "com.github.johnrengelman:shadow:8.1.1"
jfrog-buildinfo = "org.jfrog.buildinfo:build-info-extractor-gradle:5.2.0"
squirrelid = "org.enginehub:squirrelid:0.3.2"
autoService = "com.google.auto.service:auto-service:1.1.1"
jsr305 = "com.google.code.findbugs:jsr305:3.0.2"
jetbrains-annotations = "org.jetbrains:annotations:24.1.0"
junit-bom = "org.junit:junit-bom:5.10.2"
junit-jupiter-api.module = "org.junit.jupiter:junit-jupiter-api"
junit-jupiter-params.module = "org.junit.jupiter:junit-jupiter-params"
junit-jupiter-engine.module = "org.junit.jupiter:junit-jupiter-engine"
spigot = "org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT"
paperApi = "io.papermc.paper:paper-api:1.21-R0.1-SNAPSHOT"
paperLib = "io.papermc:paperlib:1.0.8"
dummypermscompat = "com.sk89q:dummypermscompat:1.10"
bstats-bukkit = "org.bstats:bstats-bukkit:2.2.1"
prtree = "org.khelekore:prtree:1.5.0"
flyway-core = "org.flywaydb:flyway-core:3.0"
commandbook = "com.sk89q:commandbook:2.3"
hamcrest-library = "org.hamcrest:hamcrest-library:2.2"
# Mojang-provided libraries, CHECK AGAINST MINECRAFT for versions
guava = "com.google.guava:guava:32.1.3-jre!!"
log4j-bom = "org.apache.logging.log4j:log4j-bom:2.22.1!!"
gson = "com.google.code.gson:gson:2.10.1!!"
fastutil = "it.unimi.dsi:fastutil:8.5.12!!"
# Bukkit-provided libraries, CHECK AGAINST SPIGOT for versions
# Note that we need to balance support for older MC versus working at all on newer ones, so the exact versions here
# may not be the same as the ones in the latest Bukkit API.
snakeyaml = "org.yaml:snakeyaml:2.0"
[libraries.worldedit-core]
module = "com.sk89q.worldedit:worldedit-core"
version.ref = "worldedit"
[libraries.worldedit-bukkit]
module = "com.sk89q.worldedit:worldedit-bukkit"
version.ref = "worldedit"
[libraries.worldedit-libs-ap]
module = "com.sk89q.worldedit.worldedit-libs:ap"
version.ref = "worldedit"
Binary file not shown.
+3 -2
View File
@@ -1,6 +1,7 @@
#Fri Nov 13 12:12:21 EST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip
Vendored Regular → Executable
+203 -118
View File
@@ -1,79 +1,127 @@
#!/usr/bin/env bash
#!/bin/sh
#
# Copyright © 2015-2021 the original 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.
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Attempt to set APP_HOME
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn ( ) {
warn () {
echo "$*"
}
} >&2
die ( ) {
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# 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
;;
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=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"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -82,83 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
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=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# 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"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+44 -42
View File
@@ -1,4 +1,20 @@
@if "%DEBUG%" == "" @echo off
@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
@rem Gradle startup script for Windows
@@ -8,26 +24,30 @@
@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=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -35,54 +55,36 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:init
@rem Get command-line arguments, handling Windowz 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.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
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
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
-3
View File
@@ -1,3 +0,0 @@
rootProject.name = 'worldguard'
include 'worldguard-core', 'worldguard-sponge', 'worldguard-legacy'
+33
View File
@@ -0,0 +1,33 @@
pluginManagement {
repositories {
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
logger.lifecycle("""
*******************************************
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 Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
rootProject.name = "worldguard"
includeBuild("build-logic")
include("worldguard-libs")
include("worldguard-libs:core")
listOf("bukkit", "core").forEach {
include("worldguard-$it")
}
+68
View File
@@ -0,0 +1,68 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
`java-library`
id("buildlogic.platform")
}
val localImplementation = configurations.create("localImplementation") {
description = "Dependencies used locally, but provided by the runtime Bukkit implementation"
isCanBeConsumed = false
isCanBeResolved = false
}
configurations["compileOnly"].extendsFrom(localImplementation)
configurations["testImplementation"].extendsFrom(localImplementation)
dependencies {
"api"(project(":worldguard-core"))
"api"(libs.worldedit.bukkit) { isTransitive = false }
"compileOnly"(libs.commandbook) { isTransitive = false }
// Technically this is api, but everyone should already have some form of the bukkit API
// Avoid pulling in another one, especially one so outdated.
"localImplementation"(libs.spigot) {
exclude("junit", "junit")
}
"compileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"testCompileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"compileOnly"(libs.paperApi) {
exclude("org.slf4j", "slf4j-api")
exclude("junit", "junit")
}
"implementation"(libs.paperLib)
"implementation"(libs.bstats.bukkit)
}
tasks.named<Copy>("processResources") {
val internalVersion = project.ext["internalVersion"]
inputs.property("internalVersion", internalVersion)
filesMatching("plugin.yml") {
expand("internalVersion" to internalVersion)
}
}
tasks.named<ShadowJar>("shadowJar") {
dependencies {
include(dependency(":worldguard-core"))
include(dependency("org.bstats:"))
include(dependency("io.papermc:paperlib"))
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats")
relocate("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib")
}
}
tasks.named("assemble").configure {
dependsOn("shadowJar")
}
configure<PublishingExtension> {
publications.named<MavenPublication>("maven") {
from(components["java"])
}
}
@@ -0,0 +1,127 @@
/*
* 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;
/**
* 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);
}
@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();
return get(worldName);
}
public BukkitWorldConfiguration get(String worldName) {
BukkitWorldConfiguration config = worlds.get(worldName);
BukkitWorldConfiguration newConfig = null;
while (config == null) {
if (newConfig == null) {
newConfig = new BukkitWorldConfiguration(plugin, worldName, this.getConfig());
}
worlds.putIfAbsent(worldName, newConfig);
config = worlds.get(worldName);
}
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,96 @@
/*
* 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
* @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,153 +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 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;
@@ -214,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;
}
@@ -289,57 +126,22 @@ 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;
}
boolean needParentSave = false;
summaryOnStart = getBoolean("summary-on-start", true);
opPermissions = getBoolean("op-permissions", true);
@@ -350,13 +152,20 @@ 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>();
needParentSave |= removeProperty("protection.disable-obsidian-generators");
useMaxPriorityAssociation = getBoolean("protection.use-max-priority-association", false);
blockPotions = new HashSet<>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
PotionEffectType effect = PotionEffectType.getByName(potionName);
@@ -367,10 +176,16 @@ 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;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
if (simulateSponge) {
log.warning("Sponge simulation is deprecated for removal in a future version. We recommend using CraftBook's sponge simulation instead.");
} else {
needParentSave |= removeProperty("simulation");
}
pumpkinScuba = getBoolean("default.pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
@@ -379,16 +194,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);
@@ -400,16 +215,19 @@ public class WorldConfiguration {
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
blockWindChargeExplosions = getBoolean("mobs.block-windcharge-explosions", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
allowTamedSpawns = getBoolean("mobs.allow-tamed-spawns", true);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
disableSnowmanTrails = getBoolean("mobs.disable-snowman-trails", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockEntityItemFrameDestroy = getBoolean("mobs.block-item-frame-destroy", false);
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);
@@ -421,21 +239,33 @@ 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);
signChestProtection = getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", true);
if (signChestProtection) {
log.warning("Sign-based chest protection is deprecated for removal in a future version. See https://worldguard.enginehub.org/en/latest/chest-protection/ for details.");
} else {
needParentSave |= removeProperty("chest-protection");
}
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);
disableCreatureSnifferEggTrampling = getBoolean("sniffer-egg.disable-creature-trampling", false);
disablePlayerSnifferEggTrampling = getBoolean("sniffer-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);
@@ -449,28 +279,38 @@ public class WorldConfiguration {
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-growth", false);
disableRockGrowth = getBoolean("dynamics.disable-rock-growth", false);
disableSculkGrowth = getBoolean("dynamics.disable-sculk-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));
disableSoilMoistureChange = getBoolean("dynamics.disable-soil-moisture-change", false);
disableCoralBlockFade = getBoolean("dynamics.disable-coral-block-fade", false);
disableCopperBlockFade = getBoolean("dynamics.disable-copper-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);
setParentOnClaim = getString("regions.set-parent-on-claim", "");
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());
}
}
@@ -480,14 +320,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);
}
@@ -518,7 +356,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
@@ -528,7 +366,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();
@@ -569,7 +408,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.");
@@ -583,49 +422,55 @@ public class WorldConfiguration {
config.setHeader(CONFIG_HEADER);
config.save();
if (needParentSave) {
parentConfig.save();
}
}
public Blacklist getBlacklist() {
return this.blacklist;
private boolean removeProperty(String prop) {
if (config.getProperty(prop) != null) {
config.removeProperty(prop);
}
if (parentConfig.getProperty(prop) != null) {
parentConfig.removeProperty(prop);
return true;
}
return false;
}
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);
@@ -635,19 +480,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,276 @@
/*
* 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.PaperPlayerService;
import com.sk89q.worldguard.bukkit.protection.events.flags.FlagContextCreateEvent;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.report.DatapackReport;
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();
regionContainer = new BukkitRegionContainer(WorldGuardPlugin.inst());
regionContainer.initialize();
debugHandler = new BukkitDebugHandler(WorldGuardPlugin.inst());
}
@Override
public void unload() {
sessionManager.shutdown();
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");
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?
if (item2.isSimilar(item)) {
// 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());
if (PaperLib.isPaper()) report.add(new DatapackReport());
}
@Override
public ProfileService createProfileService(ProfileCache profileCache) {
List<ProfileService> services = new ArrayList<>();
if (PaperLib.isPaper()) {
// Paper has a shared cache
services.add(PaperPlayerService.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().y()),
spawnLoc.add(radius, 0, radius).withY(world.getMaxY()));
}
}
}
return null;
}
}
@@ -0,0 +1,529 @@
/*
* 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.ClassSourceValidator;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.commands.GeneralCommands;
import com.sk89q.worldguard.commands.ProtectionCommands;
import com.sk89q.worldguard.commands.ToggleCommands;
import com.sk89q.worldguard.domains.registry.SimpleDomainRegistry;
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.ProtectedRegion;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.DrilldownPie;
import org.bstats.charts.SimplePie;
import org.bstats.charts.SingleLineChart;
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;
private static final int BSTATS_PLUGIN_ID = 3283;
/**
* 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() {
// Catch bad things being done by naughty plugins that include WorldGuard's classes
ClassSourceValidator verifier = new ClassSourceValidator(this);
verifier.reportMismatches(ImmutableList.of(WorldGuard.class, ProtectedRegion.class, Flag.class));
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()));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
if (!platform.getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
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);
((SimpleDomainRegistry) WorldGuard.getInstance().getDomainRegistry()).setInitialized(true);
// Enable metrics
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); // bStats plugin id
if (platform.getGlobalStateManager().extraStats) {
setupCustomCharts(metrics);
}
}
private void setupCustomCharts(Metrics metrics) {
metrics.addCustomChart(new SingleLineChart("region_count", () ->
platform.getRegionContainer().getLoaded().stream().mapToInt(RegionManager::size).sum()));
metrics.addCustomChart(new SimplePie("region_driver", () -> {
RegionDriver driver = platform.getGlobalStateManager().selectedRegionStoreDriver;
return driver instanceof DirectoryYamlDriver ? "yaml" : driver instanceof SQLDriver ? "sql" : "unknown";
}));
metrics.addCustomChart(new 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 SimplePie("chest_protection", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.signChestProtection)));
metrics.addCustomChart(new SimplePie("build_permissions", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.buildPermissions)));
metrics.addCustomChart(new SimplePie("custom_flags", () ->
"" + (WorldGuard.getInstance().getFlagRegistry().size() > Flags.INBUILT_FLAGS.size())));
metrics.addCustomChart(new 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 player) {
if (Entities.isNPC(player)) return null;
return wrapPlayer(player);
}
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);
}
/**
* Internal method. Do not use as API.
*/
public BukkitConfigurationManager getConfigManager() {
return platform.getGlobalStateManager();
}
/**
* 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;
}
}
@@ -21,16 +21,36 @@ package com.sk89q.worldguard.bukkit.cause;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.internal.WGMetadata;
import com.sk89q.worldguard.bukkit.util.Entities;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.entity.AnimalTamer;
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.LightningStrike;
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 +96,39 @@ 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()) {
Object object = getRootCause();
if (object == null) {
return false;
}
boolean found = false;
for (Object object : causes) {
if (!(object instanceof TNTPrimed) && !(object instanceof Vehicle)) {
found = true;
break;
if (object instanceof Tameable tameable && tameable.isTamed()) {
// if they're tamed but also the root cause, the owner is offline
// otherwise the owner will be the root cause (and known)
return false;
}
if (object instanceof TNTPrimed || object instanceof Vehicle) {
if (!PaperLib.isPaper()) {
return false;
}
Entity entity = (Entity) object;
BukkitWorldConfiguration config = WorldGuardPlugin.inst().getConfigManager().get(entity.getWorld().getName());
if (!config.usePaperEntityOrigin || entity.getOrigin() == null) {
return false;
}
}
return found;
return true;
}
@Nullable
@@ -110,8 +143,8 @@ public final class Cause {
@Nullable
public Player getFirstPlayer() {
for (Object object : causes) {
if (object instanceof Player) {
return (Player) object;
if (object instanceof Player p && !Entities.isNPC(p)) {
return p;
}
}
@@ -121,8 +154,8 @@ public final class Cause {
@Nullable
public Entity getFirstEntity() {
for (Object object : causes) {
if (object instanceof Entity) {
return (Entity) object;
if (object instanceof Entity e) {
return e;
}
}
@@ -132,8 +165,8 @@ public final class Cause {
@Nullable
public Entity getFirstNonPlayerEntity() {
for (Object object : causes) {
if (object instanceof Entity && !(object instanceof Player)) {
return (Entity) object;
if (object instanceof Entity e && (!(object instanceof Player) || Entities.isNPC(e))) {
return e;
}
}
@@ -143,8 +176,8 @@ public final class Cause {
@Nullable
public Block getFirstBlock() {
for (Object object : causes) {
if (object instanceof Block) {
return (Block) object;
if (object instanceof Block b) {
return b;
}
}
@@ -224,6 +257,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,45 +275,80 @@ 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) {
if (element != null) {
for (Object o : element) {
if (o == null || seen.contains(o)) {
continue;
}
if (element == null) {
return;
}
for (Object o : element) {
if (o == null || seen.contains(o)) {
continue;
}
seen.add(o);
seen.add(o);
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
addAll(((Projectile) o).getShooter());
} else if (o instanceof Vehicle) {
addAll(((Vehicle) o).getPassenger());
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
indirect = true;
addAll(((Creature) o).getTarget());
} else if (o instanceof Tameable) {
indirect = true;
addAll(((Tameable) o).getOwner());
}
// Add manually tracked parent causes
Object source = o;
int index = causes.size();
while (source instanceof Metadatable && !(source instanceof Block)) {
source = WGMetadata.getIfPresent((Metadatable) source, CAUSE_KEY, Object.class);
if (source != null) {
causes.add(index, source);
seen.add(source);
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
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);
}
}
}
causes.add(o);
} else if (o instanceof Vehicle) {
((Vehicle) o).getPassengers().forEach(this::addAll);
} else if (o instanceof AreaEffectCloud) {
indirect = true;
addAll(((AreaEffectCloud) o).getSource());
} else if (o instanceof Tameable tameable) {
indirect = true;
if (PaperLib.isPaper()) {
UUID ownerId = tameable.getOwnerUniqueId();
if (ownerId != null) {
Player owner = Bukkit.getPlayer(ownerId);
if (owner != null) {
addAll(owner);
}
}
} else {
// this will cause offline player loads if the player is offline
// too bad for spigot users
AnimalTamer owner = tameable.getOwner();
if (owner instanceof OfflinePlayer player) {
addAll(player.getPlayer()); // player object if online, else null
}
}
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
indirect = true;
addAll(((Creature) o).getTarget());
} else if (o instanceof BlockProjectileSource) {
addAll(((BlockProjectileSource) o).getBlock());
} else if (o instanceof LightningStrike && PaperLib.isPaper() &&
((LightningStrike) o).getCausingEntity() != null) {
indirect = true;
addAll(((LightningStrike) o).getCausingEntity());
}
// Add manually tracked parent causes
Object source = o;
int index = causes.size();
while (source instanceof Metadatable && !(source instanceof Block)) {
source = WGMetadata.getIfPresent((Metadatable) source, CAUSE_KEY, Object.class);
if (source != null) {
causes.add(index, source);
seen.add(source);
}
}
causes.add(o);
}
}
@@ -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,156 @@
/*
* 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.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.util.Entities;
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 static WorldGuardPlugin getPlugin() {
return WorldGuardPlugin.inst();
}
/**
* Get the global configuration.
*
* @return the configuration
*/
protected static BukkitConfigurationManager getConfig() {
return getPlugin().getConfigManager();
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected static BukkitWorldConfiguration getWorldConfig(String world) {
return getConfig().get(world);
}
protected static BukkitWorldConfiguration getWorldConfig(org.bukkit.World world) {
return getWorldConfig(world.getName());
}
/**
* 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 BukkitWorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig(((BukkitPlayer) player).getPlayer().getWorld());
}
/**
* Return whether region support is enabled.
*
* @param world the world
* @return true if region support is enabled
*/
protected static boolean isRegionSupportEnabled(org.bukkit.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 player && !Entities.isNPC(player)) {
return getPlugin().wrapPlayer(player);
} else if (rootCause instanceof OfflinePlayer offlinePlayer) {
return getPlugin().wrapOfflinePlayer(offlinePlayer);
} else if (rootCause instanceof Entity entity) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
BukkitWorldConfiguration config = getWorldConfig(entity.getWorld());
Location loc;
if (PaperLib.isPaper() && config.usePaperEntityOrigin) {
loc = entity.getOrigin();
// Origin world may be null, and thus a Location with a null world created, which cannot be adapted to a WorldEdit location
if (loc == null || loc.getWorld() == null) {
loc = entity.getLocation();
}
} else {
loc = entity.getLocation();
}
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
config.useMaxPriorityAssociation);
} else if (rootCause instanceof Block block) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Location loc = block.getLocation();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
getWorldConfig(loc.getWorld()).useMaxPriorityAssociation);
} else {
return Associables.constant(Association.NON_MEMBER);
}
}
}
@@ -0,0 +1,390 @@
/*
* 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.BukkitWorldConfiguration;
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 WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
event.filter(target -> {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
createTarget(target.getBlock())), 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) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
event.filter(target -> wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
event.filter(target -> wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
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) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Entity target = event.getEntity();
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) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ItemStack target = event.getItemStack();
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) {
WorldConfiguration wcfg = getWorldConfig(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) {
BukkitWorldConfiguration wcfg = getWorldConfig(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;
WorldConfiguration wcfg = getWorldConfig(player.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.getView().getTopInventory().getType() == InventoryType.CRAFTING)
&& 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;
WorldConfiguration wcfg = getWorldConfig(player.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) {
WorldConfiguration wcfg = getWorldConfig(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();
WorldConfiguration wcfg = getWorldConfig(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);
}
}
}
@@ -0,0 +1,160 @@
/*
* 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.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 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.event.EventHandler;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import java.util.ArrayList;
import java.util.List;
/**
* Handles blocked potions.
*/
public class BlockedPotionsListener extends AbstractListener {
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public BlockedPotionsListener(WorldGuardPlugin plugin) {
super(plugin);
}
private PotionEffectType getBlockedEffectByArrow(Arrow arrow, BukkitWorldConfiguration wcfg) {
List<PotionEffect> effects = new ArrayList<>();
PotionType potionType = arrow.getBasePotionType();
if (potionType != null) {
effects.addAll(potionType.getPotionEffects());
}
effects.addAll(arrow.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
return potionEffect.getType();
}
}
return null;
}
@EventHandler
public void onProjectile(DamageEntityEvent event) {
if (!(event.getOriginalEvent() instanceof EntityDamageByEntityEvent originalEvent)) {
return;
}
if (!Entities.isPotionArrow(originalEvent.getDamager())) {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof Arrow arrow) {
blockedEffect = getBlockedEffectByArrow(arrow, wcfg);
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
return;
}
player.sendMessage(ChatColor.RED + "Sorry, arrows with "
+ blockedEffect.getName() + " are presently disabled.");
}
event.setCancelled(true);
}
}
@EventHandler
public void onItemInteract(UseItemEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
ItemStack item = event.getItemStack();
if (item.getType() != Material.POTION
&& item.getType() != Material.SPLASH_POTION
&& item.getType() != Material.LINGERING_POTION) {
return;
}
if (!wcfg.blockPotions.isEmpty()) {
PotionEffectType blockedEffect = null;
if (!(item.getItemMeta() instanceof PotionMeta meta)) {
return;
}
// Find the first blocked effect
List<PotionEffect> effects = new ArrayList<>();
if (meta.getBasePotionType() != null) {
effects.addAll(meta.getBasePotionType().getPotionEffects());
}
effects.addAll(meta.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
blockedEffect = potionEffect.getType();
break;
}
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
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, " +
"due to limitations (and because overly-reliable potion blocking is on).");
event.setCancelled(true);
}
} else {
player.sendMessage(ChatColor.RED + "Sorry, potions with "
+ blockedEffect.getName() + " are presently disabled.");
event.setCancelled(true);
}
} else {
event.setCancelled(true);
}
}
}
}
}
@@ -101,12 +101,14 @@ public class BuildPermissionListener extends AbstractListener {
if (rootCause instanceof Player) {
final Player player = (Player) rootCause;
final Material material = event.getEffectiveMaterial();
if (!hasBuildPermission(player, "block." + material.name().toLowerCase() + ".interact")
&& !hasBuildPermission(player, "block.interact." + material.name().toLowerCase())) {
boolean blocked = event.filter(loc -> {
String blacklistName = loc.getBlock().getType().name().toLowerCase();
return hasBuildPermission(player, "block." + blacklistName + ".interact") ||
hasBuildPermission(player, "block.interact." + blacklistName);
}, true);
if (blocked && !event.isSilent()) {
tellErrorMessage(player, event.getWorld());
event.setCancelled(true);
}
}
}
@@ -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 = getWorldConfig(event.getWorld());
// 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 = getWorldConfig(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 = getWorldConfig(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);
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
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,14 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Entities;
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 +51,19 @@ 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 (Entities.isNPC(victim)) return;
if (victim instanceof Player) {
Player player = (Player) victim;
if (victim instanceof Player player) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(player)) {
if (isInvincible(localPlayer)) {
player.setFireTicks(0);
event.setCancelled(true);
@@ -68,7 +71,11 @@ public class InvincibilityListener extends AbstractListener {
EntityDamageByEntityEvent byEntityEvent = (EntityDamageByEntityEvent) event;
Entity attacker = byEntityEvent.getDamager();
if (worldConfig.regionInvinciblityRemovesMobs
if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Entity) {
attacker = (Entity) ((Projectile) attacker).getShooter();
}
if (getWorldConfig(player.getWorld()).regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
@@ -81,11 +88,12 @@ public class InvincibilityListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
if (Entities.isNPC(entity)) return;
if (entity instanceof Player) {
Player player = (Player) entity;
if (entity instanceof Player player) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(player)) {
if (isInvincible(localPlayer)) {
event.setCancelled(true);
}
}
@@ -93,10 +101,12 @@ public class InvincibilityListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (Entities.isNPC(event.getEntity())) return;
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
if (event.getEntity() instanceof Player player) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(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,161 @@
/*
* 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 org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.AbstractHorse;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityMountEvent;
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;
public class PlayerMoveListener extends AbstractListener {
public PlayerMoveListener(WorldGuardPlugin plugin) {
super(plugin);
}
@Override
public void registerEvents() {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().usePlayerMove) {
PluginManager pm = getPlugin().getServer().getPluginManager();
pm.registerEvents(this, getPlugin());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerRespawn(PlayerRespawnEvent event) {
LocalPlayer player = getPlugin().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 = getPlugin().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 = getPlugin().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 AbstractHorse) {
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(getPlugin(), () -> player.teleport(override.clone().add(0, 1, 0)), 1);
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
final Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().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));
}
session.uninitialize(localPlayer);
}
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().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,16 +19,19 @@
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;
@@ -40,7 +43,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 {
@@ -57,18 +60,22 @@ public class RegionFlagsListener extends AbstractListener {
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
// ================================================================
// PISTONS flag
// ================================================================
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
event.filter(testState(query, Flags.PISTONS), false);
}
}
if (event.getCause().find(EntityType.SNOW_GOLEM) != 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)
@@ -76,57 +83,58 @@ public class RegionFlagsListener extends AbstractListener {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
WorldConfiguration config = getWorldConfig(event.getWorld());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
// ================================================================
// PISTONS flag
// ================================================================
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
event.filter(testState(query, Flags.PISTONS), false);
}
}
// ================================================================
// CREEPER_EXPLOSION flag
// ================================================================
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);
}
// ================================================================
// ENDERDRAGON_BLOCK_DAMAGE flag
// ================================================================
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(EntityType.END_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);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
World world = entity.getWorld();
if (!isRegionSupportEnabled(world)) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
if (entity instanceof Player && event.getCause() == DamageCause.FALL) {
if (!query.testState(entity.getLocation(), (Player) entity, DefaultFlag.FALL_DAMAGE)) {
if (Entities.isNPC(entity)) return;
if (!(entity instanceof Player player)) return;
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (event.getCause() == DamageCause.FALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
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);
}
}
} catch (NoSuchFieldError ignored) {
} else if (event.getCause() == DamageCause.FLY_INTO_WALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
@@ -139,12 +147,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,35 @@ 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.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import java.util.ArrayList;
@@ -105,16 +108,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,10 +135,7 @@ 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);
@@ -137,32 +143,13 @@ public class RegionProtectionListener extends AbstractListener {
return true;
}
return !pvp && new RegionPermissionModel(getPlugin(), player).mayIgnoreRegionProtection(world);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
return !pvp && WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld());
} 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
@@ -170,7 +157,7 @@ public class RegionProtectionListener extends AbstractListener {
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
@@ -180,41 +167,39 @@ public class RegionProtectionListener extends AbstractListener {
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(block.getType());
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;
});
}
@@ -224,35 +209,32 @@ public class RegionProtectionListener extends AbstractListener {
if (!isRegionSupportEnabled(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.TNT, EntityType.TNT_MINECART) != 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;
});
}
}
@@ -263,54 +245,66 @@ public class RegionProtectionListener extends AbstractListener {
if (!isRegionSupportEnabled(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;
final Material type = target.getBlock().getType();
/* 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;
});
}
@@ -323,7 +317,7 @@ public class RegionProtectionListener extends AbstractListener {
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,28 +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 (event.getEffectiveType() == EntityType.EXPERIENCE_ORB) {
canSpawn = query.testBuild(target, associable, combine(event, DefaultFlag.EXP_DROPS));
} else if (type == EntityType.EXPERIENCE_ORB) {
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.EXP_DROPS));
what = "drop XP";
} else if (Entities.isAoECloud(type)) {
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) {
@@ -371,23 +364,23 @@ public class RegionProtectionListener extends AbstractListener {
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";
}
@@ -406,29 +399,41 @@ public class RegionProtectionListener extends AbstractListener {
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)
// weird case since sneak+interact is chest access and not ride
|| type == EntityType.CHEST_BOAT && event.getOriginalEvent() instanceof InventoryOpenEvent) {
if ((type == EntityType.ITEM_FRAME || type == EntityType.GLOW_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) || type == EntityType.CHEST_BOAT) {
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";
}
@@ -444,10 +449,10 @@ public class RegionProtectionListener extends AbstractListener {
if (!isRegionSupportEnabled(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;
@@ -473,11 +478,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()))) {
@@ -493,17 +504,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);
}
}
@@ -511,14 +522,15 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) {
Entity vehicle = event.getVehicle();
if (!isRegionSupportEnabled(vehicle.getWorld())) return; // Region support disabled
Entity exited = event.getExited();
if (vehicle instanceof Tameable && exited instanceof Player) {
Player player = (Player) exited;
if (vehicle instanceof Tameable && exited instanceof Player player && !Entities.isNPC(player)) {
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) {
@@ -532,10 +544,6 @@ public class RegionProtectionListener extends AbstractListener {
}
}
private boolean isWhitelistedEntity(Entity entity) {
return Entities.isNonPlayerCreature(entity);
}
/**
* Combine the flags from a delegate event with an array of flags.
*
@@ -554,4 +562,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;
}
}
@@ -0,0 +1,750 @@
/*
* 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.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.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.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;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.MoistureChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
/**
* The listener for block events.
*/
public class WorldGuardBlockListener extends AbstractListener {
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
super(plugin);
}
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (!wcfg.itemDurability) {
ItemStack held = player.getInventory().getItemInMainHand();
ItemMeta meta = held.getItemMeta();
if (meta != null) {
((Damageable) meta).setDamage(0);
held.setItemMeta(meta);
player.getInventory().setItemInMainHand(held);
}
}
}
/*
* Called when fluids flow.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material fromType = blockFrom.getType();
boolean isWater = Materials.isWater(fromType);
boolean isLava = fromType == Material.LAVA;
boolean isAir = fromType == Material.AIR;
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getType() == Material.SPONGE
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
}
}
}
}
}
/*if (plugin.classicWater && isWater) {
int blockBelow = blockFrom.getRelative(0, -1, 0).getTypeId();
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
blockFrom.setTypeId(9);
if (blockTo.getTypeId() == 0) {
blockTo.setTypeId(9);
}
return;
}
}*/
// Check the fluid block (from) whether it is air.
// If so and the target block is protected, cancel the event
if (!wcfg.preventWaterDamage.isEmpty()) {
Material targetId = blockTo.getType();
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
if (!wcfg.allowedLavaSpreadOver.isEmpty() && isLava) {
Material targetId = blockTo.getRelative(0, -1, 0).getType();
if (!wcfg.allowedLavaSpreadOver.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
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
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(blockFrom.getLocation()), (RegionAssociable) null, Flags.LAVA_FLOW))) {
event.setCancelled(true);
return;
}
}
/*
* Called when a block gets ignited.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(world);
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !getPlugin().hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (!wcfg.disableFireSpreadBlocks.isEmpty() && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
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 =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (wcfg.highFreqFlags && isFireSpread
&& !set.testState(null, Flags.FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && cause == IgniteCause.LAVA
&& !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.testState(null, Flags.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.testState(null, Flags.LIGHTNING)) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block is destroyed from burning.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
if (!wcfg.disableFireSpreadBlocks.isEmpty()) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(block.getType()).getId())) {
event.setCancelled(true);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
}
if (wcfg.isChestProtected(BukkitAdapter.adapt(event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Block block = event.getBlock();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (!set.testState(null, Flags.FIRE_SPREAD)) {
checkAndDestroyFireAround(block.getWorld(), x, y, z);
event.setCancelled(true);
}
}
}
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 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);
}
}
/*
* Called when block physics occurs.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
final Material id = event.getBlock().getType();
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if ((id == Material.SAND || id == Material.RED_SAND) && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == Material.NETHER_PORTAL && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
if (id == Material.LADDER && wcfg.ropeLadders) {
if (event.getBlock().getRelative(0, 1, 0).getType() == Material.LADDER) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a player places a block.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block target = event.getBlock();
World world = target.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && target.getType() == Material.SPONGE) {
if (wcfg.redstoneSponges && target.isBlockIndirectlyPowered()) {
return;
}
int ox = target.getX();
int oy = target.getY();
int oz = target.getZ();
SpongeUtil.clearSpongeWater(BukkitAdapter.adapt(world), ox, oy, oz);
}
}
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -1; cx <= 1; cx++) {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getType() == Material.SPONGE
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(BukkitAdapter.adapt(world), ox + cx, oy + cy, oz + cz);
} else if (sponge.getType() == Material.SPONGE
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(BukkitAdapter.adapt(world), ox + cx, oy + cy, oz + cz);
}
}
}
}
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.LEAF_DECAY))) {
event.setCancelled(true);
}
}
}
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material type = event.getNewState().getType();
if (event instanceof EntityBlockFormEvent) {
if (((EntityBlockFormEvent) event).getEntity() instanceof Snowman) {
if (wcfg.disableSnowmanTrails) {
event.setCancelled(true);
return;
}
}
return;
}
if (type == Material.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
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 == Material.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (!wcfg.allowedSnowFallOver.isEmpty()) {
Material targetId = event.getBlock().getRelative(0, -1, 0).getType();
if (!wcfg.allowedSnowFallOver.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
return;
}
}
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;
}
}
if (Materials.isUnwaxedCopper(event.getBlock().getType())) {
if (wcfg.disableCopperBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.COPPER_FADE))) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material newType = event.getNewState().getType(); // craftbukkit randomly gives AIR as event.getSource even if that block is not air
if (Materials.isMushroom(newType)) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
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 (newType == Material.GRASS_BLOCK) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
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 (newType == Material.MYCELIUM) {
if (wcfg.disableMyceliumSpread) {
event.setCancelled(true);
return;
}
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 (Materials.isVine(newType)) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
}
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;
}
}
if (Materials.isAmethystGrowth(newType) || newType == Material.POINTED_DRIPSTONE) {
if (wcfg.disableRockGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.ROCK_GROWTH))) {
event.setCancelled(true);
return;
}
}
if (Materials.isSculkGrowth(newType)) {
if (wcfg.disableSculkGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SCULK_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(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(loc), (RegionAssociable) null, Flags.CROP_GROWTH))) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (event.getBlock().getType() == Material.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
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;
}
} 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 && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SNOW_MELT))) {
event.setCancelled(true);
return;
}
} else if (event.getBlock().getType() == Material.FARMLAND) {
if (wcfg.disableSoilDehydration) {
event.setCancelled(true);
return;
}
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;
}
} 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 = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.blockOtherExplosions) {
event.setCancelled(true);
}
}
/**
* Called when the moisture level of a block changes
*/
@EventHandler(ignoreCancelled = true)
public void onMoistureChange(MoistureChangeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableSoilMoistureChange) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.MOISTURE_CHANGE))) {
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,76 @@
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.cause.Cause;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.InteropUtils;
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.FailedLoadRegionSet;
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.flags.StateFlag.State;
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.AbstractWindCharge;
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.WindCharge;
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;
@@ -44,12 +96,8 @@ import java.util.Set;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
public class WorldGuardEntityListener extends AbstractListener {
/**
* Construct the object;
@@ -57,35 +105,32 @@ public class WorldGuardEntityListener implements Listener {
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
WorldConfiguration wcfg = getWorldConfig(block.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;
}
if (block.getType() == Material.SNIFFER_EGG && wcfg.disableCreatureSnifferEggTrampling) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
@@ -96,16 +141,15 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
} else if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
@@ -119,7 +163,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 +179,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;
}
@@ -142,10 +190,12 @@ public class WorldGuardEntityListener implements Listener {
// handled anywhere else
if (type == DamageCause.BLOCK_EXPLOSION
&& (wcfg.blockOtherExplosions
|| (wcfg.explosionFlagCancellation
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.OTHER_EXPLOSION, defender.getLocation())))) {
|| ((wcfg.explosionFlagCancellation || Entities.isConsideredBuildingIfUsed(defender))
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(defender.getLocation()), (RegionAssociable) null, Flags.OTHER_EXPLOSION))))) {
event.setCancelled(true);
return;
}
}
}
@@ -160,19 +210,34 @@ public class WorldGuardEntityListener implements Listener {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(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 (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
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
if (wcfg.useRegions && wcfg.explosionFlagCancellation) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(defender.getLocation()))
.testState(null, Flags.OTHER_EXPLOSION)) {
event.setCancelled(true);
return;
}
}
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
@@ -209,20 +274,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;
}
}
}
}
}
@@ -239,32 +296,34 @@ public class WorldGuardEntityListener implements Listener {
return;
}
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = getPlugin().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;
}
}
if (event.getDamager() instanceof Fireball) {
Fireball fireball = (Fireball) event.getDamager();
if (event.getDamager() instanceof Fireball fireball) {
if (fireball instanceof WitherSkull) {
if (wcfg.blockWitherSkullExplosions) {
event.setCancelled(true);
return;
}
} else if (fireball instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -272,8 +331,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, Entities.getExplosionFlag(event.getDamager())) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
@@ -286,6 +345,10 @@ public class WorldGuardEntityListener implements Listener {
event.setCancelled(true);
return;
}
} else if (defender instanceof ArmorStand && Entities.isNonPlayerCreature(attacker)) {
if (wcfg.blockEntityArmorStandDestroy) {
event.setCancelled(true);
}
}
}
@@ -304,16 +367,15 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
} else if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (type == DamageCause.WITHER) {
// wither boss DoT tick
@@ -323,16 +385,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(getPlugin().wrapPlayer(player), Flags.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(player)) {
if (type == DamageCause.DROWNING && getConfig().hasAmphibiousMode(localPlayer)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -342,8 +404,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;
@@ -367,7 +429,7 @@ public class WorldGuardEntityListener implements Listener {
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
localPlayer.findFreePosition();
event.setCancelled(true);
return;
}
@@ -384,20 +446,16 @@ public class WorldGuardEntityListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = getConfig();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
if (ent != null) {
ent.remove();
}
ent.remove();
event.setCancelled(true);
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getLocation().getWorld());
if (ent instanceof Creeper) {
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
@@ -431,6 +489,11 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
} else if (ent instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -441,12 +504,10 @@ public class WorldGuardEntityListener implements Listener {
return;
}
}
// allow wither skull blocking since there is no dedicated flag atm
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (wcfg.useRegions && !(ent instanceof WindCharge)) {
for (Block block : event.blockList()) {
if (!plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation()).allows(DefaultFlag.GHAST_FIREBALL)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Entities.getExplosionFlag(ent))) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -462,6 +523,16 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.WITHER_DAMAGE)) {
event.blockList().clear();
event.setCancelled(true);
return;
}
}
}
} else {
// unhandled entity
if (wcfg.blockOtherExplosions) {
@@ -469,9 +540,9 @@ 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()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.OTHER_EXPLOSION)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -480,10 +551,9 @@ 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;
}
@@ -497,8 +567,7 @@ 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 = getConfig();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -507,6 +576,7 @@ public class WorldGuardEntityListener implements Listener {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (event.getEntityType() == EntityType.WITHER) {
if (wcfg.blockWitherExplosions) {
event.setCancelled(true);
@@ -527,28 +597,33 @@ public class WorldGuardEntityListener implements Listener {
event.setCancelled(true);
return;
}
} else if (event.getEntityType() == EntityType.PRIMED_TNT
|| event.getEntityType() == EntityType.MINECART_TNT) {
} else if (event.getEntityType() == EntityType.TNT
|| event.getEntityType() == EntityType.TNT_MINECART) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
} else if (event instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
if (!wcfg.blockPluginSpawning && Entities.isPluginSpawning(event.getSpawnReason())) {
return;
}
@@ -565,7 +640,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;
}
@@ -573,15 +650,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;
}
@@ -596,21 +674,77 @@ 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) {
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
switch (event.getEntityType()) {
case ENDER_DRAGON:
if (wcfg.blockEnderDragonPortalCreation) event.setCancelled(true);
break;
if (wcfg.useRegions && wcfg.regionNetherPortalProtection
&& event.getReason() == PortalCreateEvent.CreateReason.NETHER_PAIR
&& !event.getBlocks().isEmpty()) {
final com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getWorld());
final Cause cause = Cause.create(event.getEntity());
LocalPlayer localPlayer = null;
if (cause.getRootCause() instanceof Player player) {
if (wcfg.fakePlayerBuildOverride && InteropUtils.isFakePlayer(player)) {
return;
}
localPlayer = getPlugin().wrapPlayer(player);
if (WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, world)) {
return;
}
}
final RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer()
.get(world);
ApplicableRegionSet regions;
if (regionManager == null) {
regions = FailedLoadRegionSet.getInstance();
} else {
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);
regions = regionManager.getApplicableRegions(target);
}
final RegionAssociable associable = createRegionAssociable(cause);
final State buildState = StateFlag.denyToNone(regions.queryState(associable, Flags.BUILD));
if (!StateFlag.test(buildState, regions.queryState(associable, Flags.BLOCK_BREAK))
|| !StateFlag.test(buildState, regions.queryState(associable, Flags.BLOCK_PLACE))) {
if (localPlayer != null && !cause.isIndirect()) {
// NB there is no way to cancel the teleport without PTA (since PlayerPortal doesn't have block info)
// removing PTA was a mistake
String message = regions.queryValue(localPlayer, Flags.DENY_MESSAGE);
RegionProtectionListener.formatAndSendDenyMessage("create portals", localPlayer, message);
}
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) {
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(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());
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
if (wcfg.disablePigZap) {
event.setCancelled(true);
@@ -619,8 +753,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());
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
@@ -629,17 +763,44 @@ 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);
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && ent instanceof Player player && !Entities.isNPC(ent)
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
BukkitAdapter.adapt(ent.getLocation()),
WorldGuardPlugin.inst().wrapPlayer(player),
Flags.HEALTH_REGEN)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onFoodChange(FoodLevelChangeEvent event) {
if (event.getItem() != null) return;
HumanEntity ent = event.getEntity();
if (Entities.isNPC(ent)) return;
if (!(ent instanceof Player bukkitPlayer)) return;
if (event.getFoodLevel() > ent.getFoodLevel()) return;
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer(bukkitPlayer);
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (wcfg.useRegions
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
player.getLocation(), player, Flags.HUNGER_DRAIN)) {
event.setCancelled(true);
}
}
/**
@@ -650,28 +811,37 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
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) {
WorldConfiguration wcfg = getWorldConfig(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 || id == Material.RED_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) {
Location location = event.getBlock().getLocation();
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);
@@ -680,6 +850,15 @@ public class WorldGuardEntityListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(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.
@@ -688,15 +867,12 @@ public class WorldGuardEntityListener implements Listener {
* @return true if the event should be cancelled
*/
private boolean checkItemFrameProtection(Entity attacker, ItemFrame defender) {
World world = attacker.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
World world = defender.getWorld();
WorldConfiguration wcfg = getWorldConfig(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,13 @@
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.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;
@@ -34,7 +37,6 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
@@ -42,35 +44,18 @@ import org.bukkit.projectiles.ProjectileSource;
/**
* Listener for painting related events.
*
* @author BangL <henno.rickowski@gmail.com>
*/
public class WorldGuardHangingListener implements Listener {
public class WorldGuardHangingListener extends AbstractListener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardHangingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = getWorldConfig(world);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
@@ -87,7 +72,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 +83,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,34 +19,35 @@
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;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
@@ -55,55 +56,42 @@ 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;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Handles all events thrown in relation to a player.
*/
public class WorldGuardPlayerListener implements Listener {
public class WorldGuardPlayerListener extends AbstractListener {
private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName());
private static final Pattern opPattern = Pattern.compile("^/(?:bukkit:)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private WorldGuardPlugin plugin;
private static final Pattern opPattern = Pattern.compile("^/(?:minecraft:)?(?:bukkit:)?(?:de)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
super(plugin);
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@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 = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.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);
}
@@ -116,8 +104,8 @@ public class WorldGuardPlayerListener implements Listener {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
if (cfg.activityHaltToggle) {
player.sendMessage(ChatColor.YELLOW
@@ -126,7 +114,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 +122,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 +132,36 @@ 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 = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.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 = getPlugin().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 +170,13 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = getConfig();
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 +184,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,11 +212,11 @@ public class WorldGuardPlayerListener implements Listener {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
int slot = player.getInventory().getHeldItemSlot();
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -229,29 +232,22 @@ 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);
WorldConfiguration wcfg = getWorldConfig(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")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
for (int slot = 0; slot < 40; slot++) {
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -262,15 +258,13 @@ public class WorldGuardPlayerListener implements Listener {
}
if (wcfg.useRegions) {
//Block placedIn = block.getRelative(event.getBlockFace());
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
//ApplicableRegionSet placedInSet = plugin.getRegionContainer().createQuery().getApplicableRegions(placedIn.getLocation());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().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) && getPlugin().hasPermission(player, "worldguard.region.wand")) {
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.getApplicableRegions(BukkitAdapter.adapt(block.getLocation()), RegionQuery.QueryOption.SORT);
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 +274,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 +290,24 @@ 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);
WorldConfiguration wcfg = getWorldConfig(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;
}
if (type == Material.SNIFFER_EGG && wcfg.disablePlayerSnifferEggTrampling) {
event.setCancelled(true);
return;
}
@@ -315,19 +316,18 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (com.sk89q.worldguard.bukkit.util.Entities.isNPC(player)) return;
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(location);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
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));
}
}
}
@@ -335,12 +335,10 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
int newSlot = event.getNewSlot();
ItemStack heldItem = player.getInventory().getItem(newSlot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -352,87 +350,63 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
World world = event.getFrom().getWorld();
if (event.getTo() == null) {
// The target location for PlayerTeleportEvents can be null.
// Those events will be ignored by the server, so we can ignore them too.
return;
}
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (com.sk89q.worldguard.bukkit.util.Entities.isNPC(player)) return;
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.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) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet set = query.getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom = query.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;
}
@@ -442,20 +416,21 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
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);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.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 +438,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;
}
@@ -21,38 +21,26 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* @author zml2008
*/
public class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public class WorldGuardServerListener extends AbstractListener {
public WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
super(plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
getConfig().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
getConfig().updateCommandBookGodMode();
}
}
}
@@ -0,0 +1,80 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.listener;
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.Entities;
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;
import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.stream.Collectors;
public class WorldGuardVehicleListener extends AbstractListener {
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
super(plugin);
}
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
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();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.useRegions) {
// Did we move a block?
if (Locations.isDifferentBlock(BukkitAdapter.adapt(event.getFrom()), BukkitAdapter.adapt(event.getTo()))) {
for (Player player : playerPassengers) {
if (Entities.isNPC(player)) continue;
LocalPlayer localPlayer = getPlugin().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,43 +19,32 @@
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.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;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
public class WorldGuardWeatherListener implements Listener {
public class WorldGuardWeatherListener extends AbstractListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
@@ -70,8 +59,7 @@ 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());
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (event.toThunderState()) {
if (wcfg.disableThunder) {
@@ -86,21 +74,22 @@ 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());
WorldConfiguration wcfg = getWorldConfig(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;
@@ -32,36 +34,23 @@ import org.bukkit.event.world.WorldLoadEvent;
import java.util.logging.Logger;
public class WorldGuardWorldListener implements Listener {
public class WorldGuardWorldListener extends AbstractListener {
private static final Logger log = Logger.getLogger(WorldGuardWorldListener.class.getCanonicalName());
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
ConfigurationManager cfg = getConfig();
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 +76,7 @@ public class WorldGuardWorldListener implements Listener {
* @param world The specified world
*/
public void initWorld(World world) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
Loaded 100 of 468 files, more files were not shown because too many files have changed in this diff. Show more