Compare commits

...
642 Commits
Author SHA1 Message Date
NotAlexNoyle c67e16fbbf Update canonical Gitea link 2026-10-27 22:27:58 -04:00
NotAlexNoyle 5be4051a71 Exclude CODEOWNERS from language statistics 2026-10-27 08:25:16 -04:00
NotAlexNoyle 2249a4d393 Add CODEOWNERS (one staff approval) 2026-10-27 08:25:16 -04:00
NotAlexNoyle 1077a204cf Update regions.yml 2026-09-14 01:49:53 -04:00
NotAlexNoyle 7477ce5db5 Fix warzone creepers 2026-09-14 00:53:45 -04:00
NotAlexNoyle e8c1ea6459 Remove WGamemode-OG flag 2026-08-19 07:42:59 -04:00
NotAlexNoyle bdc08756cc Fix shop flags 2026-07-29 10:38:26 -04:00
NotAlexNoyle 66b4ffbb92 Update flags for QuickShop-OG 2026-07-22 08:33:21 -04:00
NotAlexNoyle 03dcdf5e82 Update worldguard flags 2026-07-16 19:48:39 -04:00
NotAlexNoyle b8a3272994 Fix /rg bypass 2026-06-17 05:37:07 -04:00
NotAlexNoyle 38c1d84f9e Fix hunger 2026-06-15 10:08:44 -04:00
NotAlexNoyle 9ee9d70730 Update configs 2026-06-07 09:19:49 -04:00
NotAlexNoyle cf8bca82ab FireFight-OG compatibility 2026-05-31 09:45:45 -04:00
NotAlexNoyle 46ae6c9c5e Use live TrueOG Network config files 2026-04-01 06:41:33 -04:00
NotAlexNoyle c7f1ae25d2 Update gradle to 8.14.3 2025-09-25 03:39:32 -04:00
NotAlexNoyle 58690eede0 Rebase 2025-01-01 23:50:04 -05: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 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
aromaa cb100bb797 Improve compatibility with the new onClearValue 2022-09-20 09:07:27 -04: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 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
wizjany 8b842e3a0d Release 6.1.2 for MC 1.9/1.10 2016-06-11 12:38:01 -04:00
Max Lee e38d98da00 Do not allow teleport inside of regions with the chorus-fruit-teleport deny flag set 2016-06-11 11:45:48 -04:00
wizjany 5c9ba2e22e Fix MC 1.7 compatibility to pistons. 2016-06-11 11:39:58 -04:00
wizjany e9ecb6d2a8 Treat elytra wall impact as fall damage.
Fixes WORLDGUARD-3654.
2016-06-11 11:29:01 -04:00
wizjany f5a554f4a4 block-potion-effects now blocks effects from arrows too.
Fixes WORLDGUARD-3692.
2016-06-11 10:44:50 -04:00
wizjany 53aadca45b Make fire-spread actually prevent spreading instead of just burning.
Same with lava-fire.
Fixes WORLDGUARD-3699.
2016-06-11 02:29:20 -04:00
wizjany 6c3dd4234d Protect against fishing rod usage in regions.
Fixes WORLDGUARD-3696.
Also be more explicit with some dependencies so IntelliJ stops complaining.
2016-06-11 01:22:40 -04:00
wizjany 5bd2125963 Doot doot.
Fixes WORLDGUARD-3695.
2016-05-26 02:52:43 -04:00
wizjany 8765bbb192 Last one?
Fixes WORLDGUARD-3694.
2016-05-25 21:09:43 -04:00
wizjany 53e8b780bc More backwards compat.
(Lots of people still on 1.8 it seems...)
Fixes WORLDGUARD-3693.
2016-05-25 13:29:55 -04:00
wizjany 0e252e41b2 Wrong error caught for backcompat. 2016-05-23 09:47:12 -04:00
wizjany 15a9c50ea4 Fix double output with region wand.
Also a bit of code cleanup.
2016-05-21 19:53:37 -04:00
wizjany d3acbdf382 Fix syntax error in last commit. 2016-05-21 15:08:33 -04:00
wizjany 4239bdc96d Fix issue with loading flags on non-existing regions from SQL.
No idea if this actually works or what the issue was ¯\_(ツ)_/¯
Thanks to EONABloodrayne for the updated statement (if it works)
and also blame them if it doesn't.
Fixes WORLDGUARD-3355.
2016-05-20 17:02:37 -04:00
wizjany 43a5bf1638 Handle BlockMultiPlaceEvent separately.
Unsure how much this is used but...
2016-05-20 16:48:44 -04:00
wizjany a8591e536a Add "chorus-fruit-teleport" flag to prevent teleporting with chorus fruits.
Fixes WORLDGUARD-3645.
2016-05-20 16:06:22 -04:00
wizjany 38dcdff0b6 Update/fixes for MC 1.9.
Fixes WORLDGUARD-3664, WORLDGUARD-3652, WORLDGUARD-3679, WORLDGUARD-3657, WORLDGUARD-3668.
2016-05-20 16:06:21 -04:00
wizjany 65e48d17d4 Fix another instace of chest casting exception. 2016-03-25 18:31:12 -04:00
wizjany c9b8e9f6a2 Target Java 7 for source compilation.
Also remove old pom file, since we don't use maven anymore.
Fixes WORLDGUARD-3642.
2016-03-02 15:59:31 -05:00
wizjany 93d454c675 Work around odd class casting with odder class casting.
Despite the API guaranteeing a block for chests, they are not actually BlockStates.
Fixes WORLDGUARD-3607. Probably.
2016-02-20 12:40:16 -05:00
wizjany ca4bb7a53d Update shadow plugin.
Fixes WORLDGUARD-3635.
2016-02-17 22:16:42 -05:00
wizjany c2054615db Use full class name for Grgit.
Because it apparently sometimes fails otherwise.
2016-01-16 23:19:43 -05:00
wizjany 6db2df4e29 Expand version in plugin.yml during gradle build. 2016-01-11 01:05:19 -05:00
Wizjany 536132a250 Merge pull request #350 from kosakriszi/master
Reset player saturation and exhaustion for heal command
2016-01-09 19:48:09 -05:00
kosakriszi 7c3b1ad20f Reset player saturation and exhaustion for heal command 2016-01-07 03:12:05 +01:00
wizjany 729f66afdf Should fix travis builds. 2016-01-06 00:23:15 -05:00
wizjany a7c2026414 Fireballs are now treated as projectiles.
Apparently this has existed for a few years now. Don't even ask.
Fixes WORLDGUARD-3611, WORLDGUARD-3476.
Potentially fixes lots of other issues with fireballs as well.
Other settings and so on seemed to have covered a lot though.
2016-01-05 01:09:57 -05:00
wizjany 9222b3d364 Doc file tweaks. 2015-11-13 20:51:05 -05:00
wizjany adcc41413d Clean up a few files. 2015-11-13 20:39:50 -05:00
wizjany ec08d7d73a Fix checkstyle for legacy module. 2015-11-13 20:04:51 -05:00
wizjany 3d5ee7b571 Gradle-ize. Prep for Sponge.
Old Bukkit code can still be found in the worldguard-legacy folder
and built with `gradle worldguard-legacy:build`. Hopefully nothing
got lost in the gradle-ization.
2015-11-13 19:12:55 -05:00
wizjany 32341393fe Armor stands no longer get removed by /stoplag.
Also restored MC1.7 compatibility to pistons.
2015-09-27 20:40:56 -04:00
Wizjany 0fcd42fdd5 Workbenches can now be used by default.
Since it was a source of common confusion.
Things like enderchests and anvils should be added to the interaction whitelist in config if you wish to unprotect them.
2015-08-30 16:04:27 -04:00
Wizjany e28b236a52 Add some missing 1.8 blocks. 2015-08-18 01:52:49 -04:00
wizjany 96e0ffd293 Regions now protect against pistons with slime blocks.
Fixes WORLDGUARD-3493.
2015-08-02 17:00:06 -04:00
wizjany 0ddc011a3c Fix wibbly wobbly timey wimey stuff.
Fixes WORLDGUARD-3527.
2015-08-02 16:05:47 -04:00
wizjany d320356045 Add tile entities to performance report. 2015-07-31 12:58:24 -04:00
wizjany 95bf6bc9b2 Be overly protective for creeper and enderdragon explosions.
Fixes WORLDGUARD-3522.
2015-07-06 01:39:39 -04:00
wizjany 1c4c213ed7 Switched order of greeting and farewell flags.
When going between two regions, the farewell flag of the region you're leaving should show up before the greeting flag of the region you're entering.
Fixes WORLDGUARD-3511
2015-07-06 00:23:46 -04:00
Wizjany c9eaec0ae8 Prevent NPE in portal code.
Fixes WORLDGUARD-3516
2015-06-27 00:42:08 -04:00
Wizjany fc0be7db09 Fix case-sensitivity when checking membership.
Probably.
2015-06-26 14:50:09 -04:00
wizjany dbbc31a4f4 Fix some consistency issues with both spawners and bonemeal. 2015-06-19 19:06:34 -04:00
wizjany 0f3e893aaf Force region claiming to use UUIDs.
Also remove owner params from the command, they were
ignored anyway. Claim only adds the player using the command.
Fixes WORLDGUARD-3504.
2015-06-19 18:08:20 -04:00
wizjany aa668916e4 Fix a typo in config node from last commit. 2015-06-19 17:49:14 -04:00
wizjany a426d2a42c Check correct bucket while milking cows.
Fixes WORLDGUARD-3508.
2015-06-19 17:02:09 -04:00
wizjany 5ff8b37ae8 Create a config option to enable portal protection.
Protection is off by default. Third-party portal plugins such as MV-NP
may interfere with portal protection and cause problems.
Fixes WORLDGUARD-3498.
2015-06-19 17:01:30 -04:00
wizjany 2d28e8db6d Make portal protection slightly less overprotective.
Fixes end portal usage.
Fixes WORLDGUARD-3497.
2015-06-08 15:08:46 -07:00
wizjany 463a356020 Overprotective nether portal protection.
Blocks any portal travel that might lead to portal creation in a protected area.
Fixes WORLDGUARD-3479.
2015-06-08 15:08:46 -07:00
sk89q 21d13cc72c Set version to 6.1.1-SNAPSHOT. 2015-06-08 15:08:28 -07:00
454 changed files with 27149 additions and 20540 deletions

No files matched your search

+3 -2
View File
@@ -1,2 +1,3 @@
*.java diff=java
*.java diff=java
.gitea/CODEOWNERS linguist-detectable=false
+3
View File
@@ -0,0 +1,3 @@
# Pull requests request review from the eligible staff team(s).
# One approval from either an Admin or Developer satisfies branch protection.
* @trueog/Admins @trueog/Developers
+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.
+14 -8
View File
@@ -1,13 +1,19 @@
/.classpath
/.project
/.settings
/target
.classpath
.project
.settings/
target/
.DS_Store
/*.iml
/.idea
/bin
/dependency-reduced-pom.xml
**/*.iml
**/.idea
bin/
dependency-reduced-pom.xml
*-private.sh
.gradle/
**/build/
out/
scripts/
+5 -4
View File
@@ -1,7 +1,8 @@
language: java
dist: trusty
jdk:
- oraclejdk7
- openjdk7
- openjdk6
- oraclejdk11
notifications:
email: false
email: false
before_install: chmod +x gradlew
script: ./gradlew build -S
+213
View File
@@ -1,5 +1,218 @@
# Changelog
## 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`).
* Added protection from slime block piston contraptions pushing into or pulling from regions.
* Added `chorus-fruit-teleport` flag, works similar to `enderpearl` to prevent teleportation.
* Added protection from pulling armor stands, items, and entities from protected regions.
* Changed order of greeting and farewell flags on adjacent regions. When leaving a region with a farewell flag and entering one with a greeting flag, the farewell message will be shown first now.
* Changed /heal command to also fill food/saturation meters.
* Changed fall damage prevention to also prevent flying into walls with elytra being fatal.
* Fixed fire-spread flag only preventing destruction, now prevents spreading too as per its name.
* Fixed creepers targeting players being able to blow things up in certain cases.
* Fixed armor stands being removed by /stoplag.
* Fixed some issues with fireballs being able to explode when ghast-fireball was set to deny.
* Fixed a lot of other minor issues.
## 6.1
* Added `exit-via-teleport` flag (default allow) to control exiting an exit=deny region via teleportation.
+42
View File
@@ -0,0 +1,42 @@
Compiling
=========
You can compile WorldGuard as long as you have some version of Java greater than or equal to 17 installed. Gradle will download JDK 17 specifically if needed,
but it needs some version of Java to bootstrap from.
Note that if you have JRE 17 installed, Gradle will currently attempt to use that to compile, which will not work. It is easiest to uninstall JRE 16 and
replace it with JDK 17.
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/>.
-52
View File
@@ -1,52 +0,0 @@
# New User Guide
Thank you for installing WorldGuard! By default, when you first install WorldGuard, most features will be disabled until you enable the ones that you want to use.
## Requirements
You will need to be using [Bukkit](http://dl.bukkit.org/) for your server or one of its derivatives (such as Spigot or Cauldron). If you are using Minecraft Forge, you will have to use Cauldron in order to use WorldGuard.
It is not possible to use WorldGuard with the plain vanilla server from Mojang.
## Installation
Installation is simple!
1. Extract the `WorldGuard.jar` file and put it into your server's `plugins` folder. If the folder does not exist yet, you can create it yourself.
2. Run the Bukkit server.
3. Look inside `plugins/WorldGuard` and configure the plugin as necessary. There are also in-game commands.
By default, only "ops" can use WorldGuard commands. If you install a permissions plugin, then you can assign fine grained permissions to your server's trusted users.
## Documentation
To learn how to use WorldGuard, check out [the wiki](http://wiki.sk89q.com/wiki/WorldGuard).
## Frequently Asked Questions
### How do I protect my spawn?
Check out the [region protection tutorial](http://wiki.sk89q.com/wiki/$%7Bproject.name%7D/Regions/Tutorial) on the wiki.
### Players can't do anything!
WorldGuard will typically not block something without also telling the user that he or she does not have permission. Please make sure that it's not another plugin that is preventing players from interacting with the world.
Also, be aware that spawn protection is a feature of vanilla Minecraft and you must disable that in `bukkit.yml`. It only allows ops to do anything in a specified radius around the world's spawn point.
### I made a region but anyone can build in it!
1. If players get a "you can't do that here" message but they are still able to build, it's because another plugin is likely undoing the protection offered by WorldGuard.
2. If no message is being sent, make sure that there is a region where you think one is.
### Where can I ask questions?
You can [ask questions on our forum](http://forum.sk89q.com) or visit us on IRC (irc.esper.net #sk89q).
### Where can I file a bug report or request a feature?
Visit our [issue tracker](http://youtrack.sk89q.com/dashboard). It's also used for WorldEdit and our other projects.
### Is WorldGuard open source?
Yes! [View the source code on GitHub](https://github.com/sk89q/worldguard).
+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.
+58 -46
View File
@@ -1,46 +1,58 @@
# ![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
[Maven](http://maven.apache.org). Detailed compilation information
[can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
Dependencies are automatically handled by Maven.
Contributing
------------
We happily accept contributions, especially through pull requests on GitHub.
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>
A fork of [WorldGuard](https://github.com/EngineHub/WorldGuard) 7.0.8 maintained by [TrueOG Network](https://true-og.net) for 1.19.4. WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
## Changes over WorldGuard:
- Gradle 8.0.2 -> 8.14.3.
- `build` copies the shaded jar to `build/libs/WorldGuard-<version>.jar` via `copyjar.sh`.
- Ships the live TrueOG Network `config.yml`, `config_world.yml`, and `worlds/world/regions.yml` as defaults. The world regions file is created on first run alongside the main config.
- New region flag `creeper-block-damage` (default allow). Set it to deny with `creeper-explosion` allowed to keep creeper blasts from breaking blocks while still damaging entities. This is how the spawn warzone is configured.
- Bucket use no longer plays the deny effect when a partner plugin's `safe-fluids` flag allows the action (FireFight-OG compatibility).
## Upstream description:
* 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). Run `./gradlew build` and pick up the plugin jar from `build/libs/`.
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
-----
* [TrueOG fork](https://git.trueog.net/trueog/WorldGuard)
* [Homepage](http://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](http://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [End-user documentation](https://worldguard.enginehub.org/en/latest/)
-55
View File
@@ -1,55 +0,0 @@
# Upgrading to WorldGuard 6
This is a **major upgrade**. However, it is relatively well-tested because many people have *accidentally* updated to version 6 when the Spigot team updated WorldGuard for 1.8 but did not update v5.9.
The version that you downloaded supports Minecraft 1.7.10 and 1.8.
**NEW DOCUMENTATION:** There is [new work-in-progress documentation](http://docs.enginehub.org/manual/worldguard/latest/). However, refer to the [older wiki](http://wiki.sk89q.com/wiki/WorldGuard) for missing pages.
## Downgrading to 5.9
When updating to v6, your region data will be updated to use player UUIDs rather than their names. That means that you **cannot downgrade** to WG 5.9 because it does not understand UUIDs and will remove all ownership data. However, you can use [Six2Five](https://github.com/sk89q/Six2Five/releases/tag/release-1.0) to downgrade region data stored as YAML.
Remember to make backups.
If you do not use region protection, then downgrading requires no extra steps.
## What's Changed?
There have been many changes, but the most important (and breaking ones) are listed below.
### Region Protection
The region protection has been optimized and aggressive caching has been added. That means that the impact of region protection when hundreds or thousands of regions exist has been minimized.
* UUID support was added. On first server start, your region data will be converted to use UUIDs. Names that lack a UUID (i.e. they refer to accounts that don't exist) will remain, but can be removed by re-running the conversion (see the config) after changing the configuration to remove unconverted names.
* Build protection for regions is now much more complete, and WorldGuard protects against entities and blocks making changes as if they were players. For example, TNT cannot be flung into a protected region and piston machines cannot push into a protected region. Liquid flow (lava and water) can also be checked, although this is disabled by default.
* Setting the `build` flag to `deny` will break pistons and Redstone. When you set the `build` flag to `deny`, you are essentially saying that *no one* can build at all. Now that blocks and entities are considered the same as players, they get blocked in that case. What's the solution? First of all, you probably do **not** want to set the build flag: remember, when you create a region, only members can build in it, so there's no need to change the `build` flag.
* If you want to deny building "in the wilderness," use `/rg flag __global__ passthrough deny`. Unset the `build` flag if you had set it to `deny`. As you may know, when you create a region, protection is automatically turned on (only members can build). If you don't want that, you can set a region's `passthrough` flag to `allow`. In the case of the global region, it *defaults* to `allow`, so you have to set it to `deny` to turn that off.
* Earlier versions of WorldGuard 6 changed the ``use`` flag to be much more encompassing, but this is **no longer the case**. The ``use`` flag now works like it did before in 5.x, only applying to things like doors, pressure plates, and levers. A new ``interact`` flag was added instead that controls all right clicks of blocks and entities.
* By default, the ``use`` flag is now set so only members of a region can use levers and doors within a region. If you want to disable this type of protection in all protected regions, use `/rg flag __global__ use allow`.
* Region groups for flags now work properly. You can set a certain flag to apply to only a certain group (owners, members, nonmembers, nonowners, all). Before, it only worked correctly for some flags. Region groups can be set like this: `/rg flag spawn pvp -g nonmembers deny`.
* In WG 5.9, some flags had a default region group of "non-members." That means that if you did `/rg flag spawn chest-access deny`, only non-members would be unable to open chests. In WG 6, you have to explicitly specify this: `/rg flag spawn chest-access -g nonmembers deny`.
* It is now possible to change the message that users get when they are prevented from interacting with blocks or entities. This message is defined as a region flag, so you can set it on the `__global__` region or override it in a specific region. In addition, the tone and color of the default message has been softened, but you are free to change it entirely.
* The MySQL code was substantially rewritten to be faster and more efficient. Some changes are needed to the table structure, but WorldGuard is now capable of performing those automatically. However, those who use table prefixes *may* run into trouble.
### Blacklist
* If you want to blacklist only water and lava blocks and not buckets, you can no longer apply `on-place` to water or lava blocks because it will also deny the use of buckets. If you wish to deny the use of just the liquid blocks, use `on-use`. This is because WorldGuard now considers the use of a bucket also the placement of a liquid block.
### Miscellaneous
* In the rare situation that you are user of the "auto-invincibility" and "auto-no-drowning" groups (`wg-invincible` and `wg-amphibious`), you now have to enable these features in the config (`auto-invincible-group: true` and `auto-no-drowning-group: true`). This is because some permission plugins have been causing severe hang ups whenever it is queried for a player's groups, which, in this case, happens to include when the player joins.
## Known Incompatibilities
Plugins that utilize WorldGuard's API may not work anymore. They may crash with errors. The API has changed somewhat.
* Spigot:
* `settings.global-api-cache`, if enabled, will crash WG UUID lookups (fixed in Spigot build #1625)
## Other Changes
The rest of the changes can be found in the CHANGELOG file.
In addition, there is [new work-in-progress documentation](http://docs.enginehub.org/manual/worldguard/latest/) that describes some of the new features.
+26
View File
@@ -0,0 +1,26 @@
import org.ajoberstar.grgit.Grgit
logger.lifecycle("""
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Try running 'build' in a separate Gradle run
2) Use gradlew and not gradle
3) If you still need help, ask on Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
applyRootArtifactoryConfig()
if (!project.hasProperty("gitCommitHash")) {
apply(plugin = "org.ajoberstar.grgit")
ext["gitCommitHash"] = try {
Grgit.open(mapOf("currentDir" to project.rootDir))?.head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no.git.id"
}
}
+17
View File
@@ -0,0 +1,17 @@
plugins {
`kotlin-dsl`
kotlin("jvm") version embeddedKotlinVersion
}
repositories {
mavenCentral()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation("gradle.plugin.org.cadixdev.gradle:licenser:0.6.1")
implementation("org.ajoberstar.grgit:grgit-gradle:4.1.1")
implementation("gradle.plugin.com.github.johnrengelman:shadow:7.1.2")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.27.1")
}
@@ -0,0 +1,40 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.named
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
private const val ARTIFACTORY_USER = "artifactory_user"
private const val ARTIFACTORY_PASSWORD = "artifactory_password"
fun Project.applyRootArtifactoryConfig() {
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
apply(plugin = "com.jfrog.artifactory")
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
isSkip = true
}
}
fun Project.applyCommonArtifactoryConfig() {
tasks.named<ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
+38
View File
@@ -0,0 +1,38 @@
import org.cadixdev.gradle.licenser.LicenseExtension
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.repositories
import org.gradle.kotlin.dsl.the
fun Project.applyCommonConfiguration() {
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(5, "MINUTES")
}
}
plugins.withId("java") {
the<JavaPluginExtension>().toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
apply(plugin = "org.cadixdev.licenser")
configure<LicenseExtension> {
header(rootProject.file("HEADER.txt"))
include("**/*.java")
include("**/*.kt")
}
}
+12
View File
@@ -0,0 +1,12 @@
import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.sourceSets: SourceSetContainer
get() = the<JavaPluginConvention>().sourceSets
+171
View File
@@ -0,0 +1,171 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.attributes.Bundling
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.DocsType
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.Usage
import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.component.SoftwareComponentFactory
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import javax.inject.Inject
fun Project.applyLibrariesConfiguration() {
applyCommonConfiguration()
apply(plugin = "java-base")
apply(plugin = "maven-publish")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
configurations {
create("shade")
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile"
)
tasks.register<ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
dependencies {
exclude(dependency("com.google.code.findbugs:jsr305"))
}
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
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, 8)
}
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, 8)
}
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)
}
}
}
applyCommonArtifactoryConfig()
}
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)
}
}
+113
View File
@@ -0,0 +1,113 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
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.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import org.gradle.kotlin.dsl.the
fun Project.applyPlatformAndCoreConfiguration() {
applyCommonConfiguration()
apply(plugin = "java")
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "maven-publish")
apply(plugin = "checkstyle")
apply(plugin = "com.jfrog.artifactory")
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "10.3"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testCompileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"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 as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
the<JavaPluginExtension>().withJavadocJar()
if (name == "worldguard-core" || name == "worldguard-bukkit") {
the<JavaPluginExtension>().withSourcesJar()
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(components["java"])
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
applyCommonArtifactoryConfig()
}
fun Project.applyShadowConfiguration() {
apply(plugin = "com.github.johnrengelman.shadow")
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
//include(project(":worldguard-libs:${project.name.replace("worldguard-", "")}"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core:3.0"))
}
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
}
val javaComponent = components["java"] as AdhocComponentWithVariants
javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) {
skip()
}
}
+10
View File
@@ -0,0 +1,10 @@
object Versions {
// const val PISTON = "0.4.3"
// const val AUTO_VALUE = "1.6.5"
const val WORLDEDIT = "7.2.12"
const val JUNIT = "5.9.1"
const val MOCKITO = "4.9.0"
const val SQUIRRELID = "0.3.2"
const val GUAVA = "31.1-jre"
const val FINDBUGS = "3.0.2"
}
-63
View File
@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ WorldGuard, a suite of tools for Minecraft
~ Copyright (C) sk89q <http://www.sk89q.com>
~ Copyright (C) WorldGuard team and contributors
~
~ This program is free software: you can redistribute it and/or modify it
~ under the terms of the GNU Lesser General Public License as published by the
~ Free Software Foundation, either version 3 of the License, or
~ (at your option) any later version.
~
~ This program is distributed in the hope that it will be useful, but WITHOUT
~ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
~ FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>tar.bz2</format>
<format>zip</format>
</formats>
<files>
<file>
<source>${project.build.directory}/${artifactId}-${project.version}.jar</source>
<outputDirectory>/</outputDirectory>
<filtered>false</filtered>
</file>
<file>
<source>${project.build.directory}/CHANGELOG.html</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>${project.build.directory}/INSTALL.html</source>
<destName>README.html</destName>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>${project.build.directory}/UPGRADE.html</source>
<destName>READ_BEFORE_UPGRADING_FROM_V5.html</destName>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
</files>
<fileSets>
<fileSet>
<includes>
<include>contrib/blacklist_table.sql</include>
<include>contrib/region_manual_update_20110325.sql</include>
</includes>
</fileSet>
</fileSets>
</assembly>
+63
View File
@@ -0,0 +1,63 @@
<?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">
<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 WG where it shouldn't belong, etc.
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="${config_loc}/import-control.xml"/>
</module>
<!-- Code -->
<module name="HideUtilityClassConstructor"/> <!-- Utility classes should not have a constructor -->
<module name="CovariantEquals"/>
<module name="EqualsHashCode"/> <!-- equals() and hashCode() go together -->
<module name="NestedTryDepth"> <!-- SHOULD not need to adjust this -->
<property name="max" value="2"/>
</module>
<module name="SuperFinalize"/> <!-- We don't actually use this -->
<!-- Style -->
<module name="LeftCurly"> <!-- Left brace never goes on another line -->
<property name="option" value="eol"/>
</module> <!-- We don't check right brace -->
<module name="DefaultComesLast"/> <!-- default case in switch should be last -->
<module name="GenericWhitespace"/>
<!-- Naming -->
<module name="ClassTypeParameterName">
<property name="format" value="^[A-Z][a-zA-Z0-9]*$"/>
</module>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<!-- <module name="PackageName"/> Unlikely that we would miss this in a PR -->
<module name="ParameterName"/>
<!-- <module name="TypeName"/> Unlikely that we would miss this in a PR -->
</module>
</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/>.
*/
+28 -30
View File
@@ -1,22 +1,3 @@
<!--
~ WorldGuard, a suite of tools for Minecraft
~ Copyright (C) sk89q <http://www.sk89q.com>
~ Copyright (C) WorldGuard team and contributors
~
~ This program is free software: you can redistribute it and/or modify it
~ under the terms of the GNU Lesser General Public License as published by the
~ Free Software Foundation, either version 3 of the License, or
~ (at your option) any later version.
~
~ This program is distributed in the hope that it will be useful, but WITHOUT
~ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
~ FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<!DOCTYPE import-control PUBLIC
"-//Puppy Crawl//DTD Import Control 1.1//EN"
"http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
@@ -25,17 +6,34 @@
<allow pkg="java"/>
<allow pkg="javax"/>
<allow pkg="org.junit"/>
<allow pkg="junit"/>
<allow pkg="org.mockito"/>
<allow pkg="org.hamcrest"/>
<allow pkg="org.mockito"/>
<allow pkg="junit.framework"/>
<allow pkg="com.sk89q"/>
<allow pkg="org.enginehub"/>
<allow pkg="org.bukkit"/>
<allow pkg="org.yaml.snakeyaml"/>
<allow pkg="au.com.bytecode.opencsv"/>
<allow pkg="org.khelekore.prtree"/>
<allow pkg="com.google.common"/>
<allow pkg="com.jolbox.bonecp"/>
<allow pkg="org.flywaydb.core"/>
<allow pkg="org.json.simple"/>
</import-control>
<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="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>
</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>
-3
View File
@@ -1,3 +0,0 @@
</div>
</body>
</html>
-368
View File
@@ -1,368 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>WorldGuard - titleToken</title>
<style>
body {
margin: 0;
padding: 2em 2em 3em 2em;
color: #333;
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif;
font-size: 15px;
line-height: 1.5;
word-wrap: break-word;
}
.wrapper {
margin: auto;
max-width: 750px;
}
a {
background: transparent;
}
a:active,
a:hover {
outline: 0;
}
strong {
font-weight: bold;
}
h1 {
font-size: 2em;
margin: 0 0 0.67em 0;
}
img {
border: 0;
}
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
pre {
font-family: monospace, monospace;
font-size: 1em;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
* {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
a {
color: #4183c4;
text-decoration: none;
}
a:hover,
a:focus,
a:active {
text-decoration: underline;
}
hr {
height: 0;
margin: 15px 0;
overflow: hidden;
background: transparent;
border: 0;
border-bottom: 1px solid #ddd;
}
hr:before,
hr:after {
display: table;
content: " ";
}
hr:after {
clear: both;
}
blockquote {
margin: 0;
}
ul,
ol {
padding: 0;
margin-top: 0;
margin-bottom: 0;
}
ol ol {
list-style-type: lower-roman;
}
dd {
margin-left: 0;
}
code,
pre {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 12px;
}
pre {
margin-top: 0;
margin-bottom: 0;
}
*:first-child {
margin-top: 0 !important;
}
*:last-child {
margin-bottom: 0 !important;
}
.anchor {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: block;
padding-right: 6px;
padding-left: 30px;
margin-left: -30px;
}
.anchor:focus {
outline: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
position: relative;
margin-top: 1.5em;
margin-bottom: 16px;
font-weight: bold;
line-height: 1.4;
}
h1 {
padding-bottom: 0.3em;
font-size: 2.1em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}
h2 {
padding-bottom: 0.3em;
font-size: 1.65em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}
h3 {
font-size: 1.2em;
line-height: 1.43;
}
h4 {
font-size: 1.1em;
}
h5 {
font-size: 1em;
}
h6 {
font-size: 1em;
color: #777;
}
p,
blockquote,
ul,
ol,
dl,
table,
pre {
margin-top: 0;
margin-bottom: 16px;
}
hr {
height: 4px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
}
ul,
ol {
padding-left: 2em;
}
ol ol,
ol ul {
margin-top: 0;
margin-bottom: 0;
}
li>p {
margin-top: 16px;
}
dl {
padding: 0;
}
dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: bold;
}
dl dd {
padding: 0 16px;
margin-bottom: 16px;
}
blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
blockquote>:first-child {
margin-top: 0;
}
blockquote>:last-child {
margin-bottom: 0;
}
table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all;
}
table th {
font-weight: bold;
}
table th,
table td {
padding: 6px 13px;
border: 1px solid #ddd;
}
table tr {
background-color: #fff;
border-top: 1px solid #ccc;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
img {
max-width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
code {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
}
code:before,
code:after {
letter-spacing: -0.2em;
content: "\00a0";
}
pre>code {
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}
.highlight {
margin-bottom: 16px;
}
.highlight pre,
pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border-radius: 3px;
}
.highlight pre {
margin-bottom: 0;
word-break: normal;
}
pre {
word-wrap: normal;
}
pre code {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}
pre code:before,
pre code:after {
content: normal;
}
</style>
</head>
<body>
<div class="wrapper">
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
VERSION="$1"
# Ensure the target directory exists
mkdir -p build/libs
# Copy and rename the jar, using $VERSION in the final filename
cp worldguard-bukkit/build/libs/*-dist.jar "build/libs/WorldGuard-${VERSION}.jar"
+2
View File
@@ -0,0 +1,2 @@
group=com.sk89q.worldguard
version=7.0.8
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+244
View File
@@ -0,0 +1,244 @@
#!/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 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/.
#
##############################################################################
# Attempt to set APP_HOME
# 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##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
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
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
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.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
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=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=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# 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.
# 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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
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
+92
View File
@@ -0,0 +1,92 @@
@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
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
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% 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.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
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.
goto fail
: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 %*
:end
@rem End local scope for the variables with windows NT shell
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!
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
:omega
-525
View File
@@ -1,525 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.1</version>
<packaging>jar</packaging>
<!-- Project information -->
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
<license>
<name>GNU General Public License 2.0</name>
<url>LICENSE.txt</url>
<distribution>repo</distribution>
<comments>License on all contributions</comments>
</license>
</licenses>
<issueManagement>
<system>YouTrack</system>
<url>http://youtrack.sk89q.com</url>
</issueManagement>
<ciManagement>
<system>Jenkins</system>
<url>http://build.sk89q.com</url>
</ciManagement>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
</scm>
<mailingLists>
<mailingList>
<name>Developer Discussion</name>
<archive>https://groups.google.com/d/forum/sk-dev-discuss</archive>
</mailingList>
</mailingLists>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
<repository>
<id>maven.sk89q.com</id>
<url>http://maven.sk89q.com/artifactory/libs-release-local</url>
</repository>
<snapshotRepository>
<id>maven.sk89q.com-snapshot</id>
<url>http://maven.sk89q.com/artifactory/libs-snapshot-local</url>
</snapshotRepository>
</distributionManagement>
<properties> <!-- Fix encoding warnings -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.5.8</version>
<scope>compile</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sk89q.spigot</groupId>
<artifactId>bukkit-classloader-check</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8.6-R0.1-SNAPSHOT</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.3</version>
<scope>compile</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<!-- Contains parts of Guava that are not compatible
between Bukkit 10.0.1 and 17+ -->
<groupId>com.sk89q</groupId>
<artifactId>guavabackport</artifactId>
<version>1.1</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>1.3.9</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>3.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>squirrelid</artifactId>
<version>0.1.0</version>
<scope>compile</scope>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.2.1</version>
<scope>test</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions> <!-- Used for uploading the docs -->
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
<resource>
<targetPath>migrations/</targetPath>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources/migrations/</directory>
</resource>
</resources>
<plugins>
<!-- Check style -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.12</version>
<executions>
<execution>
<id>verify-style</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirectory>${basedir}/src</sourceDirectory>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<logViolationsToConsole>true</logViolationsToConsole>
<checkstyleRules>
<module name="Checker">
<!-- Tabs are strictly banned -->
<module name="FileTabCharacter"/>
<module name="TreeWalker">
<!-- Important basics -->
<!-- <module name="PackageDeclaration"/> Unlikely that we would miss this in a PR -->
<module name="OuterTypeFilename"/> <!-- TypeName -> TypeName.java -->
<!--
Control package usage, so people don't insert Bukkit into WE where it shouldn't belong, etc.
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="${basedir}/config/checkstyle/import-control.xml"/>
</module>
<!-- Code -->
<module name="HideUtilityClassConstructor"/> <!-- Utility classes should not have a constructor -->
<module name="CovariantEquals"/>
<module name="EqualsHashCode"/> <!-- equals() and hashCode() go together -->
<module name="NestedTryDepth"> <!-- SHOULD not need to adjust this -->
<property name="max" value="2"/>
</module>
<module name="SuperFinalize"/> <!-- We don't actually use this -->
<module name="JUnitTestCase"/> <!-- Checks tearDown(), setUp() etc. -->
<!-- Style -->
<module name="LeftCurly"> <!-- Left brace never goes on another line -->
<property name="option" value="eol"/>
</module> <!-- We don't check right brance -->
<module name="DefaultComesLast"/> <!-- default case in switch should be last -->
<module name="GenericWhitespace"/>
<!-- Naming -->
<module name="ClassTypeParameterName">
<property name="format" value="^[A-Z][a-zA-Z0-9]*$"/>
</module>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z_][a-zA-Z0-9]*$"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
</module>
<!-- <module name="PackageName"/> Unlikely that we would miss this in a PR -->
<module name="ParameterName"/>
<!-- <module name="TypeName"/> Unlikely that we would miss this in a PR -->
</module>
<!-- Require the header, something that many people forget and we hate to fix -->
<!-- You should configure the header in your IDE -->
<module name="Header">
<property name="headerFile" value="${basedir}/config/checkstyle/header.txt"/>
<property name="fileExtensions" value="java"/>
</module>
</module>
</checkstyleRules>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
<include>org.flywaydb:flyway-core</include>
<include>com.sk89q:squirrelid</include>
<include>com.sk89q:guavabackport</include>
<include>com.googlecode.json-simple:json-simple</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.sk89q.guavabackport</pattern>
<shadedPattern>com.sk89q.worldguard.internal.guava</shadedPattern>
</relocation>
<relocation>
<pattern>org.flywaydb</pattern>
<shadedPattern>com.sk89q.worldguard.internal.flywaydb</shadedPattern>
</relocation>
<relocation>
<pattern>com.sk89q.squirrelid</pattern>
<shadedPattern>com.sk89q.worldguard.util.profile</shadedPattern>
</relocation>
<relocation>
<pattern>org.json.simple</pattern>
<shadedPattern>com.sk89q.worldguard.util.jsonsimple</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.ruleoftech</groupId>
<artifactId>markdown-page-generator-plugin</artifactId>
<version>0.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<inputDirectory>${basedir}</inputDirectory>
<outputDirectory>${project.build.directory}</outputDirectory>
<headerHtmlFile>${project.basedir}/config/markdown/header.html</headerHtmlFile>
<footerHtmlFile>${project.basedir}/config/markdown/footer.html</footerHtmlFile>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/config/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</project>
+7
View File
@@ -0,0 +1,7 @@
rootProject.name = "worldguard"
include("worldguard-libs")
include("worldguard-libs:core")
include("worldguard-core")
//include("worldguard-libs:bukkit")
include("worldguard-bukkit")
@@ -1,122 +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/>.
*/
package com.sk89q.worldguard;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.List;
import java.util.UUID;
public abstract class LocalPlayer implements RegionAssociable {
/**
* Get this player's name.
*
* @return The player's name
*/
public abstract String getName();
/**
* Get this player's unique ID.
*
* @return a UUID
*/
public abstract UUID getUniqueId();
/**
* Returns true if this player is inside a group.
*
* @param group The group to check
* @return Whether this player is in {@code group}
*/
public abstract boolean hasGroup(String group);
/**
* Get this player's position.
*
* @return The player's position
*/
public abstract Vector getPosition();
/**
* Kick this player.
*
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban this player.
*
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
/**
* Send this player a message.
*
* @param msg The message to send to the player
*/
public abstract void printRaw(String msg);
/**
* Get this player's list of groups.
*
* @return The groups this player is in
*/
public abstract String[] getGroups();
/**
* Returns whether this player has permission.
*
* @param perm The permission to check
* @return Whether this player has {@code perm}
*/
public abstract boolean hasPermission(String perm);
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
boolean member = false;
for (ProtectedRegion region : regions) {
if (region.isOwner(this)) {
return Association.OWNER;
} else if (!member && region.isMember(this)) {
member = true;
}
}
return member ? Association.MEMBER : Association.NON_MEMBER;
}
@Override
public boolean equals(Object obj) {
return obj instanceof LocalPlayer && ((LocalPlayer) obj).getName().equals(getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
}
@@ -1,123 +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/>.
*/
package com.sk89q.worldguard.blacklist.target;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.sk89q.guavabackport.collect.Range;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.util.Enums;
import org.bukkit.Material;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TargetMatcherParser {
private static final Pattern DATA_VALUE_PATTERN = Pattern.compile("^([^:]+):([^:]+)$");
private static final Pattern LESS_THAN_PATTERN = Pattern.compile("^<=\\s*([0-9]+)$");
private static final Pattern GREATER_THAN_PATTERN = Pattern.compile("^>=\\s*([0-9]+)$");
private static final Pattern RANGE_PATTERN = Pattern.compile("^([0-9]+)\\s*-\\s*([0-9]+)$");
public TargetMatcher fromInput(String input) throws TargetMatcherParseException {
Matcher matcher = DATA_VALUE_PATTERN.matcher(input.trim());
if (matcher.matches()) {
return new DataValueRangeMatcher(parseType(matcher.group(1)), parseDataValueRanges(matcher.group(2)));
} else {
return new WildcardDataMatcher(parseType(input));
}
}
private int parseType(String input) throws TargetMatcherParseException {
input = input.trim();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
int id = getItemID(input);
if (id > 0) {
return id;
}
Material material = Enums.findFuzzyByValue(Material.class, input);
if (material != null) {
return material.getId();
}
throw new TargetMatcherParseException("Unknown block or item name: " + input);
}
}
private Predicate<Short> parseDataValueRanges(String input) throws TargetMatcherParseException {
List<Predicate<Short>> predicates = new ArrayList<Predicate<Short>>();
for (String part : input.split(";")) {
predicates.add(parseRange(part));
}
return Predicates.or(predicates);
}
private Predicate<Short> parseRange(String input) throws TargetMatcherParseException {
input = input.trim();
Matcher matcher;
matcher = LESS_THAN_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.atMost(Short.parseShort(matcher.group(1)));
}
matcher = GREATER_THAN_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.atLeast(Short.parseShort(matcher.group(1)));
}
matcher = RANGE_PATTERN.matcher(input);
if (matcher.matches()) {
return Range.closed(Short.parseShort(matcher.group(1)), Short.parseShort(matcher.group(2)));
}
try {
short s = Short.parseShort(input);
return Range.closed(s, s);
} catch (NumberFormatException e) {
throw new TargetMatcherParseException("Unknown data value range: " + input);
}
}
/**
* Get an item's ID from its name.
*
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
if (type != null) {
return type.getID();
} else {
return -1;
}
}
}
@@ -1,78 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
class BukkitOfflinePlayer extends LocalPlayer {
private final OfflinePlayer player;
BukkitOfflinePlayer(OfflinePlayer offlinePlayer) {
this.player = offlinePlayer;
}
@Override
public String getName() {
return player.getName();
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean hasGroup(String group) {
return false;
}
@Override
public Vector getPosition() {
return Vector.ZERO;
}
@Override
public void kick(String msg) {
}
@Override
public void ban(String msg) {
}
@Override
public void printRaw(String msg) {
}
@Override
public String[] getGroups() {
return new String[0];
}
@Override
public boolean hasPermission(String perm) {
return false;
}
}
@@ -1,111 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
public class BukkitPlayer extends LocalPlayer {
private final WorldGuardPlugin plugin;
private final Player player;
private final String name;
private final boolean silenced;
public BukkitPlayer(WorldGuardPlugin plugin, Player player) {
this(plugin, player, false);
}
BukkitPlayer(WorldGuardPlugin plugin, Player player, boolean silenced) {
checkNotNull(plugin);
checkNotNull(player);
this.plugin = plugin;
this.player = player;
// getName() takes longer than before in newer versions of Minecraft
this.name = player.getName();
this.silenced = silenced;
}
@Override
public String getName() {
return name;
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(player, group);
}
@Override
public Vector getPosition() {
Location loc = player.getLocation();
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
@Override
public void kick(String msg) {
if (!silenced) {
player.kickPlayer(msg);
}
}
@Override
public void ban(String msg) {
if (!silenced) {
player.setBanned(true);
player.kickPlayer(msg);
}
}
@Override
public String[] getGroups() {
return plugin.getGroups(player);
}
@Override
public void printRaw(String msg) {
if (!silenced) {
player.sendMessage(msg);
}
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(player, perm);
}
public Player getPlayer() {
return player;
}
}
@@ -1,401 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import com.google.common.collect.ImmutableList;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.target.MaterialTarget;
import com.sk89q.worldguard.blacklist.target.Target;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
public class BukkitUtil {
private static Method ONLINE_PLAYERS_METHOD;
private BukkitUtil() {
}
/**
* Converts the location of a Bukkit block to a WorldEdit vector.
*
* @param block The block to convert
* @return The block's location as a BlockVector
*/
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
/**
* Converts a Bukkit location to a WorldEdit vector.
*
* @param loc A Bukkit Location
* @return A Vector with the location's x, y, and z values
*/
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
/**
* Converts a Bukkit vector to a WorldEdit vector.
*
* @param vector The Bukkit vector
* @return A WorldEdit vector with the same values as the Bukkit vector.
*/
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
}
/**
* Converts a WorldEdit vector to a Bukkit location.
*
* @param world The World to create the new Location with
* @param vec The vector to use for coordinates
* @return The Vector as a location with a World of world
*/
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Create a dummy region that encompasses the size of a chunk.
*
* @param chunk The chunk
* @return The dummy region
*/
public static ProtectedRegion toRegion(Chunk chunk) {
World world = chunk.getWorld();
int minX = chunk.getX() << 4;
int minZ = chunk.getZ() << 4;
return new ProtectedCuboidRegion("_", new BlockVector(minX, 0, minZ), new BlockVector(minX + 15, world.getMaxHeight(), minZ + 15));
}
/**
* Matches one player based on name.
*
* @param server The server to check
* @param name The name to attempt to match
* @deprecated see {@link WorldGuardPlugin#matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @return The matched player if any, otherwise null
*/
@Deprecated
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
return null;
}
return players.get(0);
}
/**
* Drops a sign item and removes a sign.
*
* @param block The block
* @deprecated see {@link org.bukkit.block.Block#breakNaturally()}
*/
@Deprecated
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(ItemID.SIGN, 1));
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
* @param world
* @param ox
* @param oy
* @param oz
*/
public static void setBlockToWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 0) {
block.setTypeId(8);
}
}
/**
* Checks if the given block is water
*
* @param world the world
* @param ox x
* @param oy y
* @param oz z
* @return true if it's water
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
return id == 8 || id == 9;
}
/**
* 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;
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
* a series of two free blocks. The player will be teleported to
* that free position.
*
* @param player
*/
public static void findFreePosition(Player player) {
Location loc = player.getLocation();
int x = loc.getBlockX();
int y = Math.max(0, loc.getBlockY());
int origY = y;
int z = loc.getBlockZ();
World world = player.getWorld();
byte free = 0;
while (y <= world.getMaxHeight() + 1) {
if (BlockType.canPassThrough(world.getBlockTypeIdAt(x, y, z))) {
free++;
} else {
free = 0;
}
if (free == 2) {
if (y - 1 != origY || y == 1) {
loc.setX(x + 0.5);
loc.setY(y);
loc.setZ(z + 0.5);
if (y <= 2 && world.getBlockAt(x,0,z).getTypeId() == BlockID.AIR) {
world.getBlockAt(x,0,z).setTypeId(20);
loc.setY(2);
}
player.setFallDistance(0F);
player.teleport(loc);
}
return;
}
y++;
}
}
/**
* Replace color macros in a string. The macros are in the form of `[char]
* where char represents the color. R is for red, Y is for yellow,
* G is for green, C is for cyan, B is for blue, and P is for purple.
* The uppercase versions of those are the darker shades, while the
* lowercase versions are the lighter shades. For white, it's 'w', and
* 0-2 are black, dark grey, and grey, respectively.
*
* @param str
* @return color-coded string
*/
public static String replaceColorMacros(String str) {
str = str.replace("&r", ChatColor.RED.toString());
str = str.replace("&R", ChatColor.DARK_RED.toString());
str = str.replace("&y", ChatColor.YELLOW.toString());
str = str.replace("&Y", ChatColor.GOLD.toString());
str = str.replace("&g", ChatColor.GREEN.toString());
str = str.replace("&G", ChatColor.DARK_GREEN.toString());
str = str.replace("&c", ChatColor.AQUA.toString());
str = str.replace("&C", ChatColor.DARK_AQUA.toString());
str = str.replace("&b", ChatColor.BLUE.toString());
str = str.replace("&B", ChatColor.DARK_BLUE.toString());
str = str.replace("&p", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("&P", ChatColor.DARK_PURPLE.toString());
str = str.replace("&0", ChatColor.BLACK.toString());
str = str.replace("&1", ChatColor.DARK_GRAY.toString());
str = str.replace("&2", ChatColor.GRAY.toString());
str = str.replace("&w", ChatColor.WHITE.toString());
str = str.replace("&k", ChatColor.MAGIC.toString());
str = str.replace("&l", ChatColor.BOLD.toString());
str = str.replace("&m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("&n", ChatColor.UNDERLINE.toString());
str = str.replace("&o", ChatColor.ITALIC.toString());
str = str.replace("&x", ChatColor.RESET.toString());
return str;
}
/**
* Returns whether an entity should be removed for the halt activity mode.
*
* @param entity
* @return true if it's to be removed
*/
public static boolean isIntensiveEntity(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingBlock
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
/**
* Search an enum for a value, and return the first one found. Return null if the
* enum entry is not found.
*
* @param enumType enum class
* @param values values to test
* @return a value in the enum or null
*/
public static <T extends Enum<T>> T tryEnum(Class<T> enumType, String ... values) {
for (String val : values) {
try {
return Enum.valueOf(enumType, val);
} catch (IllegalArgumentException e) {
}
}
return null;
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @return a target
*/
public static Target createTarget(Block block) {
checkNotNull(block);
return new MaterialTarget(block.getTypeId(), block.getData());
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @param material a fallback material
* @return a target
*/
public static Target createTarget(Block block, Material material) {
checkNotNull(material);
if (block.getType() == material) {
return new MaterialTarget(block.getTypeId(), block.getData());
} else {
return new MaterialTarget(material.getId(), (short) 0);
}
}
/**
* Get a blacklist target for the given item.
*
* @param item the item
* @return a target
*/
public static Target createTarget(ItemStack item) {
checkNotNull(item);
return new MaterialTarget(item.getTypeId(), item.getDurability());
}
/**
* Get a blacklist target for the given material.
*
* @param material the material
* @return a target
*/
public static Target createTarget(Material material) {
checkNotNull(material);
return new MaterialTarget(material.getId(), (short) 0);
}
/**
* Get a collection of the currently online players.
*
* @return The online players
*/
@SuppressWarnings("unchecked")
public static Collection<? extends Player> getOnlinePlayers() {
try {
return Bukkit.getServer().getOnlinePlayers();
} catch (NoSuchMethodError ignored) {
}
try {
if (ONLINE_PLAYERS_METHOD == null) {
ONLINE_PLAYERS_METHOD = getOnlinePlayersMethod();
}
Object result = ONLINE_PLAYERS_METHOD.invoke(Bukkit.getServer());
if (result instanceof Player[]) {
return ImmutableList.copyOf((Player[]) result);
} else if (result instanceof Collection<?>) {
return (Collection<? extends Player>) result;
} else {
throw new RuntimeException("Result of getOnlinePlayers() call was not a known data type");
}
} catch (Exception e) {
throw new RuntimeException("WorldGuard is not compatible with this version of Bukkit", e);
}
}
private static Method getOnlinePlayersMethod() throws NoSuchMethodException {
try {
return Server.class.getMethod("getOnlinePlayers");
} catch (NoSuchMethodException e1) {
return Server.class.getMethod("_INVALID_getOnlinePlayers");
}
}
}
@@ -1,296 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import com.google.common.collect.ImmutableMap;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.protection.managers.storage.DriverType;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.protection.managers.storage.file.DirectoryYamlDriver;
import com.sk89q.worldguard.protection.managers.storage.sql.SQLDriver;
import com.sk89q.worldguard.session.handler.WaterBreathing;
import com.sk89q.worldguard.util.report.Unreported;
import com.sk89q.worldguard.util.sql.DataSourceConfig;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class ConfigurationManager {
private static final Logger log = Logger.getLogger(ConfigurationManager.class.getCanonicalName());
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace most settings in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" +
"# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
@Unreported private WorldGuardPlugin plugin;
@Unreported private ConcurrentMap<String, WorldConfiguration> worlds;
@Unreported private YAMLProcessor config;
private boolean hasCommandBookGodMode = false;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean useGodPermission;
public boolean useGodGroup;
public boolean useAmphibiousGroup;
public boolean usePlayerMove;
public boolean usePlayerTeleports;
public boolean deopOnJoin;
public boolean blockInGameOp;
public boolean migrateRegionsToUuid;
public boolean keepUnresolvedNames;
@Unreported public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
@Unreported public RegionDriver selectedRegionStoreDriver;
@Unreported public Map<DriverType, RegionDriver> regionStoreDriverMap;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
this.worlds = new ConcurrentHashMap<String, WorldConfiguration>();
}
/**
* Get the folder for storing data files and configuration.
*
* @return the data folder
*/
public File getDataFolder() {
return plugin.getDataFolder();
}
/**
* Get the folder for storing data files and configuration for each
* world.
*
* @return the data folder
*/
public File getWorldsDataFolder() {
return new File(getDataFolder(), "worlds");
}
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
plugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
config = new YAMLProcessor(new File(plugin.getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
log.severe("Error reading configuration for global config: ");
e.printStackTrace();
}
config.removeProperty("suppress-tick-sync-warnings");
migrateRegionsToUuid = config.getBoolean("regions.uuid-migration.perform-on-next-start", true);
keepUnresolvedNames = config.getBoolean("regions.uuid-migration.keep-names-that-lack-uuids", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
useGodPermission = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
useGodGroup = config.getBoolean("auto-invincible-group", false);
useAmphibiousGroup = config.getBoolean("auto-no-drowning-group", false);
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean("use-player-move-event", true);
usePlayerTeleports = config.getBoolean("use-player-teleports", true);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
hostKeys = new HashMap<String, String>();
Object hostKeysRaw = config.getProperty("host-keys");
if (hostKeysRaw == null || !(hostKeysRaw instanceof Map)) {
config.setProperty("host-keys", new HashMap<String, String>());
} else {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
hostKeys.put(key.toLowerCase(), value);
}
}
// ====================================================================
// Region store drivers
// ====================================================================
boolean useSqlDatabase = config.getBoolean("regions.sql.use", false);
String sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
String sqlUsername = config.getString("regions.sql.username", "worldguard");
String sqlPassword = config.getString("regions.sql.password", "worldguard");
String sqlTablePrefix = config.getString("regions.sql.table-prefix", "");
DataSourceConfig dataSourceConfig = new DataSourceConfig(sqlDsn, sqlUsername, sqlPassword, sqlTablePrefix);
SQLDriver sqlDriver = new SQLDriver(dataSourceConfig);
DirectoryYamlDriver yamlDriver = new DirectoryYamlDriver(getWorldsDataFolder(), "regions.yml");
this.regionStoreDriverMap = ImmutableMap.<DriverType, RegionDriver>builder()
.put(DriverType.MYSQL, sqlDriver)
.put(DriverType.YAML, yamlDriver)
.build();
this.selectedRegionStoreDriver = useSqlDatabase ? sqlDriver : yamlDriver;
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
config.setHeader(CONFIG_HEADER);
}
/**
* Unload the configuration.
*/
public void unload() {
worlds.clear();
}
public void disableUuidMigration() {
config.setProperty("regions.uuid-migration.perform-on-next-start", false);
if (!config.save()) {
log.severe("Error saving configuration!");
}
}
/**
* Get the configuration for a world.
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
public WorldConfiguration get(World world) {
String worldName = world.getName();
WorldConfiguration config = worlds.get(worldName);
WorldConfiguration newConfig = null;
while (config == null) {
if (newConfig == null) {
newConfig = new WorldConfiguration(plugin, worldName, this.config);
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
}
/**
* Check to see if god mode is enabled for a player.
*
* @param player The player to check
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(Player player) {
return plugin.getSessionManager().get(player).isInvincible(player);
}
/**
* Enable amphibious mode for a player.
*
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(Player player) {
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(true);
}
}
/**
* Disable amphibious mode for a player.
*
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(Player player) {
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
if (handler != null) {
handler.setWaterBreathing(false);
}
}
/**
* Check to see if amphibious mode is enabled for a player.
*
* @param player The player to check
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(Player player) {
WaterBreathing handler = plugin.getSessionManager().get(player).getHandler(WaterBreathing.class);
return handler != null && handler.hasWaterBreathing();
}
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;
}
}
@@ -1,373 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.FailedLoadRegionSet;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.PermissiveRegionSet;
import com.sk89q.worldguard.protection.RegionResultSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.util.Collection;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* This object allows easy spatial queries involving region data for the
* purpose of implementing protection / region flag checks.
*
* <p>Results may be cached for brief amounts of time. If you want to get
* data for the purposes of changing it, use of this class is not recommended.
* Some of the return values of the methods may be simulated to reduce
* boilerplate code related to implementing protection, meaning that false
* data is returned.</p>
*/
public class RegionQuery {
private final WorldGuardPlugin plugin;
private final ConfigurationManager config;
@SuppressWarnings("deprecation")
private final GlobalRegionManager globalManager;
private final QueryCache cache;
/**
* Create a new instance.
*
* @param plugin the plugin
* @param cache the query cache
*/
RegionQuery(WorldGuardPlugin plugin, QueryCache cache) {
checkNotNull(plugin);
checkNotNull(cache);
this.plugin = plugin;
this.config = plugin.getGlobalStateManager();
this.cache = cache;
//noinspection deprecation
this.globalManager = plugin.getGlobalRegionManager();
}
/**
* Query for regions containing the given location.
*
* <p>An instance of {@link RegionResultSet} will always be returned,
* even if regions are disabled or region data failed to load. An
* appropriate "virtual" set will be returned in such a case
* (for example, if regions are disabled, the returned set
* would permit all activities).</p>
*
* @param location the location
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(Location location) {
checkNotNull(location);
World world = location.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return PermissiveRegionSet.getInstance();
}
RegionManager manager = globalManager.get(location.getWorld());
if (manager != null) {
return cache.queryContains(manager, location);
} else {
return FailedLoadRegionSet.getInstance();
}
}
/**
* Returns true if the BUILD flag allows the action in the location, but it
* can be overridden by a list of other flags. The BUILD flag will not
* override the other flags, but the other flags can override BUILD. If
* neither BUILD or any of the flags permit the action, then false will
* be returned.
*
* <p>Use this method when checking flags that are related to build
* protection. For example, lighting fire in a region should not be
* permitted unless the player is a member of the region or the
* LIGHTER flag allows it. However, the LIGHTER flag should be able
* to allow lighting fires even if BUILD is set to DENY.</p>
*
* <p>How this method works (BUILD can be overridden by other flags but
* not the other way around) is inconsistent, but it's required for
* legacy reasons.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testBuild(Location location, Player player, StateFlag... flag) {
if (flag.length == 0) {
return testState(location, player, DefaultFlag.BUILD);
}
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, player, DefaultFlag.BUILD)),
queryState(location, player, flag)));
}
/**
* Returns true if the BUILD flag allows the action in the location, but it
* can be overridden by a list of other flags. The BUILD flag will not
* override the other flags, but the other flags can override BUILD. If
* neither BUILD or any of the flags permit the action, then false will
* be returned.
*
* <p>Use this method when checking flags that are related to build
* protection. For example, lighting fire in a region should not be
* permitted unless the player is a member of the region or the
* LIGHTER flag allows it. However, the LIGHTER flag should be able
* to allow lighting fires even if BUILD is set to DENY.</p>
*
* <p>How this method works (BUILD can be overridden by other flags but
* not the other way around) is inconsistent, but it's required for
* legacy reasons.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testBuild(Location location, RegionAssociable associable, StateFlag... flag) {
if (flag.length == 0) {
return testState(location, associable, DefaultFlag.BUILD);
}
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, associable, DefaultFlag.BUILD)),
queryState(location, associable, flag)));
}
/**
* Test whether the (effective) value for a list of state flags equals
* {@code ALLOW}.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testState(Location location, @Nullable Player player, StateFlag... flag) {
return StateFlag.test(queryState(location, player, flag));
}
/**
* Test whether the (effective) value for a list of state flags equals
* {@code ALLOW}.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public boolean testState(Location location, @Nullable RegionAssociable associable, StateFlag... flag) {
return StateFlag.test(queryState(location, associable, flag));
}
/**
* Get the (effective) value for a list of state flags. The rules of
* states is observed here; that is, {@code DENY} overrides {@code ALLOW},
* and {@code ALLOW} overrides {@code NONE}. One flag may override another.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region groups that apply
* @param flags a list of flags to check
* @return a state
* @see RegionResultSet#queryState(RegionAssociable, StateFlag...)
*/
@Nullable
public State queryState(Location location, @Nullable Player player, StateFlag... flags) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryState(localPlayer, flags);
}
/**
* Get the (effective) value for a list of state flags. The rules of
* states is observed here; that is, {@code DENY} overrides {@code ALLOW},
* and {@code ALLOW} overrides {@code NONE}. One flag may override another.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is in the list of flags.</p>
*
* @param location the location
* @param associable an optional associable
* @param flags a list of flags to check
* @return a state
* @see RegionResultSet#queryState(RegionAssociable, StateFlag...)
*/
@Nullable
public State queryState(Location location, @Nullable RegionAssociable associable, StateFlag... flags) {
return getApplicableRegions(location).queryState(associable, flags);
}
/**
* Get the effective value for a flag. If there are multiple values
* (for example, multiple overlapping regions with
* the same priority may have the same flag set), then the selected
* (or "winning") value will depend on the flag type.
*
* <p>Only some flag types actually have a strategy for picking the
* "best value." For most types, the actual value that is chosen to be
* returned is undefined (it could be any value). As of writing, the only
* type of flag that actually has a strategy for picking a value is the
* {@link StateFlag}.</p>
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return a value, which could be {@code null}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
@Nullable
public <V> V queryValue(Location location, @Nullable Player player, Flag<V> flag) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryValue(localPlayer, flag);
}
/**
* Get the effective value for a flag. If there are multiple values
* (for example, multiple overlapping regions with
* the same priority may have the same flag set), then the selected
* (or "winning") value will depend on the flag type.
*
* <p>Only some flag types actually have a strategy for picking the
* "best value." For most types, the actual value that is chosen to be
* returned is undefined (it could be any value). As of writing, the only
* type of flag that actually has a strategy for picking a value is the
* {@link StateFlag}.</p>
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return a value, which could be {@code null}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
@Nullable
public <V> V queryValue(Location location, @Nullable RegionAssociable associable, Flag<V> flag) {
return getApplicableRegions(location).queryValue(associable, flag);
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
* from the collection will be used.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param player an optional player, which would be used to determine the region group to apply
* @param flag the flag
* @return a collection of values
* @see RegionResultSet#queryAllValues(RegionAssociable, Flag)
*/
public <V> Collection<V> queryAllValues(Location location, @Nullable Player player, Flag<V> flag) {
LocalPlayer localPlayer = player != null ? plugin.wrapPlayer(player) : null;
return getApplicableRegions(location).queryAllValues(localPlayer, flag);
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
* from the collection will be used.
*
* <p>{@code player} can be non-null to satisfy region group requirements,
* otherwise it will be assumed that the caller that is not a member of any
* regions. (Flags on a region can be changed so that they only apply
* to certain users.) The player argument is required if the
* {@link DefaultFlag#BUILD} flag is the flag being queried.</p>
*
* @param location the location
* @param associable an optional associable
* @param flag the flag
* @return a collection of values
* @see RegionResultSet#queryAllValues(RegionAssociable, Flag)
*/
public <V> Collection<V> queryAllValues(Location location, @Nullable RegionAssociable associable, Flag<V> flag) {
return getApplicableRegions(location).queryAllValues(associable, flag);
}
}
@@ -1,71 +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/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.World;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Helper class to get a reference to WorldGuard and its components.
*/
public class WGBukkit {
private WGBukkit() {
}
/**
* Get the WorldGuard plugin. If WorldGuard isn't loaded yet, then this will
* return null.
* <p>
* If you are depending on WorldGuard in your plugin, you should place
* <code>softdepend: [WorldGuard]</code> or <code>depend: [WorldGuard]</code>
* in your plugin.yml so that this won't return null for you.
*
* @return the WorldGuard plugin or null
*/
public static WorldGuardPlugin getPlugin() {
return WorldGuardPlugin.inst();
}
/**
* Set cache to null for reload WorldGuardPlugin
* @deprecated instance is now stored directly in {@link WorldGuardPlugin}
*/
@Deprecated
public static void cleanCache() {
// do nothing - plugin instance is stored in plugin class now
}
/**
* Returns the region manager for a given world. May return null if WorldGuard
* is not loaded or region protection is not enabled for the given world.
*
* @param world world
* @return a region manager or null
*/
public static RegionManager getRegionManager(World world) {
if (getPlugin() == null) {
return null;
}
return WorldGuardPlugin.inst().getRegionManager(world);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,135 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.task.FutureForwardingTask;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
public class AsyncCommandHelper {
private final ListenableFuture<?> future;
private final WorldGuardPlugin plugin;
private final CommandSender sender;
@Nullable
private Object[] formatArgs;
private AsyncCommandHelper(ListenableFuture<?> future, WorldGuardPlugin plugin, CommandSender sender) {
checkNotNull(future);
checkNotNull(plugin);
checkNotNull(sender);
this.future = future;
this.plugin = plugin;
this.sender = sender;
}
public AsyncCommandHelper formatUsing(Object... args) {
this.formatArgs = args;
return this;
}
private String format(String message) {
if (formatArgs != null) {
return String.format(message, formatArgs);
} else {
return message;
}
}
public AsyncCommandHelper registerWithSupervisor(String description) {
plugin.getSupervisor().monitor(
FutureForwardingTask.create(
future, format(description), sender));
return this;
}
public AsyncCommandHelper sendMessageAfterDelay(String message) {
FutureProgressListener.addProgressListener(future, sender, format(message));
return this;
}
public AsyncCommandHelper thenRespondWith(String success, String failure) {
// Send a response message
Futures.addCallback(
future,
new MessageFutureCallback.Builder(plugin, sender)
.onSuccess(format(success))
.onFailure(format(failure))
.build());
return this;
}
public AsyncCommandHelper thenTellErrorsOnly(String failure) {
// Send a response message
Futures.addCallback(
future,
new MessageFutureCallback.Builder(plugin, sender)
.onFailure(format(failure))
.build());
return this;
}
public AsyncCommandHelper forRegionDataLoad(World world, boolean silent) {
checkNotNull(world);
formatUsing(world.getName());
registerWithSupervisor("Loading region data for '%s'");
if (silent) {
thenTellErrorsOnly("Failed to load regions '%s'");
} else {
sendMessageAfterDelay("(Please wait... loading the region data for '%s')");
thenRespondWith(
"Loaded region data for '%s'",
"Failed to load regions '%s'");
}
return this;
}
public AsyncCommandHelper forRegionDataSave(World world, boolean silent) {
checkNotNull(world);
formatUsing(world.getName());
registerWithSupervisor("Saving region data for '%s'");
if (silent) {
thenTellErrorsOnly("Failed to save regions '%s'");
} else {
sendMessageAfterDelay("(Please wait... saving the region data for '%s')");
thenRespondWith(
"Saved region data for '%s'",
"Failed to load regions '%s'");
}
return this;
}
public static AsyncCommandHelper wrap(ListenableFuture<?> future, WorldGuardPlugin plugin, CommandSender sender) {
return new AsyncCommandHelper(future, plugin, sender);
}
}
@@ -1,196 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.google.common.base.Function;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.paste.EngineHubPaste;
import org.bukkit.ChatColor;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Command-related utility methods.
*/
public final class CommandUtils {
private static final Logger log = Logger.getLogger(CommandUtils.class.getCanonicalName());
private CommandUtils() {
}
/**
* Replace color macros in a string.
*
* @param str the string
* @return the new string
*/
public static String replaceColorMacros(String str) {
// TODO: Make this more efficient
str = str.replace("`r", ChatColor.RED.toString());
str = str.replace("`R", ChatColor.DARK_RED.toString());
str = str.replace("`y", ChatColor.YELLOW.toString());
str = str.replace("`Y", ChatColor.GOLD.toString());
str = str.replace("`g", ChatColor.GREEN.toString());
str = str.replace("`G", ChatColor.DARK_GREEN.toString());
str = str.replace("`c", ChatColor.AQUA.toString());
str = str.replace("`C", ChatColor.DARK_AQUA.toString());
str = str.replace("`b", ChatColor.BLUE.toString());
str = str.replace("`B", ChatColor.DARK_BLUE.toString());
str = str.replace("`p", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("`P", ChatColor.DARK_PURPLE.toString());
str = str.replace("`0", ChatColor.BLACK.toString());
str = str.replace("`1", ChatColor.DARK_GRAY.toString());
str = str.replace("`2", ChatColor.GRAY.toString());
str = str.replace("`w", ChatColor.WHITE.toString());
str = str.replace("`k", ChatColor.MAGIC.toString());
str = str.replace("`l", ChatColor.BOLD.toString());
str = str.replace("`m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("`n", ChatColor.UNDERLINE.toString());
str = str.replace("`o", ChatColor.ITALIC.toString());
str = str.replace("`x", ChatColor.RESET.toString());
// MC classic
str = str.replace("&c", ChatColor.RED.toString());
str = str.replace("&4", ChatColor.DARK_RED.toString());
str = str.replace("&e", ChatColor.YELLOW.toString());
str = str.replace("&6", ChatColor.GOLD.toString());
str = str.replace("&a", ChatColor.GREEN.toString());
str = str.replace("&2", ChatColor.DARK_GREEN.toString());
str = str.replace("&b", ChatColor.AQUA.toString());
str = str.replace("&3", ChatColor.DARK_AQUA.toString());
str = str.replace("&9", ChatColor.BLUE.toString());
str = str.replace("&1", ChatColor.DARK_BLUE.toString());
str = str.replace("&d", ChatColor.LIGHT_PURPLE.toString());
str = str.replace("&5", ChatColor.DARK_PURPLE.toString());
str = str.replace("&0", ChatColor.BLACK.toString());
str = str.replace("&8", ChatColor.DARK_GRAY.toString());
str = str.replace("&7", ChatColor.GRAY.toString());
str = str.replace("&f", ChatColor.WHITE.toString());
str = str.replace("&k", ChatColor.MAGIC.toString());
str = str.replace("&l", ChatColor.BOLD.toString());
str = str.replace("&m", ChatColor.STRIKETHROUGH.toString());
str = str.replace("&n", ChatColor.UNDERLINE.toString());
str = str.replace("&o", ChatColor.ITALIC.toString());
str = str.replace("&x", ChatColor.RESET.toString());
str = str.replace("&r", ChatColor.RESET.toString());
return str;
}
/**
* Get the name of the given owner object.
*
* @param owner the owner object
* @return a name
*/
public static String getOwnerName(@Nullable Object owner) {
if (owner == null) {
return "?";
} else if (owner instanceof Player) {
return ((Player) owner).getName();
} else if (owner instanceof ConsoleCommandSender) {
return "*CONSOLE*";
} else if (owner instanceof BlockCommandSender) {
return ((BlockCommandSender) owner).getBlock().getLocation().toString();
} else {
return "?";
}
}
/**
* Return a function that accepts a string to send a message to the
* given sender.
*
* @param sender the sender
* @return a function
*/
public static Function<String, ?> messageFunction(final CommandSender sender) {
return new Function<String, Object>() {
@Override
public Object apply(@Nullable String s) {
sender.sendMessage(s);
return null;
}
};
}
/**
* Submit data to a pastebin service and inform the sender of
* success or failure.
*
* @param plugin The plugin
* @param sender The sender
* @param content The content
* @param successMessage The message, formatted with {@link String#format(String, Object...)} on success
*/
public static void pastebin(WorldGuardPlugin plugin, final CommandSender sender, String content, final String successMessage) {
ListenableFuture<URL> future = new EngineHubPaste().paste(content);
AsyncCommandHelper.wrap(future, plugin, sender)
.registerWithSupervisor("Submitting content to a pastebin service...")
.sendMessageAfterDelay("(Please wait... sending output to pastebin...)");
Futures.addCallback(future, new FutureCallback<URL>() {
@Override
public void onSuccess(URL url) {
sender.sendMessage(ChatColor.YELLOW + String.format(successMessage, url));
}
@Override
public void onFailure(Throwable throwable) {
log.log(Level.WARNING, "Failed to submit pastebin", throwable);
sender.sendMessage(ChatColor.RED + "Failed to submit to a pastebin. Please see console for the error.");
}
});
}
}
@@ -1,55 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Timer;
import static com.google.common.base.Preconditions.checkNotNull;
public class FutureProgressListener implements Runnable {
private static final Timer timer = new Timer();
private static final int MESSAGE_DELAY = 1000;
private final MessageTimerTask task;
public FutureProgressListener(CommandSender sender, String message) {
checkNotNull(sender);
checkNotNull(message);
task = new MessageTimerTask(sender, ChatColor.GRAY + message);
timer.schedule(task, MESSAGE_DELAY);
}
@Override
public void run() {
task.cancel();
}
public static void addProgressListener(ListenableFuture<?> future, CommandSender sender, String message) {
future.addListener(new FutureProgressListener(sender, message), MoreExecutors.sameThreadExecutor());
}
}
@@ -1,311 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.GodMode;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class GeneralCommands {
private final WorldGuardPlugin plugin;
public GeneralCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
@Command(aliases = {"god"}, usage = "[player]",
desc = "Enable godmode on a player", flags = "s", max = 1)
public void god(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<? extends Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
Session session = plugin.getSessionManager().get(player);
if (GodMode.set(player, session, true)) {
player.setFireTicks(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode enabled! Use /ungod to disable.");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God enabled by "
+ plugin.toName(sender) + ".");
}
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW + "Players now have god mode.");
}
}
@SuppressWarnings("deprecation")
@Command(aliases = {"ungod"}, usage = "[player]",
desc = "Disable godmode on a player", flags = "s", max = 1)
public void ungod(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager config = plugin.getGlobalStateManager();
Iterable<? extends Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god");
} else {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.god.other");
}
for (Player player : targets) {
Session session = plugin.getSessionManager().get(player);
if (GodMode.set(player, session, false)) {
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "God mode disabled!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "God disabled by "
+ plugin.toName(sender) + ".");
}
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW + "Players no longer have god mode.");
}
}
@Command(aliases = {"heal"}, usage = "[player]", desc = "Heal a player", flags = "s", max = 1)
public void heal(CommandContext args,CommandSender sender) throws CommandException {
Iterable<? extends Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.heal.other");
}
for (Player player : targets) {
player.setHealth(player.getMaxHealth());
player.setFoodLevel(20);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Healed!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Healed by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players healed.");
}
}
@Command(aliases = {"slay"}, usage = "[player]", desc = "Slay a player", flags = "s", max = 1)
public void slay(CommandContext args, CommandSender sender) throws CommandException {
Iterable<? extends Player> targets = null;
boolean included = false;
// Detect arguments based on the number of arguments provided
if (args.argsLength() == 0) {
targets = plugin.matchPlayers(plugin.checkPlayer(sender));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay");
} else if (args.argsLength() == 1) {
targets = plugin.matchPlayers(sender, args.getString(0));
// Check permissions!
plugin.checkPermission(sender, "worldguard.slay.other");
}
for (Player player : targets) {
player.setHealth(0);
// Tell the user
if (player.equals(sender)) {
player.sendMessage(ChatColor.YELLOW + "Slain!");
// Keep track of this
included = true;
} else {
player.sendMessage(ChatColor.YELLOW + "Slain by "
+ plugin.toName(sender) + ".");
}
}
// The player didn't receive any items, then we need to send the
// user a message so s/he know that something is indeed working
if (!included && args.hasFlag('s')) {
sender.sendMessage(ChatColor.YELLOW.toString() + "Players slain.");
}
}
@Command(aliases = {"locate"}, usage = "[player]", desc = "Locate a player", max = 1)
@CommandPermissions({"worldguard.locate"})
public void locate(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
if (args.argsLength() == 0) {
player.setCompassTarget(player.getWorld().getSpawnLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass reset to spawn.");
} else {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
player.setCompassTarget(target.getLocation());
sender.sendMessage(ChatColor.YELLOW.toString() + "Compass repointed.");
}
}
@Command(aliases = {"stack", ";"}, usage = "", desc = "Stack items", max = 0)
@CommandPermissions({"worldguard.stack"})
public void stack(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
boolean ignoreMax = plugin.hasPermission(player, "worldguard.stack.illegitimate");
boolean ignoreDamaged = plugin.hasPermission(player, "worldguard.stack.damaged");
ItemStack[] items = player.getInventory().getContents();
int len = items.length;
int affected = 0;
for (int i = 0; i < len; i++) {
ItemStack item = items[i];
// Avoid infinite stacks and stacks with durability
if (item == null || item.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
int max = ignoreMax ? 64 : item.getMaxStackSize();
if (item.getAmount() < max) {
int needed = max - item.getAmount(); // Number of needed items until max
// Find another stack of the same type
for (int j = i + 1; j < len; j++) {
ItemStack item2 = items[j];
// Avoid infinite stacks and stacks with durability
if (item2 == null || item2.getAmount() <= 0
|| (!ignoreMax && item.getMaxStackSize() == 1)) {
continue;
}
// Same type?
// Blocks store their color in the damage value
if (item2.getTypeId() == item.getTypeId() &&
((!ItemType.usesDamageValue(item.getTypeId()) && ignoreDamaged)
|| item.getDurability() == item2.getDurability()) &&
((item.getItemMeta() == null && item2.getItemMeta() == null)
|| (item.getItemMeta() != null &&
item.getItemMeta().equals(item2.getItemMeta())))) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(max);
item2.setAmount(item2.getAmount() - needed);
break;
// This stack will
} else {
items[j] = null;
item.setAmount(item.getAmount() + item2.getAmount());
needed = max - item.getAmount();
}
affected++;
}
}
}
}
if (affected > 0) {
player.getInventory().setContents(items);
}
player.sendMessage(ChatColor.YELLOW + "Items compacted into stacks!");
}
}
@@ -1,103 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.google.common.util.concurrent.FutureCallback;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
public class MessageFutureCallback<V> implements FutureCallback<V> {
private final WorldGuardPlugin plugin;
private final CommandSender sender;
@Nullable
private final String success;
@Nullable
private final String failure;
private MessageFutureCallback(WorldGuardPlugin plugin, CommandSender sender, @Nullable String success, @Nullable String failure) {
this.plugin = plugin;
this.sender = sender;
this.success = success;
this.failure = failure;
}
@Override
public void onSuccess(@Nullable V v) {
if (success != null) {
sender.sendMessage(ChatColor.YELLOW + success);
}
}
@Override
public void onFailure(@Nullable Throwable throwable) {
String failure = this.failure != null ? this.failure : "An error occurred";
sender.sendMessage(ChatColor.RED + failure + ": " + plugin.convertThrowable(throwable));
}
public static class Builder {
private final WorldGuardPlugin plugin;
private final CommandSender sender;
@Nullable
private String success;
@Nullable
private String failure;
public Builder(WorldGuardPlugin plugin, CommandSender sender) {
checkNotNull(plugin);
checkNotNull(sender);
this.plugin = plugin;
this.sender = sender;
}
public Builder onSuccess(@Nullable String message) {
this.success = message;
return this;
}
public Builder onFailure(@Nullable String message) {
this.failure = message;
return this;
}
public <V> MessageFutureCallback<V> build() {
return new MessageFutureCallback<V>(plugin, sender, success, failure);
}
}
public static <V> MessageFutureCallback<V> createRegionLoadCallback(WorldGuardPlugin plugin, CommandSender sender) {
return new Builder(plugin, sender)
.onSuccess("Successfully load the region data.")
.build();
}
public static <V> MessageFutureCallback<V> createRegionSaveCallback(WorldGuardPlugin plugin, CommandSender sender) {
return new Builder(plugin, sender)
.onSuccess("Successfully saved the region data.")
.build();
}
}
@@ -1,165 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class ToggleCommands {
private final WorldGuardPlugin plugin;
public ToggleCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"stopfire"}, usage = "[<world>]",
desc = "Disables all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void stopFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (!wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(
ChatColor.YELLOW
+ "Fire spread has been globally disabled for '" + world.getName() + "' by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(
ChatColor.YELLOW
+ "Fire spread was already globally disabled.");
}
wcfg.fireSpreadDisableToggle = true;
}
@Command(aliases = {"allowfire"}, usage = "[<world>]",
desc = "Allows all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void allowFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (wcfg.fireSpreadDisableToggle) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "Fire spread has been globally for '" + world.getName() + "' re-enabled by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(ChatColor.YELLOW
+ "Fire spread was already globally enabled.");
}
wcfg.fireSpreadDisableToggle = false;
}
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "cis", max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public void stopLag(CommandContext args, CommandSender sender) throws CommandException {
ConfigurationManager configManager = plugin.getGlobalStateManager();
if (args.hasFlag('i')) {
if (configManager.activityHaltToggle) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity is not allowed.");
} else {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity is allowed.");
}
} else {
configManager.activityHaltToggle = !args.hasFlag('c');
if (configManager.activityHaltToggle) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted.");
}
if (!args.hasFlag('s')) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted by "
+ plugin.toName(sender) + ".");
} else {
sender.sendMessage(ChatColor.YELLOW
+ "(Silent) ALL intensive server activity halted by "
+ plugin.toName(sender) + ".");
}
for (World world : plugin.getServer().getWorlds()) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
if (removed > 10) {
sender.sendMessage("" + removed + " entities (>10) auto-removed from "
+ world.getName());
}
}
} else {
if (!args.hasFlag('s')) {
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity is now allowed.");
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity is now allowed.");
}
} else {
sender.sendMessage(ChatColor.YELLOW
+ "(Silent) ALL intensive server activity is now allowed.");
}
}
}
}
}
@@ -1,296 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.logging.LoggerToChatHandler;
import com.sk89q.worldguard.bukkit.util.report.*;
import com.sk89q.worldguard.util.profiler.SamplerBuilder;
import com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler;
import com.sk89q.worldguard.util.profiler.ThreadIdFilter;
import com.sk89q.worldguard.util.profiler.ThreadNameFilter;
import com.sk89q.worldguard.util.report.ReportList;
import com.sk89q.worldguard.util.report.SystemInfoReport;
import com.sk89q.worldguard.util.task.Task;
import com.sk89q.worldguard.util.task.TaskStateComparator;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.management.ThreadInfo;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WorldGuardCommands {
private static final Logger log = Logger.getLogger(WorldGuardCommands.class.getCanonicalName());
private final WorldGuardPlugin plugin;
@Nullable
private Sampler activeSampler;
public WorldGuardCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"version"}, desc = "Get the WorldGuard version", max = 0)
public void version(CommandContext args, CommandSender sender) throws CommandException {
sender.sendMessage(ChatColor.YELLOW
+ "WorldGuard " + plugin.getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW
+ "http://www.sk89q.com");
}
@Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
@CommandPermissions({"worldguard.reload"})
public void reload(CommandContext args, CommandSender sender) throws CommandException {
// TODO: This is subject to a race condition, but at least other commands are not being processed concurrently
List<Task<?>> tasks = plugin.getSupervisor().getTasks();
if (!tasks.isEmpty()) {
throw new CommandException("There are currently pending tasks. Use /wg running to monitor these tasks first.");
}
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
if (sender instanceof Player) {
handler = new LoggerToChatHandler(sender);
handler.setLevel(Level.ALL);
minecraftLogger = Logger.getLogger("com.sk89q.worldguard");
minecraftLogger.addHandler(handler);
}
try {
ConfigurationManager config = plugin.getGlobalStateManager();
config.unload();
config.load();
for (World world : Bukkit.getServer().getWorlds()) {
config.get(world);
}
plugin.getRegionContainer().reload();
// WGBukkit.cleanCache();
sender.sendMessage("WorldGuard configuration reloaded.");
} catch (Throwable t) {
sender.sendMessage("Error while reloading: "
+ t.getMessage());
} finally {
if (minecraftLogger != null) {
minecraftLogger.removeHandler(handler);
}
}
}
@Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({"worldguard.report"})
public void report(CommandContext args, final CommandSender sender) throws CommandException {
ReportList report = new ReportList("Report");
report.add(new SystemInfoReport());
report.add(new ServerReport());
report.add(new PluginReport());
report.add(new SchedulerReport());
report.add(new ServicesReport());
report.add(new WorldReport());
report.add(new PerformanceReport());
report.add(new ConfigReport(plugin));
String result = report.toString();
try {
File dest = new File(plugin.getDataFolder(), "report.txt");
Files.write(result, dest, Charset.forName("UTF-8"));
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report written to " + dest.getAbsolutePath());
} catch (IOException e) {
throw new CommandException("Failed to write report: " + e.getMessage());
}
if (args.hasFlag('p')) {
plugin.checkPermission(sender, "worldguard.report.pastebin");
CommandUtils.pastebin(plugin, sender, result, "WorldGuard report: %s.report");
}
}
@Command(aliases = {"profile"}, usage = "[<minutes>]",
desc = "Profile the CPU usage of the server", min = 0, max = 1,
flags = "t:p")
@CommandPermissions("worldguard.profile")
public void profile(final CommandContext args, final CommandSender sender) throws CommandException {
Predicate<ThreadInfo> threadFilter;
String threadName = args.getFlag('t');
final boolean pastebin;
if (args.hasFlag('p')) {
plugin.checkPermission(sender, "worldguard.report.pastebin");
pastebin = true;
} else {
pastebin = false;
}
if (threadName == null) {
threadFilter = new ThreadIdFilter(Thread.currentThread().getId());
} else if (threadName.equals("*")) {
threadFilter = Predicates.alwaysTrue();
} else {
threadFilter = new ThreadNameFilter(threadName);
}
int minutes;
if (args.argsLength() == 0) {
minutes = 5;
} else {
minutes = args.getInteger(0);
if (minutes < 1) {
throw new CommandException("You must run the profile for at least 1 minute.");
} else if (minutes > 10) {
throw new CommandException("You can profile for, at maximum, 10 minutes.");
}
}
Sampler sampler;
synchronized (this) {
if (activeSampler != null) {
throw new CommandException("A profile is currently in progress! Please use /wg stopprofile to stop the current profile.");
}
SamplerBuilder builder = new SamplerBuilder();
builder.setThreadFilter(threadFilter);
builder.setRunTime(minutes, TimeUnit.MINUTES);
sampler = activeSampler = builder.start();
}
AsyncCommandHelper.wrap(sampler.getFuture(), plugin, sender)
.formatUsing(minutes)
.registerWithSupervisor("Running CPU profiler for %d minute(s)...")
.sendMessageAfterDelay("(Please wait... profiling for %d minute(s)...)")
.thenTellErrorsOnly("CPU profiling failed.");
sampler.getFuture().addListener(new Runnable() {
@Override
public void run() {
synchronized (WorldGuardCommands.this) {
activeSampler = null;
}
}
}, MoreExecutors.sameThreadExecutor());
Futures.addCallback(sampler.getFuture(), new FutureCallback<Sampler>() {
@Override
public void onSuccess(Sampler result) {
String output = result.toString();
try {
File dest = new File(plugin.getDataFolder(), "profile.txt");
Files.write(output, dest, Charset.forName("UTF-8"));
sender.sendMessage(ChatColor.YELLOW + "CPU profiling data written to " + dest.getAbsolutePath());
} catch (IOException e) {
sender.sendMessage(ChatColor.RED + "Failed to write CPU profiling data: " + e.getMessage());
}
if (pastebin) {
CommandUtils.pastebin(plugin, sender, output, "Profile result: %s.profile");
}
}
@Override
public void onFailure(Throwable throwable) {
}
});
}
@Command(aliases = {"stopprofile"}, usage = "",desc = "Stop a running profile", min = 0, max = 0)
@CommandPermissions("worldguard.profile")
public void stopProfile(CommandContext args, final CommandSender sender) throws CommandException {
synchronized (this) {
if (activeSampler == null) {
throw new CommandException("No CPU profile is currently running.");
}
activeSampler.cancel();
activeSampler = null;
}
sender.sendMessage("The running CPU profile has been stopped.");
}
@Command(aliases = {"flushstates", "clearstates"},
usage = "[player]", desc = "Flush the state manager", max = 1)
@CommandPermissions("worldguard.flushstates")
public void flushStates(CommandContext args, CommandSender sender) throws CommandException {
if (args.argsLength() == 0) {
plugin.getSessionManager().resetAllStates();
sender.sendMessage("Cleared all states.");
} else {
Player player = plugin.getServer().getPlayer(args.getString(0));
if (player != null) {
plugin.getSessionManager().resetState(player);
sender.sendMessage("Cleared states for player \"" + player.getName() + "\".");
}
}
}
@Command(aliases = {"running", "queue"}, desc = "List running tasks", max = 0)
@CommandPermissions("worldguard.running")
public void listRunningTasks(CommandContext args, CommandSender sender) throws CommandException {
List<Task<?>> tasks = plugin.getSupervisor().getTasks();
if (!tasks.isEmpty()) {
Collections.sort(tasks, new TaskStateComparator());
StringBuilder builder = new StringBuilder();
builder.append(ChatColor.GRAY);
builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
builder.append(" Running tasks ");
builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
builder.append("\n").append(ChatColor.GRAY).append("Note: Some 'running' tasks may be waiting to be start.");
for (Task task : tasks) {
builder.append("\n");
builder.append(ChatColor.BLUE).append("(").append(task.getState().name()).append(") ");
builder.append(ChatColor.YELLOW);
builder.append(CommandUtils.getOwnerName(task.getOwner()));
builder.append(": ");
builder.append(ChatColor.WHITE);
builder.append(task.getName());
}
sender.sendMessage(builder.toString());
} else {
sender.sendMessage(ChatColor.YELLOW + "There are currently no running tasks.");
}
}
@Command(aliases = {"debug"}, desc = "Debugging commands")
@NestedCommand({DebuggingCommands.class})
public void debug(CommandContext args, CommandSender sender) {}
}
File diff suppressed because it is too large. Load diff
@@ -1,397 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands.region;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldguard.bukkit.RegionContainer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Set;
class RegionCommandsBase {
protected RegionCommandsBase() {
}
/**
* Get the permission model to lookup permissions.
*
* @param sender the sender
* @return the permission model
*/
protected static RegionPermissionModel getPermissionModel(CommandSender sender) {
return new RegionPermissionModel(WorldGuardPlugin.inst(), sender);
}
/**
* Gets the world from the given flag, or falling back to the the current player
* if the sender is a player, otherwise reporting an error.
*
* @param args the arguments
* @param sender the sender
* @param flag the flag (such as 'w')
* @return a world
* @throws CommandException on error
*/
protected static World checkWorld(CommandContext args, CommandSender sender, char flag) throws CommandException {
if (args.hasFlag(flag)) {
return WorldGuardPlugin.inst().matchWorld(sender, args.getFlag(flag));
} else {
if (sender instanceof Player) {
return WorldGuardPlugin.inst().checkPlayer(sender).getWorld();
} else {
throw new CommandException("Please specify " + "the world with -" + flag + " world_name.");
}
}
}
/**
* Validate a region ID.
*
* @param id the id
* @param allowGlobal whether __global__ is allowed
* @return the id given
* @throws CommandException thrown on an error
*/
protected static String checkRegionId(String id, boolean allowGlobal) throws CommandException {
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException(
"The region name of '" + id + "' contains characters that are not allowed.");
}
if (!allowGlobal && id.equalsIgnoreCase("__global__")) { // Sorry, no global
throw new CommandException(
"Sorry, you can't use __global__ here.");
}
return id;
}
/**
* Get a protected region by a given name, otherwise throw a
* {@link CommandException}.
*
* <p>This also validates the region ID.</p>
*
* @param regionManager the region manager
* @param id the name to search
* @param allowGlobal true to allow selecting __global__
* @throws CommandException thrown if no region is found by the given name
*/
protected static ProtectedRegion checkExistingRegion(RegionManager regionManager, String id, boolean allowGlobal) throws CommandException {
// Validate the id
checkRegionId(id, allowGlobal);
ProtectedRegion region = regionManager.getRegion(id);
// No region found!
if (region == null) {
// But we want a __global__, so let's create one
if (id.equalsIgnoreCase("__global__")) {
region = new GlobalProtectedRegion(id);
regionManager.addRegion(region);
return region;
}
throw new CommandException(
"No region could be found with the name of '" + id + "'.");
}
return region;
}
/**
* Get the region at the player's location, if possible.
*
* <p>If the player is standing in several regions, an error will be raised
* and a list of regions will be provided.</p>
*
* @param regionManager the region manager
* @param player the player
* @return a region
* @throws CommandException thrown if no region was found
*/
protected static ProtectedRegion checkRegionStandingIn(RegionManager regionManager, Player player) throws CommandException {
return checkRegionStandingIn(regionManager, player, false);
}
/**
* Get the region at the player's location, if possible.
*
* <p>If the player is standing in several regions, an error will be raised
* and a list of regions will be provided.</p>
*
* <p>If the player is not standing in any regions, the global region will
* returned if allowGlobal is true and it exists.</p>
*
* @param regionManager the region manager
* @param player the player
* @param allowGlobal whether to search for a global region if no others are found
* @return a region
* @throws CommandException thrown if no region was found
*/
protected static ProtectedRegion checkRegionStandingIn(RegionManager regionManager, Player player, boolean allowGlobal) throws CommandException {
ApplicableRegionSet set = regionManager.getApplicableRegions(player.getLocation());
if (set.size() == 0) {
if (allowGlobal) {
ProtectedRegion global = checkExistingRegion(regionManager, "__global__", true);
player.sendMessage(ChatColor.GRAY + "You're not standing in any " +
"regions. Using the global region for this world instead.");
return global;
}
throw new CommandException(
"You're not standing in a region." +
"Specify an ID if you want to select a specific region.");
} else if (set.size() > 1) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (ProtectedRegion region : set) {
if (!first) {
builder.append(", ");
}
first = false;
builder.append(region.getId());
}
throw new CommandException(
"You're standing in several regions (please pick one).\nYou're in: " + builder.toString());
}
return set.iterator().next();
}
/**
* Get a WorldEdit selection for a player, or emit an exception if there is none
* available.
*
* @param player the player
* @return the selection
* @throws CommandException thrown on an error
*/
protected static Selection checkSelection(Player player) throws CommandException {
WorldEditPlugin worldEdit = WorldGuardPlugin.inst().getWorldEdit();
Selection selection = worldEdit.getSelection(player);
if (selection == null) {
throw new CommandException(
"Please select an area first. " +
"Use WorldEdit to make a selection! " +
"(wiki: http://wiki.sk89q.com/wiki/WorldEdit).");
}
return selection;
}
/**
* Check that a region with the given ID does not already exist.
*
* @param manager the manager
* @param id the ID
* @throws CommandException thrown if the ID already exists
*/
protected static void checkRegionDoesNotExist(RegionManager manager, String id, boolean mayRedefine) throws CommandException {
if (manager.hasRegion(id)) {
throw new CommandException("A region with that name already exists. Please choose another name." +
(mayRedefine ? " To change the shape, use /region redefine " + id + "." : ""));
}
}
/**
* Check that the given region manager is not null.
*
* @param plugin the plugin
* @param world the world
* @throws CommandException thrown if the manager is null
*/
protected static RegionManager checkRegionManager(WorldGuardPlugin plugin, World world) throws CommandException {
if (!plugin.getGlobalStateManager().get(world).useRegions) {
throw new CommandException("Region support is disabled in the target world. " +
"It can be enabled per-world in WorldGuard's configuration files. " +
"However, you may need to restart your server afterwards.");
}
RegionManager manager = plugin.getRegionContainer().get(world);
if (manager == null) {
throw new CommandException("Region data failed to load for this world. " +
"Please ask a server administrator to read the logs to identify the reason.");
}
return manager;
}
/**
* Create a {@link ProtectedRegion} from the player's selection.
*
* @param player the player
* @param id the ID of the new region
* @return a new region
* @throws CommandException thrown on an error
*/
protected static ProtectedRegion checkRegionFromSelection(Player player, String id) throws CommandException {
Selection selection = checkSelection(player);
// Detect the type of region from WorldEdit
if (selection instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) selection;
int minY = polySel.getNativeMinimumPoint().getBlockY();
int maxY = polySel.getNativeMaximumPoint().getBlockY();
return new ProtectedPolygonalRegion(id, polySel.getNativePoints(), minY, maxY);
} else if (selection instanceof CuboidSelection) {
BlockVector min = selection.getNativeMinimumPoint().toBlockVector();
BlockVector max = selection.getNativeMaximumPoint().toBlockVector();
return new ProtectedCuboidRegion(id, min, max);
} else {
throw new CommandException("Sorry, you can only use cuboids and polygons for WorldGuard regions.");
}
}
/**
* Warn the region saving is failing.
*
* @param sender the sender to send the message to
*/
protected static void warnAboutSaveFailures(CommandSender sender) {
RegionContainer container = WorldGuardPlugin.inst().getRegionContainer();
Set<RegionManager> failures = container.getSaveFailures();
if (failures.size() > 0) {
String failingList = Joiner.on(", ").join(Iterables.transform(failures, new Function<RegionManager, String>() {
@Override
public String apply(RegionManager regionManager) {
return "'" + regionManager.getName() + "'";
}
}));
sender.sendMessage(ChatColor.GOLD +
"(Warning: The background saving of region data is failing for these worlds: " + failingList + ". " +
"Your changes are getting lost. See the server log for more information.)");
}
}
/**
* Warn the sender if the dimensions of the given region are worrying.
*
* @param sender the sender to send the message to
* @param region the region
*/
protected static void warnAboutDimensions(CommandSender sender, ProtectedRegion region) {
int height = region.getMaximumPoint().getBlockY() - region.getMinimumPoint().getBlockY();
if (height <= 2) {
sender.sendMessage(ChatColor.GRAY + "(Warning: The height of the region was " + (height + 1) + " block(s).)");
}
}
/**
* Inform a new user about automatic protection.
*
* @param sender the sender to send the message to
* @param manager the region manager
* @param region the region
*/
protected static void informNewUser(CommandSender sender, RegionManager manager, ProtectedRegion region) {
if (manager.getRegions().size() <= 2) {
sender.sendMessage(ChatColor.GRAY +
"(This region is NOW PROTECTED from modification from others. " +
"Don't want that? Use " +
ChatColor.AQUA + "/rg flag " + region.getId() + " passthrough allow" +
ChatColor.GRAY + ")");
}
}
/**
* Set a player's selection to a given region.
*
* @param player the player
* @param region the region
* @throws CommandException thrown on a command error
*/
protected static void setPlayerSelection(Player player, ProtectedRegion region) throws CommandException {
WorldEditPlugin worldEdit = WorldGuardPlugin.inst().getWorldEdit();
World world = player.getWorld();
// Set selection
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
Vector pt1 = cuboid.getMinimumPoint();
Vector pt2 = cuboid.getMaximumPoint();
CuboidSelection selection = new CuboidSelection(world, pt1, pt2);
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a cuboid.");
} else if (region instanceof ProtectedPolygonalRegion) {
ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
Polygonal2DSelection selection = new Polygonal2DSelection(
world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(),
poly2d.getMaximumPoint().getBlockY() );
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
throw new CommandException(
"Can't select global regions! " +
"That would cover the entire world.");
} else {
throw new CommandException("Unknown region type: " +
region.getClass().getCanonicalName());
}
}
/**
* Utility method to set a flag.
*
* @param region the region
* @param flag the flag
* @param sender the sender
* @param value the value
* @throws InvalidFlagFormat thrown if the value is invalid
*/
protected static <V> void setFlag(ProtectedRegion region, Flag<V> flag, CommandSender sender, String value) throws InvalidFlagFormat {
region.setFlag(flag, flag.parseInput(WorldGuardPlugin.inst(), sender, value));
}
}
@@ -1,343 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands.region;
import com.sk89q.squirrelid.cache.ProfileCache;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.Callable;
/**
* Create a region printout, as used in /region info to show information about
* a region.
*/
public class RegionPrintoutBuilder implements Callable<String> {
private final ProtectedRegion region;
@Nullable
private final ProfileCache cache;
private final StringBuilder builder = new StringBuilder();
/**
* Create a new instance with a region to report on.
*
* @param region the region
* @param cache a profile cache, or {@code null}
*/
public RegionPrintoutBuilder(ProtectedRegion region, @Nullable ProfileCache cache) {
this.region = region;
this.cache = cache;
}
/**
* Add a new line.
*/
private void newLine() {
builder.append("\n");
}
/**
* Add region name, type, and priority.
*/
public void appendBasics() {
builder.append(ChatColor.BLUE);
builder.append("Region: ");
builder.append(ChatColor.YELLOW);
builder.append(region.getId());
builder.append(ChatColor.GRAY);
builder.append(" (type=");
builder.append(region.getType().getName());
builder.append(ChatColor.GRAY);
builder.append(", priority=");
builder.append(region.getPriority());
builder.append(")");
newLine();
}
/**
* Add information about flags.
*/
public void appendFlags() {
builder.append(ChatColor.BLUE);
builder.append("Flags: ");
appendFlagsList(true);
newLine();
}
/**
* Append just the list of flags (without "Flags:"), including colors.
*
* @param useColors true to use colors
*/
public void appendFlagsList(boolean useColors) {
boolean hasFlags = false;
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object val = region.getFlag(flag), group = null;
// No value
if (val == null) {
continue;
}
if (hasFlags) {
builder.append(", ");
} else {
if (useColors) {
builder.append(ChatColor.YELLOW);
}
}
RegionGroupFlag groupFlag = flag.getRegionGroupFlag();
if (groupFlag != null) {
group = region.getFlag(groupFlag);
}
if (group == null) {
builder.append(flag.getName()).append(": ")
.append(ChatColor.stripColor(String.valueOf(val)));
} else {
builder.append(flag.getName()).append(" -g ")
.append(group).append(": ")
.append(ChatColor.stripColor(String.valueOf(val)));
}
hasFlags = true;
}
if (!hasFlags) {
if (useColors) {
builder.append(ChatColor.RED);
}
builder.append("(none)");
}
}
/**
* Add information about parents.
*/
public void appendParents() {
appendParentTree(true);
}
/**
* Add information about parents.
*
* @param useColors true to use colors
*/
public void appendParentTree(boolean useColors) {
if (region.getParent() == null) {
return;
}
List<ProtectedRegion> inheritance = new ArrayList<ProtectedRegion>();
ProtectedRegion r = region;
inheritance.add(r);
while (r.getParent() != null) {
r = r.getParent();
inheritance.add(r);
}
ListIterator<ProtectedRegion> it = inheritance.listIterator(
inheritance.size());
int indent = 0;
while (it.hasPrevious()) {
ProtectedRegion cur = it.previous();
if (useColors) {
builder.append(ChatColor.GREEN);
}
// Put symbol for child
if (indent != 0) {
for (int i = 0; i < indent; i++) {
builder.append(" ");
}
builder.append("\u2517");
}
// Put name
builder.append(cur.getId());
// Put (parent)
if (!cur.equals(region)) {
if (useColors) {
builder.append(ChatColor.GRAY);
}
builder.append(" (parent, priority=").append(cur.getPriority()).append(")");
}
indent++;
newLine();
}
}
/**
* Add information about members.
*/
public void appendDomain() {
builder.append(ChatColor.BLUE);
builder.append("Owners: ");
addDomainString(region.getOwners());
newLine();
builder.append(ChatColor.BLUE);
builder.append("Members: ");
addDomainString(region.getMembers());
newLine();
}
private void addDomainString(DefaultDomain domain) {
if (domain.size() != 0) {
builder.append(ChatColor.YELLOW);
builder.append(domain.toUserFriendlyString(cache));
} else {
builder.append(ChatColor.RED);
builder.append("(none)");
}
}
/**
* Add information about coordinates.
*/
public void appendBounds() {
BlockVector min = region.getMinimumPoint();
BlockVector max = region.getMaximumPoint();
builder.append(ChatColor.BLUE);
builder.append("Bounds:");
builder.append(ChatColor.YELLOW);
builder.append(" (").append(min.getBlockX()).append(",").append(min.getBlockY()).append(",").append(min.getBlockZ()).append(")");
builder.append(" -> (").append(max.getBlockX()).append(",").append(max.getBlockY()).append(",").append(max.getBlockZ()).append(")");
newLine();
}
private void appendRegionInformation() {
builder.append(ChatColor.GRAY);
builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
builder.append(" Region Info ");
builder.append("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
newLine();
appendBasics();
appendFlags();
appendParents();
appendDomain();
appendBounds();
if (cache != null) {
builder.append(ChatColor.GRAY).append("Any names suffixed by * are 'last seen names' and may not be up to date.");
newLine();
}
}
@Override
public String call() throws Exception {
appendRegionInformation();
return builder.toString();
}
/**
* Send the report to a {@link CommandSender}.
*
* @param sender the recipient
*/
public void send(CommandSender sender) {
sender.sendMessage(toString());
}
public StringBuilder append(boolean b) {
return builder.append(b);
}
public StringBuilder append(char c) {
return builder.append(c);
}
public StringBuilder append(char[] str, int offset, int len) {
return builder.append(str, offset, len);
}
public StringBuilder append(char[] str) {
return builder.append(str);
}
public StringBuilder append(CharSequence s, int start, int end) {
return builder.append(s, start, end);
}
public StringBuilder append(CharSequence s) {
return builder.append(s);
}
public StringBuilder append(double d) {
return builder.append(d);
}
public StringBuilder append(float f) {
return builder.append(f);
}
public StringBuilder append(int i) {
return builder.append(i);
}
public StringBuilder append(long lng) {
return builder.append(lng);
}
public StringBuilder append(Object obj) {
return builder.append(obj);
}
public StringBuilder append(String str) {
return builder.append(str);
}
public StringBuilder append(StringBuffer sb) {
return builder.append(sb);
}
public StringBuilder appendCodePoint(int codePoint) {
return builder.appendCodePoint(codePoint);
}
@Override
public String toString() {
return builder.toString().trim();
}
}
@@ -1,236 +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/>.
*/
package com.sk89q.worldguard.bukkit.commands.task;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.squirrelid.Profile;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
public class RegionLister implements Callable<Integer> {
private static final Logger log = Logger.getLogger(RegionLister.class.getCanonicalName());
private final WorldGuardPlugin plugin;
private final CommandSender sender;
private final RegionManager manager;
private OwnerMatcher ownerMatcher;
private int page;
public RegionLister(WorldGuardPlugin plugin, RegionManager manager, CommandSender sender) {
checkNotNull(plugin);
checkNotNull(manager);
checkNotNull(sender);
this.plugin = plugin;
this.manager = manager;
this.sender = sender;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void filterOwnedByPlayer(final Player player) {
ownerMatcher = new OwnerMatcher() {
@Override
public String getName() {
return player.getName();
}
@Override
public boolean isContainedWithin(DefaultDomain domain) throws CommandException {
return domain.contains(player.getUniqueId());
}
};
}
public void filterOwnedByName(String name, boolean nameOnly) {
if (nameOnly) {
filterOwnedByName(name);
} else {
filterOwnedByProfile(name);
}
}
private void filterOwnedByName(final String name) {
ownerMatcher = new OwnerMatcher() {
@Override
public String getName() {
return name;
}
@Override
public boolean isContainedWithin(DefaultDomain domain) throws CommandException {
return domain.contains(name);
}
};
}
private void filterOwnedByProfile(final String name) {
ownerMatcher = new OwnerMatcher() {
private UUID uniqueId;
@Override
public String getName() {
return name;
}
@Override
public boolean isContainedWithin(DefaultDomain domain) throws CommandException {
if (domain.contains(name)) {
return true;
}
if (uniqueId == null) {
Profile profile;
try {
profile = plugin.getProfileService().findByName(name);
} catch (IOException e) {
log.log(Level.WARNING, "Failed UUID lookup of '" + name + "'", e);
throw new CommandException("Failed to lookup the UUID of '" + name + "'");
} catch (InterruptedException e) {
log.log(Level.WARNING, "Failed UUID lookup of '" + name + "'", e);
throw new CommandException("The lookup the UUID of '" + name + "' was interrupted");
}
if (profile == null) {
throw new CommandException("A user by the name of '" + name + "' does not seem to exist.");
}
uniqueId = profile.getUniqueId();
}
return domain.contains(uniqueId);
}
};
}
@Override
public Integer call() throws Exception {
Map<String, ProtectedRegion> regions = manager.getRegions();
// Build a list of regions to show
List<RegionListEntry> entries = new ArrayList<RegionListEntry>();
int index = 0;
for (String id : regions.keySet()) {
RegionListEntry entry = new RegionListEntry(id, index++);
// Filtering by owner?
ProtectedRegion region = regions.get(id);
if (ownerMatcher != null) {
entry.isOwner = ownerMatcher.isContainedWithin(region.getOwners());
entry.isMember = ownerMatcher.isContainedWithin(region.getMembers());
if (!entry.isOwner && !entry.isMember) {
continue; // Skip
}
}
entries.add(entry);
}
Collections.sort(entries);
final int totalSize = entries.size();
final int pageSize = 10;
final int pages = (int) Math.ceil(totalSize / (float) pageSize);
sender.sendMessage(ChatColor.RED
+ (ownerMatcher == null ? "Regions (page " : "Regions for " + ownerMatcher.getName() + " (page ")
+ (page + 1) + " of " + pages + "):");
if (page < pages) {
// Print
for (int i = page * pageSize; i < page * pageSize + pageSize; i++) {
if (i >= totalSize) {
break;
}
sender.sendMessage(ChatColor.YELLOW.toString() + entries.get(i));
}
}
return page;
}
private static interface OwnerMatcher {
public String getName();
public boolean isContainedWithin(DefaultDomain domain) throws CommandException;
}
private class RegionListEntry implements Comparable<RegionListEntry> {
private final String id;
private final int index;
boolean isOwner;
boolean isMember;
private RegionListEntry(String id, int index) {
this.id = id;
this.index = index;
}
@Override
public int compareTo(RegionListEntry o) {
if (isOwner != o.isOwner) {
return isOwner ? 1 : -1;
}
if (isMember != o.isMember) {
return isMember ? 1 : -1;
}
return id.compareTo(o.id);
}
@Override
public String toString() {
if (isOwner) {
return (index + 1) + ". +" + id;
} else if (isMember) {
return (index + 1) + ". -" + id;
} else {
return (index + 1) + ". " + id;
}
}
}
}
@@ -1,103 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Abstract listener to ease creation of listeners.
*/
class AbstractListener implements Listener {
private final WorldGuardPlugin plugin;
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public AbstractListener(WorldGuardPlugin plugin) {
checkNotNull(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the plugin.
*
* @return the plugin
*/
protected WorldGuardPlugin getPlugin() {
return plugin;
}
/**
* Get the global configuration.
*
* @return the configuration
*/
protected ConfigurationManager getConfig() {
return plugin.getGlobalStateManager();
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
/**
* Return whether region support is enabled.
*
* @param world the world
* @return true if region support is enabled
*/
protected boolean isRegionSupportEnabled(World world) {
return getWorldConfig(world).useRegions;
}
}
@@ -1,320 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.google.common.base.Predicate;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.event.*;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
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 org.bukkit.Location;
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.BlockDispenseEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import static com.sk89q.worldguard.bukkit.BukkitUtil.createTarget;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
/**
* Handle events that need to be processed by the blacklist.
*/
public class BlacklistListener extends AbstractListener {
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public BlacklistListener(WorldGuardPlugin plugin) {
super(plugin);
}
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, toVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false)) {
return false;
} else if (!wcfg.getBlacklist().check(
new ItemDestroyWithBlacklistEvent(localPlayer, toVector(target), createTarget(player.getItemInHand())), false, false)) {
return false;
}
return true;
}
});
}
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
return wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, toVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false);
}
});
}
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(new Predicate<Location>() {
@Override
public boolean apply(Location target) {
return wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, toVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false);
}
});
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Material material = Materials.getRelatedMaterial(event.getEffectiveType());
if (material != null) {
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(localPlayer, toVector(event.getTarget()), createTarget(material)), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Entity target = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (target instanceof Item) {
Item item = (Item) target;
if (!wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer,
toVector(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, toVector(event.getTarget()), createTarget(material)), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ItemStack target = event.getItemStack();
WorldConfiguration wcfg = getWorldConfig(player);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(localPlayer, toVector(player.getLocation()), createTarget(target)), false, false)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
if (!wcfg.getBlacklist().check(
new ItemDropBlacklistEvent(getPlugin().wrapPlayer(event.getPlayer()),
toVector(ci.getLocation()), createTarget(ci.getItemStack())), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(new BlockDispenseBlacklistEvent(null, toVector(event.getBlock()), createTarget(event.getItem())), false, false)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
HumanEntity entity = event.getWhoClicked();
Inventory inventory = event.getInventory();
ItemStack item = event.getCurrentItem();
if (item != null && entity instanceof Player) {
Player player = (Player) entity;
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, toVector(entity.getLocation()), createTarget(item)), false, false)) {
event.setCancelled(true);
if (inventory.getHolder().equals(player)) {
event.setCurrentItem(null);
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryCreative(InventoryCreativeEvent event) {
HumanEntity entity = event.getWhoClicked();
ItemStack item = event.getCursor();
if (item != null && entity instanceof Player) {
Player player = (Player) entity;
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, toVector(entity.getLocation()), createTarget(item)), false, false)) {
event.setCancelled(true);
event.setCursor(null);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
Inventory inventory = player.getInventory();
ItemStack item = inventory.getItem(event.getNewSlot());
if (item != null) {
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemAcquireBlacklistEvent(localPlayer, toVector(player.getLocation()), createTarget(item)), false, false)) {
inventory.setItem(event.getNewSlot(), null);
}
}
}
}
@@ -1,97 +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/>.
*/
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.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
/**
* Handles blocked potions.
*/
public class BlockedPotionsListener extends AbstractListener {
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public BlockedPotionsListener(WorldGuardPlugin plugin) {
super(plugin);
}
@EventHandler
public void onItemInteract(UseItemEvent event) {
ConfigurationManager cfg = getPlugin().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
ItemStack item = event.getItemStack();
// We only care about portions
if (item.getType() != Material.POTION || BukkitUtil.isWaterPotion(item)) {
return;
}
if (!wcfg.blockPotions.isEmpty()) {
PotionEffect blockedEffect = null;
Potion potion = Potion.fromDamage(BukkitUtil.getPotionEffectBits(item));
// Find the first blocked effect
for (PotionEffect effect : potion.getEffects()) {
if (wcfg.blockPotions.contains(effect.getType())) {
blockedEffect = effect;
break;
}
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
if (potion.isSplash() && wcfg.blockPotionsAlways) {
player.sendMessage(ChatColor.RED + "Sorry, potions with " +
blockedEffect.getType().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.getType().getName() + " are presently disabled.");
event.setCancelled(true);
}
} else {
event.setCancelled(true);
}
}
}
}
}
@@ -1,942 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.google.common.collect.Lists;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
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 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;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import com.sk89q.worldguard.bukkit.listener.debounce.BlockPistonExtendKey;
import com.sk89q.worldguard.bukkit.listener.debounce.BlockPistonRetractKey;
import com.sk89q.worldguard.bukkit.listener.debounce.EventDebounce;
import com.sk89q.worldguard.bukkit.listener.debounce.legacy.AbstractEventDebounce.Entry;
import com.sk89q.worldguard.bukkit.listener.debounce.legacy.BlockEntityEventDebounce;
import com.sk89q.worldguard.bukkit.listener.debounce.legacy.EntityEntityEventDebounce;
import com.sk89q.worldguard.bukkit.listener.debounce.legacy.InventoryMoveItemEventDebounce;
import com.sk89q.worldguard.bukkit.util.Blocks;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.*;
import org.bukkit.material.Dispenser;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static com.sk89q.worldguard.bukkit.cause.Cause.create;
public class EventAbstractionListener extends AbstractListener {
private final BlockEntityEventDebounce interactDebounce = new BlockEntityEventDebounce(10000);
private final EntityEntityEventDebounce pickupDebounce = new EntityEntityEventDebounce(10000);
private final BlockEntityEventDebounce entityBreakBlockDebounce = new BlockEntityEventDebounce(10000);
private final InventoryMoveItemEventDebounce moveItemDebounce = new InventoryMoveItemEventDebounce(30000);
private final EventDebounce<BlockPistonRetractKey> pistonRetractDebounce = EventDebounce.create(5000);
private final EventDebounce<BlockPistonExtendKey> pistonExtendDebounce = EventDebounce.create(5000);
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public EventAbstractionListener(WorldGuardPlugin plugin) {
super(plugin);
}
@Override
public void registerEvents() {
super.registerEvents();
try {
getPlugin().getServer().getPluginManager().registerEvents(new SpigotCompatListener(), getPlugin());
} catch (LinkageError ignored) {
}
}
//-------------------------------------------------------------------------
// Block break / place
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Events.fireToCancel(event, new BreakBlockEvent(event, create(event.getPlayer()), event.getBlock()));
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), event.getBlock().getLocation().add(0.5, 1, 0.5));
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
BlockState previousState = event.getBlockReplacedState();
// Some blocks, like tall grass and fire, get replaced
if (previousState.getType() != Material.AIR) {
Events.fireToCancel(event, new BreakBlockEvent(event, create(event.getPlayer()), previousState.getLocation(), previousState.getType()));
}
if (!event.isCancelled()) {
ItemStack itemStack = new ItemStack(event.getBlockPlaced().getType(), 1);
Events.fireToCancel(event, new UseItemEvent(event, create(event.getPlayer()), event.getPlayer().getWorld(), itemStack));
}
if (!event.isCancelled()) {
Events.fireToCancel(event, new PlaceBlockEvent(event, create(event.getPlayer()), event.getBlock()));
}
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), event.getBlockPlaced().getLocation().add(0.5, 0.5, 0.5));
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
Block target = event.getBlock();
Block[] adjacent = new Block[] {
target.getRelative(BlockFace.NORTH),
target.getRelative(BlockFace.SOUTH),
target.getRelative(BlockFace.WEST),
target.getRelative(BlockFace.EAST),
target.getRelative(BlockFace.UP),
target.getRelative(BlockFace.DOWN)};
int found = 0;
boolean allowed = false;
for (Block source : adjacent) {
if (source.getType() == Material.FIRE) {
found++;
if (Events.fireAndTestCancel(new BreakBlockEvent(event, create(source), target))) {
source.setType(Material.AIR);
} else {
allowed = true;
}
}
}
if (found > 0 && !allowed) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onStructureGrowEvent(StructureGrowEvent event) {
int originalCount = event.getBlocks().size();
List<Block> blockList = Lists.transform(event.getBlocks(), new BlockStateAsBlockFunction());
Player player = event.getPlayer();
if (player != null) {
Events.fireBulkEventToCancel(event, new PlaceBlockEvent(event, create(player), event.getLocation().getWorld(), blockList, Material.AIR));
} else {
Events.fireBulkEventToCancel(event, new PlaceBlockEvent(event, create(event.getLocation().getBlock()), event.getLocation().getWorld(), blockList, Material.AIR));
}
if (!event.isCancelled() && event.getBlocks().size() != originalCount) {
event.getLocation().getBlock().setType(Material.AIR);
}
}
// TODO: Handle EntityCreatePortalEvent?
@EventHandler(ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Block block = event.getBlock();
Entity entity = event.getEntity();
Material to = event.getTo();
// Forget about Redstone ore, especially since we handle it in INTERACT
if (Materials.isRedstoneOre(block.getType()) && Materials.isRedstoneOre(to)) {
return;
}
// Fire two events: one as BREAK and one as PLACE
if (event.getTo() != Material.AIR && event.getBlock().getType() != Material.AIR) {
Events.fireToCancel(event, new BreakBlockEvent(event, create(entity), block));
Events.fireToCancel(event, new PlaceBlockEvent(event, create(entity), block.getLocation(), to));
} else {
if (event.getTo() == Material.AIR) {
// Track the source so later we can create a proper chain of causes
if (entity instanceof FallingBlock) {
Cause.trackParentCause(entity, block);
// Switch around the event
Events.fireToCancel(event, new SpawnEntityEvent(event, create(block), entity));
} else {
entityBreakBlockDebounce.debounce(
event.getBlock(), event.getEntity(), event, new BreakBlockEvent(event, create(entity), event.getBlock()));
}
} else {
boolean wasCancelled = event.isCancelled();
Cause cause = create(entity);
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, event.getBlock().getLocation(), to));
if (event.isCancelled() && !wasCancelled && entity instanceof FallingBlock) {
FallingBlock fallingBlock = (FallingBlock) entity;
ItemStack itemStack = new ItemStack(fallingBlock.getMaterial(), 1, fallingBlock.getBlockData());
Item item = block.getWorld().dropItem(fallingBlock.getLocation(), itemStack);
item.setVelocity(new Vector());
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(block, entity), item))) {
item.remove();
}
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity();
Events.fireBulkEventToCancel(event, new BreakBlockEvent(event, create(entity), event.getLocation().getWorld(), event.blockList(), Material.AIR));
}
@SuppressWarnings("deprecation")
@EventHandler(ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isSticky()) {
EventDebounce.Entry entry = pistonRetractDebounce.getIfNotPresent(new BlockPistonRetractKey(event), event);
if (entry != null) {
Block piston = event.getBlock();
Cause cause = create(piston);
// Workaround for incorrect piston events
BlockFace direction = event.getDirection();
if (piston.getType() == Material.PISTON_MOVING_PIECE) {
direction = new PistonExtensionMaterial(Material.PISTON_STICKY_BASE.getId(), piston.getData()).getFacing();
}
Location retractLocation = piston.getRelative(direction, 2).getLocation();
Events.fireToCancel(event, new BreakBlockEvent(event, cause, retractLocation, Material.AIR));
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, piston.getRelative(direction)));
entry.setCancelled(event.isCancelled());
if (event.isCancelled()) {
playDenyEffect(piston.getLocation().add(0.5, 1, 0.5));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
EventDebounce.Entry entry = pistonExtendDebounce.getIfNotPresent(new BlockPistonExtendKey(event), event);
if (entry != null) {
// A hack for now
List<Block> blocks = new ArrayList<Block>(event.getBlocks());
Block lastBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1);
blocks.add(lastBlock);
int originalLength = blocks.size();
Events.fireBulkEventToCancel(event, new PlaceBlockEvent(event, create(event.getBlock()), event.getBlock().getWorld(), blocks, Material.STONE));
if (blocks.size() != originalLength) {
event.setCancelled(true);
}
entry.setCancelled(event.isCancelled());
if (event.isCancelled()) {
playDenyEffect(event.getBlock().getLocation().add(0.5, 1, 0.5));
}
}
}
//-------------------------------------------------------------------------
// Block external interaction
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
Block target = event.getBlock();
// Previously, and perhaps still, the only way to catch cake eating
// events was through here
if (target.getType() == Material.CAKE_BLOCK) {
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), target));
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
@Nullable ItemStack item = player.getItemInHand();
Block clicked = event.getClickedBlock();
Block placed;
boolean silent = false;
boolean modifiesWorld;
Cause cause = create(player);
switch (event.getAction()) {
case PHYSICAL:
// Forget about Redstone ore
if (Materials.isRedstoneOre(clicked.getType()) || clicked.getType() == Material.SOIL) {
silent = true;
}
interactDebounce.debounce(clicked, event.getPlayer(), event,
new UseBlockEvent(event, cause, clicked).setSilent(silent).setAllowed(hasInteractBypass(clicked)));
break;
case RIGHT_CLICK_BLOCK:
placed = clicked.getRelative(event.getBlockFace());
// Re-used for dispensers
handleBlockRightClick(event, create(event.getPlayer()), item, clicked, event.getBlockFace(), placed);
case LEFT_CLICK_BLOCK:
placed = clicked.getRelative(event.getBlockFace());
// Only fire events for blocks that are modified when right clicked
modifiesWorld = isBlockModifiedOnClick(clicked, event.getAction() == Action.RIGHT_CLICK_BLOCK) || (item != null && isItemAppliedToBlock(item, clicked));
if (Events.fireAndTestCancel(new UseBlockEvent(event, cause, clicked).setAllowed(!modifiesWorld))) {
event.setUseInteractedBlock(Result.DENY);
}
// Handle connected blocks (i.e. beds, chests)
for (Block connected : Blocks.getConnected(clicked)) {
if (Events.fireAndTestCancel(new UseBlockEvent(event, create(event.getPlayer()), connected).setAllowed(!modifiesWorld))) {
event.setUseInteractedBlock(Result.DENY);
break;
}
}
// Special handling of putting out fires
if (event.getAction() == Action.LEFT_CLICK_BLOCK && placed.getType() == Material.FIRE) {
if (Events.fireAndTestCancel(new BreakBlockEvent(event, create(event.getPlayer()), placed))) {
event.setUseInteractedBlock(Result.DENY);
break;
}
}
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), clicked.getLocation().add(0.5, 1, 0.5));
}
case LEFT_CLICK_AIR:
case RIGHT_CLICK_AIR:
if (item != null && !item.getType().isBlock() && Events.fireAndTestCancel(new UseItemEvent(event, cause, player.getWorld(), item))) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true); // The line above does not appear to work with spawn eggs
}
// Check for items that the administrator has configured to
// emit a "use block here" event where the player is
// standing, which is a hack to protect items that don't
// throw events
if (item != null && getWorldConfig(player.getWorld()).blockUseAtFeet.test(item)) {
if (Events.fireAndTestCancel(new UseBlockEvent(event, cause, player.getLocation().getBlock()))) {
event.setCancelled(true);
}
}
break;
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityInteract(org.bukkit.event.entity.EntityInteractEvent event) {
interactDebounce.debounce(event.getBlock(), event.getEntity(), event,
new UseBlockEvent(event, create(event.getEntity()), event.getBlock()).setAllowed(hasInteractBypass(event.getBlock())));
}
@EventHandler(ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
Block block = event.getBlock();
Material type = block.getType();
Cause cause;
// Find the cause
if (event.getPlayer() != null) {
cause = create(event.getPlayer());
} else if (event.getIgnitingEntity() != null) {
cause = create(event.getIgnitingEntity());
} else if (event.getIgnitingBlock() != null) {
cause = create(event.getIgnitingBlock());
} else {
cause = Cause.unknown();
}
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, block.getLocation(), Material.FIRE));
}
@EventHandler(ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), event.getBlock()));
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), event.getBlock().getLocation().add(0.5, 0.5, 0.5));
}
}
@EventHandler(ignoreCancelled = true)
public void onBedEnter(PlayerBedEnterEvent event) {
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), event.getBed()));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
Block blockAffected = event.getBlockClicked().getRelative(event.getBlockFace());
boolean allowed = false;
// Milk buckets can't be emptied as of writing
if (event.getBucket() == Material.MILK_BUCKET) {
allowed = true;
}
ItemStack item = new ItemStack(event.getBucket(), 1);
Material blockMaterial = Materials.getBucketBlockMaterial(event.getBucket());
Events.fireToCancel(event, new PlaceBlockEvent(event, create(player), blockAffected.getLocation(), blockMaterial).setAllowed(allowed));
Events.fireToCancel(event, new UseItemEvent(event, create(player), player.getWorld(), item).setAllowed(allowed));
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), blockAffected.getLocation().add(0.5, 0.5, 0.5));
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
Block blockAffected = event.getBlockClicked().getRelative(event.getBlockFace());
boolean allowed = false;
// Milk buckets can't be emptied as of writing
if (event.getBucket() == Material.MILK_BUCKET) {
allowed = true;
}
ItemStack item = new ItemStack(event.getBucket(), 1);
Events.fireToCancel(event, new BreakBlockEvent(event, create(player), blockAffected).setAllowed(allowed));
Events.fireToCancel(event, new UseItemEvent(event, create(player), player.getWorld(), item).setAllowed(allowed));
if (event.isCancelled()) {
playDenyEffect(event.getPlayer(), blockAffected.getLocation().add(0.5, 0.5, 0.5));
}
}
// TODO: Handle EntityPortalEnterEvent
//-------------------------------------------------------------------------
// Block self-interaction
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
WorldConfiguration config = getWorldConfig(event.getBlock().getWorld());
// This only applies to regions but nothing else cares about high
// frequency events at the moment
if (!config.useRegions || (!config.highFreqFlags && !config.checkLiquidFlow)) {
return;
}
Block from = event.getBlock();
Block to = event.getToBlock();
Material fromType = from.getType();
Material toType = to.getType();
// Liquids pass this event when flowing to solid blocks
if (toType.isSolid() && Materials.isLiquid(fromType)) {
return;
}
// This significantly reduces the number of events without having
// too much effect. Unfortunately it appears that even if this
// check didn't exist, you can raise the level of some liquid
// flow and the from/to data may not be correct.
if ((Materials.isWater(fromType) && Materials.isWater(toType)) || (Materials.isLava(fromType) && Materials.isLava(toType))) {
return;
}
Cause cause = create(from);
// Disable since it's probably not needed
/*if (from.getType() != Material.AIR) {
Events.fireToCancel(event, new BreakBlockEvent(event, cause, to));
}*/
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, to.getLocation(), from.getType()));
}
//-------------------------------------------------------------------------
// Entity break / place
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
switch (event.getSpawnReason()) {
case DISPENSE_EGG:
case EGG:
case SPAWNER_EGG:
if (getWorldConfig(event.getEntity().getWorld()).strictEntitySpawn) {
Events.fireToCancel(event, new SpawnEntityEvent(event, Cause.unknown(), event.getEntity()));
}
break;
case NATURAL:
case JOCKEY:
case CHUNK_GEN:
case SPAWNER:
case LIGHTNING:
case BUILD_SNOWMAN:
case BUILD_IRONGOLEM:
case BUILD_WITHER:
case VILLAGE_DEFENSE:
case VILLAGE_INVASION:
case BREEDING:
case SLIME_SPLIT:
case REINFORCEMENTS:
case NETHER_PORTAL:
case INFECTION:
case CURED:
case OCELOT_BABY:
case SILVERFISH_BLOCK:
case MOUNT:
case CUSTOM:
case DEFAULT:
}
}
@EventHandler(ignoreCancelled = true)
public void onHangingPlace(HangingPlaceEvent event) {
Events.fireToCancel(event, new SpawnEntityEvent(event, create(event.getPlayer()), event.getEntity()));
if (event.isCancelled()) {
Block effectBlock = event.getBlock().getRelative(event.getBlockFace());
playDenyEffect(event.getPlayer(), effectBlock.getLocation().add(0.5, 0.5, 0.5));
}
}
@EventHandler(ignoreCancelled = true)
public void onHangingBreak(HangingBreakEvent event) {
if (event instanceof HangingBreakByEntityEvent) {
Entity remover = ((HangingBreakByEntityEvent) event).getRemover();
Events.fireToCancel(event, new DestroyEntityEvent(event, create(remover), event.getEntity()));
if (event.isCancelled() && remover instanceof Player) {
playDenyEffect((Player) remover, event.getEntity().getLocation());
}
}
}
@EventHandler(ignoreCancelled = true)
public void onVehicleDestroy(VehicleDestroyEvent event) {
Events.fireToCancel(event, new DestroyEntityEvent(event, create(event.getAttacker()), event.getVehicle()));
}
@EventHandler(ignoreCancelled = true)
public void onBlockExp(BlockExpEvent event) {
if (event.getExpToDrop() > 0) { // Event is raised even where no XP is being dropped
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getBlock()), event.getBlock().getLocation(), EntityType.EXPERIENCE_ORB))) {
event.setExpToDrop(0);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerFish(PlayerFishEvent event) {
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getPlayer(), event.getHook()), event.getHook().getLocation(), EntityType.EXPERIENCE_ORB))) {
event.setExpToDrop(0);
}
}
@EventHandler(ignoreCancelled = true)
public void onExpBottle(ExpBottleEvent event) {
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getEntity()), event.getEntity().getLocation(), EntityType.EXPERIENCE_ORB))) {
event.setExperience(0);
// Give the player back his or her XP bottle
ProjectileSource shooter = event.getEntity().getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
if (player.getGameMode() != GameMode.CREATIVE) {
player.getInventory().addItem(new ItemStack(Material.EXP_BOTTLE, 1));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityDeath(EntityDeathEvent event) {
if (event.getDroppedExp() > 0) {
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getEntity()), event.getEntity().getLocation(), EntityType.EXPERIENCE_ORB))) {
event.setDroppedExp(0);
}
}
}
//-------------------------------------------------------------------------
// Entity external interaction
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ItemStack item = player.getItemInHand();
Entity entity = event.getRightClicked();
Events.fireToCancel(event, new UseItemEvent(event, create(player), world, item));
Events.fireToCancel(event, new UseEntityEvent(event, create(player), entity));
}
@EventHandler(ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof EntityDamageByBlockEvent) {
@Nullable Block attacker = ((EntityDamageByBlockEvent) event).getDamager();
// The attacker should NOT be null, but sometimes it is
// See WORLDGUARD-3350
if (attacker != null) {
Events.fireToCancel(event, new DamageEntityEvent(event, create(attacker), event.getEntity()));
}
} else if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent entityEvent = (EntityDamageByEntityEvent) event;
Entity damager = entityEvent.getDamager();
Events.fireToCancel(event, new DamageEntityEvent(event, create(damager), event.getEntity()));
// Item use event with the item in hand
// Older blacklist handler code used this, although it suffers from
// race problems
if (damager instanceof Player) {
ItemStack item = ((Player) damager).getItemInHand();
if (item != null) {
Events.fireToCancel(event, new UseItemEvent(event, create(damager), event.getEntity().getWorld(), item));
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
if (event instanceof EntityCombustByBlockEvent) {
Events.fireToCancel(event, new DamageEntityEvent(event, create(((EntityCombustByBlockEvent) event).getCombuster()), event.getEntity()));
} else if (event instanceof EntityCombustByEntityEvent) {
Events.fireToCancel(event, new DamageEntityEvent(event, create(((EntityCombustByEntityEvent) event).getCombuster()), event.getEntity()));
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityUnleash(EntityUnleashEvent event) {
if (event instanceof PlayerUnleashEntityEvent) {
PlayerUnleashEntityEvent playerEvent = (PlayerUnleashEntityEvent) event;
Events.fireToCancel(playerEvent, new UseEntityEvent(playerEvent, create(playerEvent.getPlayer()), event.getEntity()));
} else {
// TODO: Raise anyway?
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityTame(EntityTameEvent event) {
Events.fireToCancel(event, new UseEntityEvent(event, create(event.getOwner()), event.getEntity()));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerShearEntity(PlayerShearEntityEvent event) {
Events.fireToCancel(event, new UseEntityEvent(event, create(event.getPlayer()), event.getEntity()));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Item item = event.getItem();
pickupDebounce.debounce(event.getPlayer(), item, event, new DestroyEntityEvent(event, create(event.getPlayer()), event.getItem()));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
Events.fireToCancel(event, new SpawnEntityEvent(event, create(event.getPlayer()), event.getItemDrop()));
}
@EventHandler(ignoreCancelled = true)
public void onVehicleDamage(VehicleDamageEvent event) {
Entity attacker = event.getAttacker();
Events.fireToCancel(event, new DamageEntityEvent(event, create(attacker), event.getVehicle()));
}
@EventHandler(ignoreCancelled = true)
public void onVehicleEnter(VehicleDamageEvent event) {
Events.fireToCancel(event, new UseEntityEvent(event, create(event.getAttacker()), event.getVehicle()));
}
//-------------------------------------------------------------------------
// Composite events
//-------------------------------------------------------------------------
@EventHandler(ignoreCancelled = true)
public void onPlayerItemConsume(PlayerItemConsumeEvent event) {
Events.fireToCancel(event, new UseItemEvent(event, create(event.getPlayer()), event.getPlayer().getWorld(), event.getItem()));
}
@EventHandler(ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) {
InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState) {
Events.fireToCancel(event, new UseBlockEvent(event, create(event.getPlayer()), ((BlockState) holder).getBlock()));
} else if (holder instanceof Entity) {
if (!(holder instanceof Player)) {
Events.fireToCancel(event, new UseEntityEvent(event, create(event.getPlayer()), (Entity) holder));
}
}
}
@EventHandler(ignoreCancelled = true)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
final InventoryHolder causeHolder = event.getInitiator().getHolder();
InventoryHolder sourceHolder = event.getSource().getHolder();
InventoryHolder targetHolder = event.getDestination().getHolder();
Entry entry;
if ((entry = moveItemDebounce.tryDebounce(event)) != null) {
Cause cause;
if (causeHolder instanceof Entity) {
cause = create(causeHolder);
} else if (causeHolder instanceof BlockState) {
cause = create(((BlockState) causeHolder).getBlock());
} else {
cause = Cause.unknown();
}
if (!causeHolder.equals(sourceHolder)) {
handleInventoryHolderUse(event, cause, sourceHolder);
}
handleInventoryHolderUse(event, cause, targetHolder);
if (event.isCancelled() && causeHolder instanceof Hopper) {
Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() {
@Override
public void run() {
((Hopper) causeHolder).getBlock().breakNaturally();
}
});
} else {
entry.setCancelled(event.isCancelled());
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
Entity entity = event.getEntity();
ThrownPotion potion = event.getPotion();
World world = entity.getWorld();
Cause cause = create(potion);
// Fire item interaction event
Events.fireToCancel(event, new UseItemEvent(event, cause, world, potion.getItem()));
// Fire entity interaction event
if (!event.isCancelled()) {
int blocked = 0;
boolean hasDamageEffect = Materials.hasDamageEffect(potion.getEffects());
for (LivingEntity affected : event.getAffectedEntities()) {
DelegateEvent delegate = hasDamageEffect
? new DamageEntityEvent(event, cause, affected) :
new UseEntityEvent(event, cause, affected);
// Consider the potion splash flag
delegate.getRelevantFlags().add(DefaultFlag.POTION_SPLASH);
if (Events.fireAndTestCancel(delegate)) {
event.setIntensity(affected, 0);
blocked++;
}
}
if (blocked == event.getAffectedEntities().size()) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
Cause cause = create(event.getBlock());
Block dispenserBlock = event.getBlock();
ItemStack item = event.getItem();
MaterialData materialData = dispenserBlock.getState().getData();
Events.fireToCancel(event, new UseItemEvent(event, cause, dispenserBlock.getWorld(), item));
// Simulate right click event as players have it
if (materialData instanceof Dispenser) {
Dispenser dispenser = (Dispenser) materialData;
Block placed = dispenserBlock.getRelative(dispenser.getFacing());
Block clicked = placed.getRelative(dispenser.getFacing());
handleBlockRightClick(event, cause, item, clicked, dispenser.getFacing().getOppositeFace(), placed);
}
}
/**
* Handle the right click of a block while an item is held.
*
* @param event the original event
* @param cause the list of cause
* @param item the item
* @param clicked the clicked block
* @param faceClicked the face of the clicked block
* @param placed the placed block
* @param <T> the event type
*/
private static <T extends Event & Cancellable> void handleBlockRightClick(T event, Cause cause, @Nullable ItemStack item, Block clicked, BlockFace faceClicked, Block placed) {
if (item != null && item.getType() == Material.TNT) {
// Workaround for a bug that allowed TNT to trigger instantly if placed
// next to redstone, without plugins getting the clicked place event
// (not sure if this actually still happens)
Events.fireToCancel(event, new UseBlockEvent(event, cause, clicked.getLocation(), Material.TNT));
}
// Handle created Minecarts
if (item != null && Materials.isMinecart(item.getType())) {
// TODO: Give a more specific Minecart type
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), EntityType.MINECART));
}
// Handle created boats
if (item != null && item.getType() == Material.BOAT) {
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), EntityType.BOAT));
}
// Handle created armor stands
if (item != null && item.getType() == Materials.ARMOR_STAND) {
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), EntityType.ARMOR_STAND));
}
// Handle created spawn eggs
if (item != null && item.getType() == Material.MONSTER_EGG) {
MaterialData data = item.getData();
if (data instanceof SpawnEgg) {
@Nullable EntityType type = ((SpawnEgg) data).getSpawnedType();
if (type == null) {
type = EntityType.SHEEP; // Haven't investigated why it's sometimes null
}
Events.fireToCancel(event, new SpawnEntityEvent(event, cause, placed.getLocation().add(0.5, 0, 0.5), type));
}
}
// Handle cocoa beans
if (item != null && item.getType() == Material.INK_SACK && Materials.isDyeColor(item.getData(), DyeColor.BROWN)) {
// CraftBukkit doesn't or didn't throw a clicked place for this
if (!(faceClicked == BlockFace.DOWN || faceClicked == BlockFace.UP)) {
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, placed.getLocation(), Material.COCOA));
}
}
// Workaround for http://leaky.bukkit.org/issues/1034
if (item != null && item.getType() == Material.TNT) {
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, placed.getLocation(), Material.TNT));
}
}
@SuppressWarnings("unchecked")
private static <T extends Event & Cancellable> void handleInventoryHolderUse(T originalEvent, Cause cause, InventoryHolder holder) {
if (originalEvent.isCancelled()) {
return;
}
if (holder instanceof Entity) {
Events.fireToCancel(originalEvent, new UseEntityEvent(originalEvent, cause, (Entity) holder));
} else if (holder instanceof BlockState) {
Events.fireToCancel(originalEvent, new UseBlockEvent(originalEvent, cause, ((BlockState) holder).getBlock()));
} else if (holder instanceof DoubleChest) {
Events.fireToCancel(originalEvent, new UseBlockEvent(originalEvent, cause, ((BlockState) ((DoubleChest) holder).getLeftSide()).getBlock()));
Events.fireToCancel(originalEvent, new UseBlockEvent(originalEvent, cause, ((BlockState) ((DoubleChest) holder).getRightSide()).getBlock()));
}
}
private boolean hasInteractBypass(Block block) {
return getWorldConfig(block.getWorld()).allowAllInteract.test(block);
}
private boolean hasInteractBypass(World world, ItemStack item) {
return getWorldConfig(world).allowAllInteract.test(item);
}
private boolean isBlockModifiedOnClick(Block block, boolean rightClick) {
return Materials.isBlockModifiedOnClick(block.getType(), rightClick) && !hasInteractBypass(block);
}
private boolean isItemAppliedToBlock(ItemStack item, Block clicked) {
return Materials.isItemAppliedToBlock(item.getType(), clicked.getType())
&& !hasInteractBypass(clicked)
&& !hasInteractBypass(clicked.getWorld(), item);
}
private void playDenyEffect(Player player, Location location) {
//player.playSound(location, Sound.SUCCESSFUL_HIT, 0.2f, 0.4f);
player.playEffect(location, Effect.SMOKE, BlockFace.UP);
}
private void playDenyEffect(Location location) {
location.getWorld().playEffect(location, Effect.SMOKE, BlockFace.UP);
}
public class SpigotCompatListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event){
onPlayerInteractEntity(event);
}
@EventHandler(ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
Events.fireBulkEventToCancel(event, new BreakBlockEvent(event, create(event.getBlock()),
event.getBlock().getLocation().getWorld(), event.blockList(), Material.AIR));
}
}
}
@@ -1,118 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
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.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
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 implements Listener {
private final WorldGuardPlugin plugin;
public PlayerMoveListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
if (plugin.getGlobalStateManager().usePlayerMove) {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Session session = plugin.getSessionManager().get(player);
session.testMoveTo(player, event.getRespawnLocation(), MoveType.RESPAWN, true);
}
@EventHandler
public void onVehicleEnter(VehicleEnterEvent event) {
Entity entity = event.getEntered();
if (entity instanceof Player) {
Player player = (Player) entity;
Session session = plugin.getSessionManager().get(player);
if (null != session.testMoveTo(player, event.getVehicle().getLocation(), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(PlayerMoveEvent event) {
final Player player = event.getPlayer();
Session session = plugin.getSessionManager().get(player);
final Location override = session.testMoveTo(player, event.getTo(), MoveType.MOVE);
if (override != null) {
override.setX(override.getBlockX() + 0.5);
override.setY(override.getBlockY());
override.setZ(override.getBlockZ() + 0.5);
override.setPitch(event.getTo().getPitch());
override.setYaw(event.getTo().getYaw());
event.setTo(override.clone());
Entity vehicle = player.getVehicle();
if (vehicle != null) {
vehicle.eject();
Entity current = vehicle;
while (current != null) {
current.eject();
vehicle.setVelocity(new Vector());
if (vehicle instanceof LivingEntity) {
vehicle.teleport(override.clone());
} else {
vehicle.teleport(override.clone().add(0, 1, 0));
}
current = current.getVehicle();
}
player.teleport(override.clone().add(0, 1, 0));
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
player.teleport(override.clone().add(0, 1, 0));
}
}, 1);
}
}
}
}
@@ -1,132 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.World;
import static com.sk89q.worldguard.bukkit.BukkitUtil.isBlockWater;
import static com.sk89q.worldguard.bukkit.BukkitUtil.setBlockToWater;
public final class SpongeUtil {
private SpongeUtil() {
}
/**
* Remove water around a sponge.
*
* @param plugin The plugin instace
* @param world The world the sponge isin
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void clearSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water around a sponge.
*
* @param plugin The plugin instance
* @param world The world the sponge is located in
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void addSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// The negative x edge
int cx = ox - wcfg.spongeRadius - 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx + 1, cy, cz);
}
}
}
// The positive x edge
cx = ox + wcfg.spongeRadius + 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx - 1, cy, cz);
}
}
}
// The negative y edge
int cy = oy - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy + 1, cz);
}
}
}
// The positive y edge
cy = oy + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy - 1, cz);
}
}
}
// The negative z edge
int cz = oz - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz + 1);
}
}
}
// The positive z edge
cz = oz + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz - 1);
}
}
}
}
}
@@ -1,667 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowman;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.inventory.ItemStack;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block target = event.getBlock();
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getType() != Material.AIR && !(ItemType.usesDamageValue(held.getTypeId())|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) 0);
player.setItemInHand(held);
}
}
}
/*
* Called when fluids flow.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
boolean isAir = blockFrom.getTypeId() == 0;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
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.getTypeId() == 19
&& (!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.size() > 0) {
int targetId = blockTo.getTypeId();
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.highFreqFlags && isWater
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.WATER_FLOW,
blockFrom.getLocation())) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && isLava
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.LAVA_FLOW,
blockFrom.getLocation())) {
event.setCancelled(true);
return;
}
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& (blockTo.getTypeId() == BlockID.REDSTONE_WIRE
|| blockTo.getTypeId() == BlockID.TRIPWIRE)) {
blockTo.setTypeId(BlockID.AIR);
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 = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
if (wcfg.highFreqFlags && isFireSpread
&& !set.allows(DefaultFlag.FIRE_SPREAD)) {
event.setCancelled(true);
return;
}
if (wcfg.highFreqFlags && cause == IgniteCause.LAVA
&& !set.allows(DefaultFlag.LAVA_FIRE)) {
event.setCancelled(true);
return;
}
if (cause == IgniteCause.FIREBALL && event.getPlayer() == null) {
// wtf bukkit, FIREBALL is supposed to be reserved to players
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.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 = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
if (wcfg.isChestProtected(event.getBlock())) {
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 = plugin.getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, BlockID.FIRE);
event.setCancelled(true);
}
}
}
private void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
private void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
}
}
/*
* Called when block physics occurs.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int id = event.getBlock().getTypeId();
if (id == 13 && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
if (wcfg.ropeLadders && event.getBlock().getType() == Material.LADDER) {
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();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(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(plugin, world, ox, oy, oz);
}
}
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -1; cx <= 1; cx++) {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
}
}
}
}
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY,
event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
}
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int type = event.getNewState().getTypeId();
if (event instanceof EntityBlockFormEvent) {
if (((EntityBlockFormEvent) event).getEntity() instanceof Snowman) {
if (wcfg.disableSnowmanTrails) {
event.setCancelled(true);
return;
}
}
return;
}
if (type == BlockID.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_FORM, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (type == BlockID.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.allowedSnowFallOver.size() > 0) {
int targetId = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedSnowFallOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_FALL, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
int fromType = event.getSource().getTypeId();
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.MUSHROOMS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.GRASS) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.GRASS_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.MYCELIUM) {
if (wcfg.disableMyceliumSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.MYCELIUM_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.VINE) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.VINE_GROWTH, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
switch (event.getBlock().getTypeId()) {
case BlockID.ICE:
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
break;
case BlockID.SNOW:
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
break;
case BlockID.SOIL:
if (wcfg.disableSoilDehydration) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SOIL_DRY, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
break;
}
}
}
@@ -1,401 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.blocks.BlockID;
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.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.GameModeFlag;
import com.sk89q.worldguard.util.command.CommandFilter;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Handles all events thrown in relation to a player.
*/
public class WorldGuardPlayerListener implements Listener {
private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName());
private static final Pattern opPattern = Pattern.compile("^/(?:bukkit:)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
this.plugin = 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);
if (session != null) {
GameModeFlag handler = session.getHandler(GameModeFlag.class);
if (handler != null && wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(player, player.getWorld())) {
GameMode expected = handler.getSetGameMode();
if (handler.getOriginalGameMode() != null && expected != null && expected != event.getNewGameMode()) {
log.info("Game mode change on " + player.getName() + " has been blocked due to the region GAMEMODE flag");
event.setCancelled(true);
}
}
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (cfg.activityHaltToggle) {
player.sendMessage(ChatColor.YELLOW
+ "Intensive server activity has been HALTED.");
int removed = 0;
for (Entity entity : world.getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
if (removed > 10) {
log.info("Halt-Act: " + removed + " entities (>10) auto-removed from "
+ player.getWorld().toString());
}
}
if (wcfg.fireSpreadDisableToggle) {
player.sendMessage(ChatColor.YELLOW
+ "Fire spread is currently globally disabled for this world.");
}
Events.fire(new ProcessPlayerEvent(player));
plugin.getSessionManager().get(player); // Initializes a session
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(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!");
event.setCancelled(true);
return;
}
for (Iterator<Player> i = event.getRecipients().iterator(); i.hasNext();) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.RECEIVE_CHAT, i.next().getLocation())) {
i.remove();
}
}
if (event.getRecipients().size() == 0) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
String hostKey = cfg.hostKeys.get(player.getName().toLowerCase());
if (hostKey != null) {
String hostname = event.getHostname();
int colonIndex = hostname.indexOf(':');
if (colonIndex != -1) {
hostname = hostname.substring(0, colonIndex);
}
if (!hostname.equals(hostKey)) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"You did not join with the valid host key!");
log.warning("WorldGuard host key check: " +
player.getName() + " joined with '" + hostname +
"' but '" + hostKey + "' was expected. Kicked!");
return;
}
}
if (cfg.deopOnJoin) {
player.setOp(false);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
handleBlockRightClick(event);
} else if (event.getAction() == Action.PHYSICAL) {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int slot = player.getInventory().getHeldItemSlot();
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
player.getInventory().setItem(slot, null);
player.sendMessage(ChatColor.RED + "Infinite stack removed.");
}
}
}
/**
* Called when a player right clicks a block.
*
* @param event Thrown event
*/
private void handleBlockRightClick(PlayerInteractEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getClickedBlock();
World world = block.getWorld();
int type = block.getTypeId();
Player player = event.getPlayer();
ItemStack item = player.getItemInHand();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(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)
&& wcfg.removeInfiniteStacks
&& !plugin.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) {
player.getInventory().setItem(slot, null);
player.sendMessage(ChatColor.RED + "Infinite stack in slot #" + slot + " removed.");
}
}
}
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);
if (item.getTypeId() == wcfg.regionWand && plugin.hasPermission(player, "worldguard.region.wand")) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? "
+ (set.canBuild(localPlayer) ? "Yes" : "No"));
StringBuilder str = new StringBuilder();
for (Iterator<ProtectedRegion> it = set.iterator(); it.hasNext();) {
str.append(it.next().getId());
if (it.hasNext()) {
str.append(", ");
}
}
player.sendMessage(ChatColor.YELLOW + "Applicable regions: " + str.toString());
} else {
player.sendMessage(ChatColor.YELLOW + "WorldGuard: No defined regions here!");
}
event.setCancelled(true);
}
}
}
/**
* Called when a player steps on a pressure plate or tramples crops.
*
* @param event Thrown event
*/
private void handlePhysicalInteract(PlayerInteractEvent event) {
if (event.isCancelled()) return;
Player player = event.getPlayer();
Block block = event.getClickedBlock(); //not actually clicked but whatever
int type = block.getTypeId();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (block.getTypeId() == BlockID.SOIL && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
}
@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 (wcfg.useRegions) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(location);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
com.sk89q.worldedit.Location spawn = set.getFlag(DefaultFlag.SPAWN_LOC, localPlayer);
if (spawn != null) {
event.setRespawnLocation(com.sk89q.worldedit.bukkit.BukkitUtil.toLocation(spawn));
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int newSlot = event.getNewSlot();
ItemStack heldItem = player.getInventory().getItem(newSlot);
if (heldItem != null && heldItem.getAmount() < 0) {
player.getInventory().setItem(newSlot, null);
player.sendMessage(ChatColor.RED + "Infinite stack removed.");
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
World world = event.getFrom().getWorld();
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
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 (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;
}
}
}
}
@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);
if (wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(player, world)) {
ApplicableRegionSet set = plugin.getRegionContainer().createQuery().getApplicableRegions(player.getLocation());
Set<String> allowedCommands = set.getFlag(DefaultFlag.ALLOWED_CMDS, localPlayer);
Set<String> blockedCommands = set.getFlag(DefaultFlag.BLOCKED_CMDS, localPlayer);
CommandFilter test = new CommandFilter(allowedCommands, blockedCommands);
if (!test.apply(event.getMessage())) {
player.sendMessage(ChatColor.RED + event.getMessage() + " is not allowed in this area.");
event.setCancelled(true);
return;
}
}
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).");
event.setCancelled(true);
return;
}
}
}
}
@@ -1,74 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Locations;
import com.sk89q.worldguard.session.MoveType;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.util.Vector;
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
if (vehicle.getPassenger() == null || !(vehicle.getPassenger() instanceof Player)) return;
Player player = (Player) vehicle.getPassenger();
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
// Did we move a block?
if (Locations.isDifferentBlock(event.getFrom(), event.getTo())) {
if (null != plugin.getSessionManager().get(player).testMoveTo(player, event.getTo(), MoveType.RIDE)) {
vehicle.setVelocity(new Vector(0,0,0));
vehicle.teleport(event.getFrom());
}
}
}
}
}
@@ -1,54 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener.debounce;
import org.bukkit.block.Block;
public class BlockBlockPair {
private final BlockMaterialPair block1;
private final BlockMaterialPair block2;
public BlockBlockPair(Block block1, Block block2) {
this.block1 = new BlockMaterialPair(block1);
this.block2 = new BlockMaterialPair(block2);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockBlockPair that = (BlockBlockPair) o;
if (!block1.equals(that.block1)) return false;
if (!block2.equals(that.block2)) return false;
return true;
}
@Override
public int hashCode() {
int result = block1.hashCode();
result = 31 * result + block2.hashCode();
return result;
}
}
@@ -1,58 +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/>.
*/
package com.sk89q.worldguard.bukkit.listener.debounce;
import org.bukkit.Material;
import org.bukkit.block.Block;
import static com.google.common.base.Preconditions.checkNotNull;
public class BlockMaterialPair {
private final Block block;
private final Material material;
public BlockMaterialPair(Block block) {
checkNotNull(block);
this.block = block;
this.material = block.getType();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockMaterialPair blockKey = (BlockMaterialPair) o;
if (!block.equals(blockKey.block)) return false;
if (material != blockKey.material) return false;
return true;
}
@Override
public int hashCode() {
int result = block.hashCode();
result = 31 * result + material.hashCode();
return result;
}
}
@@ -1,48 +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/>.
*/
package com.sk89q.worldguard.bukkit.permission;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.internal.PermissionModel;
abstract class AbstractPermissionModel implements PermissionModel {
private final WorldGuardPlugin plugin;
private final CommandSender sender;
public AbstractPermissionModel(WorldGuardPlugin plugin, CommandSender sender) {
this.plugin = plugin;
this.sender = sender;
}
protected WorldGuardPlugin getPlugin() {
return plugin;
}
public CommandSender getSender() {
return sender;
}
protected boolean hasPluginPermission(String permission) {
return plugin.hasPermission(getSender(), "worldguard." + permission);
}
}
@@ -1,87 +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/>.
*/
package com.sk89q.worldguard.bukkit.util;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.material.Bed;
import org.bukkit.material.Chest;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Utility methods to deal with blocks.
*/
public final class Blocks {
private Blocks() {
}
/**
* Get a list of connected blocks to the given block, not including
* the given block.
*
* @param block the block
* @return a list of connected blocks, not including the given block
*/
public static List<Block> getConnected(Block block) {
BlockState state = block.getState();
MaterialData data = state.getData();
if (data instanceof Bed) {
Bed bed = (Bed) data;
if (bed.isHeadOfBed()) {
return Arrays.asList(block.getRelative(bed.getFacing().getOppositeFace()));
} else {
return Arrays.asList(block.getRelative(bed.getFacing()));
}
} else if (data instanceof Chest) {
BlockFace facing = ((Chest) data).getFacing();
ArrayList<Block> chests = new ArrayList<Block>();
if (facing == BlockFace.NORTH || facing == BlockFace.SOUTH) {
if (block.getRelative(BlockFace.EAST).getState().getData() instanceof Chest) {
chests.add(block.getRelative(BlockFace.EAST));
}
if (block.getRelative(BlockFace.WEST).getState().getData() instanceof Chest) {
chests.add(block.getRelative(BlockFace.WEST));
}
} else if (facing == BlockFace.EAST || facing == BlockFace.WEST) {
if (block.getRelative(BlockFace.NORTH).getState().getData() instanceof Chest) {
chests.add(block.getRelative(BlockFace.NORTH));
}
if (block.getRelative(BlockFace.SOUTH).getState().getData() instanceof Chest) {
chests.add(block.getRelative(BlockFace.SOUTH));
}
} else {
// don't know how to handle diagonal chests
return Collections.emptyList();
}
return chests;
} else {
return Collections.emptyList();
}
}
}
@@ -1,782 +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/>.
*/
package com.sk89q.worldguard.bukkit.util;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.material.Dye;
import org.bukkit.material.MaterialData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import javax.annotation.Nullable;
import java.util.*;
/**
* Material utility class.
*/
public final class Materials {
private static final int MODIFIED_ON_RIGHT = 1;
private static final int MODIFIED_ON_LEFT = 2;
private static final int MODIFIES_BLOCKS = 4;
private static final BiMap<EntityType, Material> ENTITY_ITEMS = HashBiMap.create();
private static final Map<Material, Integer> MATERIAL_FLAGS = new HashMap<Material, Integer>();
private static final Set<PotionEffectType> DAMAGE_EFFECTS = new HashSet<PotionEffectType>();
public static Material ARMOR_STAND;
static {
try {
ARMOR_STAND = Material.ARMOR_STAND;
} catch (NoSuchFieldError ignored) {
ARMOR_STAND = null;
}
ENTITY_ITEMS.put(EntityType.PAINTING, Material.PAINTING);
ENTITY_ITEMS.put(EntityType.ARROW, Material.ARROW);
ENTITY_ITEMS.put(EntityType.SNOWBALL, Material.SNOW_BALL);
ENTITY_ITEMS.put(EntityType.FIREBALL, Material.FIREBALL);
ENTITY_ITEMS.put(EntityType.SMALL_FIREBALL, Material.FIREWORK_CHARGE);
ENTITY_ITEMS.put(EntityType.ENDER_PEARL, Material.ENDER_PEARL);
ENTITY_ITEMS.put(EntityType.THROWN_EXP_BOTTLE, Material.EXP_BOTTLE);
ENTITY_ITEMS.put(EntityType.ITEM_FRAME, Material.ITEM_FRAME);
ENTITY_ITEMS.put(EntityType.PRIMED_TNT, Material.TNT);
ENTITY_ITEMS.put(EntityType.FIREWORK, Material.FIREWORK);
ENTITY_ITEMS.put(EntityType.MINECART_COMMAND, Material.COMMAND_MINECART);
ENTITY_ITEMS.put(EntityType.BOAT, Material.BOAT);
ENTITY_ITEMS.put(EntityType.MINECART, Material.MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_CHEST, Material.STORAGE_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_FURNACE, Material.POWERED_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_TNT, Material.EXPLOSIVE_MINECART);
ENTITY_ITEMS.put(EntityType.MINECART_HOPPER, Material.HOPPER_MINECART);
ENTITY_ITEMS.put(EntityType.SPLASH_POTION, Material.POTION);
ENTITY_ITEMS.put(EntityType.EGG, Material.EGG);
try {
ENTITY_ITEMS.put(EntityType.ARMOR_STAND, Material.ARMOR_STAND);
} catch (NoSuchFieldError ignored) {}
MATERIAL_FLAGS.put(Material.AIR, 0);
MATERIAL_FLAGS.put(Material.STONE, 0);
MATERIAL_FLAGS.put(Material.GRASS, 0);
MATERIAL_FLAGS.put(Material.DIRT, 0);
MATERIAL_FLAGS.put(Material.COBBLESTONE, 0);
MATERIAL_FLAGS.put(Material.WOOD, 0);
MATERIAL_FLAGS.put(Material.SAPLING, 0);
MATERIAL_FLAGS.put(Material.BEDROCK, 0);
MATERIAL_FLAGS.put(Material.WATER, 0);
MATERIAL_FLAGS.put(Material.STATIONARY_WATER, 0);
MATERIAL_FLAGS.put(Material.LAVA, 0);
MATERIAL_FLAGS.put(Material.STATIONARY_LAVA, 0);
MATERIAL_FLAGS.put(Material.SAND, 0);
MATERIAL_FLAGS.put(Material.GRAVEL, 0);
MATERIAL_FLAGS.put(Material.GOLD_ORE, 0);
MATERIAL_FLAGS.put(Material.IRON_ORE, 0);
MATERIAL_FLAGS.put(Material.COAL_ORE, 0);
MATERIAL_FLAGS.put(Material.LOG, 0);
MATERIAL_FLAGS.put(Material.LEAVES, 0);
MATERIAL_FLAGS.put(Material.SPONGE, 0);
MATERIAL_FLAGS.put(Material.GLASS, 0);
MATERIAL_FLAGS.put(Material.LAPIS_ORE, 0);
MATERIAL_FLAGS.put(Material.LAPIS_BLOCK, 0);
MATERIAL_FLAGS.put(Material.DISPENSER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SANDSTONE, 0);
MATERIAL_FLAGS.put(Material.NOTE_BLOCK, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BED_BLOCK, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.POWERED_RAIL, 0);
MATERIAL_FLAGS.put(Material.DETECTOR_RAIL, 0);
MATERIAL_FLAGS.put(Material.PISTON_STICKY_BASE, 0);
MATERIAL_FLAGS.put(Material.WEB, 0);
MATERIAL_FLAGS.put(Material.LONG_GRASS, 0);
MATERIAL_FLAGS.put(Material.DEAD_BUSH, 0);
MATERIAL_FLAGS.put(Material.PISTON_BASE, 0);
MATERIAL_FLAGS.put(Material.PISTON_EXTENSION, 0);
MATERIAL_FLAGS.put(Material.WOOL, 0);
MATERIAL_FLAGS.put(Material.PISTON_MOVING_PIECE, 0);
MATERIAL_FLAGS.put(Material.YELLOW_FLOWER, 0);
MATERIAL_FLAGS.put(Material.RED_ROSE, 0);
MATERIAL_FLAGS.put(Material.BROWN_MUSHROOM, 0);
MATERIAL_FLAGS.put(Material.RED_MUSHROOM, 0);
MATERIAL_FLAGS.put(Material.GOLD_BLOCK, 0);
MATERIAL_FLAGS.put(Material.IRON_BLOCK, 0);
MATERIAL_FLAGS.put(Material.DOUBLE_STEP, 0);
MATERIAL_FLAGS.put(Material.STEP, 0);
MATERIAL_FLAGS.put(Material.BRICK, 0);
MATERIAL_FLAGS.put(Material.TNT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BOOKSHELF, 0);
MATERIAL_FLAGS.put(Material.MOSSY_COBBLESTONE, 0);
MATERIAL_FLAGS.put(Material.OBSIDIAN, 0);
MATERIAL_FLAGS.put(Material.TORCH, 0);
MATERIAL_FLAGS.put(Material.FIRE, 0);
MATERIAL_FLAGS.put(Material.MOB_SPAWNER, 0);
MATERIAL_FLAGS.put(Material.WOOD_STAIRS, 0);
MATERIAL_FLAGS.put(Material.CHEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REDSTONE_WIRE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_ORE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WORKBENCH, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CROPS, 0);
MATERIAL_FLAGS.put(Material.SOIL, 0);
MATERIAL_FLAGS.put(Material.FURNACE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BURNING_FURNACE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SIGN_POST, 0);
MATERIAL_FLAGS.put(Material.WOODEN_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.LADDER, 0);
MATERIAL_FLAGS.put(Material.RAILS, 0);
MATERIAL_FLAGS.put(Material.COBBLESTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.WALL_SIGN, 0);
MATERIAL_FLAGS.put(Material.LEVER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.STONE_PLATE, 0);
MATERIAL_FLAGS.put(Material.IRON_DOOR_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WOOD_PLATE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_ORE, 0);
MATERIAL_FLAGS.put(Material.GLOWING_REDSTONE_ORE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_TORCH_OFF, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_TORCH_ON, 0);
MATERIAL_FLAGS.put(Material.STONE_BUTTON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SNOW, 0);
MATERIAL_FLAGS.put(Material.ICE, 0);
MATERIAL_FLAGS.put(Material.SNOW_BLOCK, 0);
MATERIAL_FLAGS.put(Material.CACTUS, 0);
MATERIAL_FLAGS.put(Material.CLAY, 0);
MATERIAL_FLAGS.put(Material.SUGAR_CANE_BLOCK, 0);
MATERIAL_FLAGS.put(Material.JUKEBOX, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.FENCE, 0);
MATERIAL_FLAGS.put(Material.PUMPKIN, 0);
MATERIAL_FLAGS.put(Material.NETHERRACK, 0);
MATERIAL_FLAGS.put(Material.SOUL_SAND, 0);
MATERIAL_FLAGS.put(Material.GLOWSTONE, 0);
MATERIAL_FLAGS.put(Material.PORTAL, 0);
MATERIAL_FLAGS.put(Material.JACK_O_LANTERN, 0);
MATERIAL_FLAGS.put(Material.CAKE_BLOCK, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DIODE_BLOCK_OFF, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DIODE_BLOCK_ON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.STAINED_GLASS, 0);
MATERIAL_FLAGS.put(Material.TRAP_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.MONSTER_EGGS, 0);
MATERIAL_FLAGS.put(Material.SMOOTH_BRICK, 0);
MATERIAL_FLAGS.put(Material.HUGE_MUSHROOM_1, 0);
MATERIAL_FLAGS.put(Material.HUGE_MUSHROOM_2, 0);
MATERIAL_FLAGS.put(Material.IRON_FENCE, 0);
MATERIAL_FLAGS.put(Material.THIN_GLASS, 0);
MATERIAL_FLAGS.put(Material.MELON_BLOCK, 0);
MATERIAL_FLAGS.put(Material.PUMPKIN_STEM, 0);
MATERIAL_FLAGS.put(Material.MELON_STEM, 0);
MATERIAL_FLAGS.put(Material.VINE, 0);
MATERIAL_FLAGS.put(Material.FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BRICK_STAIRS, 0);
MATERIAL_FLAGS.put(Material.SMOOTH_STAIRS, 0);
MATERIAL_FLAGS.put(Material.MYCEL, 0);
MATERIAL_FLAGS.put(Material.WATER_LILY, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK, 0);
MATERIAL_FLAGS.put(Material.NETHER_FENCE, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK_STAIRS, 0);
MATERIAL_FLAGS.put(Material.NETHER_WARTS, 0);
MATERIAL_FLAGS.put(Material.ENCHANTMENT_TABLE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BREWING_STAND, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CAULDRON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ENDER_PORTAL, 0);
MATERIAL_FLAGS.put(Material.ENDER_PORTAL_FRAME, 0);
MATERIAL_FLAGS.put(Material.ENDER_STONE, 0);
MATERIAL_FLAGS.put(Material.DRAGON_EGG, MODIFIED_ON_LEFT | MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REDSTONE_LAMP_OFF, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_LAMP_ON, 0);
MATERIAL_FLAGS.put(Material.WOOD_DOUBLE_STEP, 0);
MATERIAL_FLAGS.put(Material.WOOD_STEP, 0);
MATERIAL_FLAGS.put(Material.COCOA, 0);
MATERIAL_FLAGS.put(Material.SANDSTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.EMERALD_ORE, 0);
MATERIAL_FLAGS.put(Material.ENDER_CHEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.TRIPWIRE_HOOK, 0);
MATERIAL_FLAGS.put(Material.TRIPWIRE, 0);
MATERIAL_FLAGS.put(Material.EMERALD_BLOCK, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_WOOD_STAIRS, 0);
MATERIAL_FLAGS.put(Material.BIRCH_WOOD_STAIRS, 0);
MATERIAL_FLAGS.put(Material.JUNGLE_WOOD_STAIRS, 0);
MATERIAL_FLAGS.put(Material.COMMAND, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BEACON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.COBBLE_WALL, 0);
MATERIAL_FLAGS.put(Material.FLOWER_POT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CARROT, 0);
MATERIAL_FLAGS.put(Material.POTATO, 0);
MATERIAL_FLAGS.put(Material.WOOD_BUTTON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SKULL, 0);
MATERIAL_FLAGS.put(Material.ANVIL, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.TRAPPED_CHEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.GOLD_PLATE, 0);
MATERIAL_FLAGS.put(Material.IRON_PLATE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_COMPARATOR_OFF, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REDSTONE_COMPARATOR_ON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DAYLIGHT_DETECTOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REDSTONE_BLOCK, 0);
MATERIAL_FLAGS.put(Material.QUARTZ_ORE, 0);
MATERIAL_FLAGS.put(Material.HOPPER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.QUARTZ_BLOCK, 0);
MATERIAL_FLAGS.put(Material.QUARTZ_STAIRS, 0);
MATERIAL_FLAGS.put(Material.ACTIVATOR_RAIL, 0);
MATERIAL_FLAGS.put(Material.DROPPER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.STAINED_CLAY, 0);
MATERIAL_FLAGS.put(Material.STAINED_GLASS_PANE, 0);
MATERIAL_FLAGS.put(Material.LEAVES_2, 0);
MATERIAL_FLAGS.put(Material.LOG_2, 0);
MATERIAL_FLAGS.put(Material.ACACIA_STAIRS, 0);
MATERIAL_FLAGS.put(Material.DARK_OAK_STAIRS, 0);
MATERIAL_FLAGS.put(Material.HAY_BLOCK, 0);
MATERIAL_FLAGS.put(Material.CARPET, 0);
MATERIAL_FLAGS.put(Material.HARD_CLAY, 0);
MATERIAL_FLAGS.put(Material.COAL_BLOCK, 0);
MATERIAL_FLAGS.put(Material.PACKED_ICE, 0);
MATERIAL_FLAGS.put(Material.DOUBLE_PLANT, 0);
try {
MATERIAL_FLAGS.put(Material.STANDING_BANNER, 0);
MATERIAL_FLAGS.put(Material.WALL_BANNER, 0);
MATERIAL_FLAGS.put(Material.DAYLIGHT_DETECTOR_INVERTED, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE, 0);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.DOUBLE_STONE_SLAB2, 0);
MATERIAL_FLAGS.put(Material.STONE_SLAB2, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ACACIA_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SPRUCE_FENCE, 0);
MATERIAL_FLAGS.put(Material.BIRCH_FENCE, 0);
MATERIAL_FLAGS.put(Material.JUNGLE_FENCE, 0);
MATERIAL_FLAGS.put(Material.DARK_OAK_FENCE, 0);
MATERIAL_FLAGS.put(Material.ACACIA_FENCE, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ACACIA_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_DOOR, MODIFIED_ON_RIGHT);
} catch (NoSuchFieldError ignored) {
}
MATERIAL_FLAGS.put(Material.IRON_SPADE, 0);
MATERIAL_FLAGS.put(Material.IRON_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.IRON_AXE, 0);
MATERIAL_FLAGS.put(Material.FLINT_AND_STEEL, 0);
MATERIAL_FLAGS.put(Material.APPLE, 0);
MATERIAL_FLAGS.put(Material.BOW, 0);
MATERIAL_FLAGS.put(Material.ARROW, 0);
MATERIAL_FLAGS.put(Material.COAL, 0);
MATERIAL_FLAGS.put(Material.DIAMOND, 0);
MATERIAL_FLAGS.put(Material.IRON_INGOT, 0);
MATERIAL_FLAGS.put(Material.GOLD_INGOT, 0);
MATERIAL_FLAGS.put(Material.IRON_SWORD, 0);
MATERIAL_FLAGS.put(Material.WOOD_SWORD, 0);
MATERIAL_FLAGS.put(Material.WOOD_SPADE, 0);
MATERIAL_FLAGS.put(Material.WOOD_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.WOOD_AXE, 0);
MATERIAL_FLAGS.put(Material.STONE_SWORD, 0);
MATERIAL_FLAGS.put(Material.STONE_SPADE, 0);
MATERIAL_FLAGS.put(Material.STONE_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.STONE_AXE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_SWORD, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_SPADE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_AXE, 0);
MATERIAL_FLAGS.put(Material.STICK, 0);
MATERIAL_FLAGS.put(Material.BOWL, 0);
MATERIAL_FLAGS.put(Material.MUSHROOM_SOUP, 0);
MATERIAL_FLAGS.put(Material.GOLD_SWORD, 0);
MATERIAL_FLAGS.put(Material.GOLD_SPADE, 0);
MATERIAL_FLAGS.put(Material.GOLD_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.GOLD_AXE, 0);
MATERIAL_FLAGS.put(Material.STRING, 0);
MATERIAL_FLAGS.put(Material.FEATHER, 0);
MATERIAL_FLAGS.put(Material.SULPHUR, 0);
MATERIAL_FLAGS.put(Material.WOOD_HOE, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.STONE_HOE, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.IRON_HOE, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.DIAMOND_HOE, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.GOLD_HOE, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.SEEDS, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.WHEAT, 0);
MATERIAL_FLAGS.put(Material.BREAD, 0);
MATERIAL_FLAGS.put(Material.LEATHER_HELMET, 0);
MATERIAL_FLAGS.put(Material.LEATHER_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.LEATHER_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.LEATHER_BOOTS, 0);
MATERIAL_FLAGS.put(Material.CHAINMAIL_HELMET, 0);
MATERIAL_FLAGS.put(Material.CHAINMAIL_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.CHAINMAIL_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.CHAINMAIL_BOOTS, 0);
MATERIAL_FLAGS.put(Material.IRON_HELMET, 0);
MATERIAL_FLAGS.put(Material.IRON_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.IRON_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.IRON_BOOTS, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_HELMET, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_BOOTS, 0);
MATERIAL_FLAGS.put(Material.GOLD_HELMET, 0);
MATERIAL_FLAGS.put(Material.GOLD_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.GOLD_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.GOLD_BOOTS, 0);
MATERIAL_FLAGS.put(Material.FLINT, 0);
MATERIAL_FLAGS.put(Material.PORK, 0);
MATERIAL_FLAGS.put(Material.GRILLED_PORK, 0);
MATERIAL_FLAGS.put(Material.PAINTING, 0);
MATERIAL_FLAGS.put(Material.GOLDEN_APPLE, 0);
MATERIAL_FLAGS.put(Material.SIGN, 0);
MATERIAL_FLAGS.put(Material.WOOD_DOOR, 0);
MATERIAL_FLAGS.put(Material.BUCKET, 0);
MATERIAL_FLAGS.put(Material.WATER_BUCKET, 0);
MATERIAL_FLAGS.put(Material.LAVA_BUCKET, 0);
MATERIAL_FLAGS.put(Material.MINECART, 0);
MATERIAL_FLAGS.put(Material.SADDLE, 0);
MATERIAL_FLAGS.put(Material.IRON_DOOR, 0);
MATERIAL_FLAGS.put(Material.REDSTONE, 0);
MATERIAL_FLAGS.put(Material.SNOW_BALL, 0);
MATERIAL_FLAGS.put(Material.BOAT, 0);
MATERIAL_FLAGS.put(Material.LEATHER, 0);
MATERIAL_FLAGS.put(Material.MILK_BUCKET, 0);
MATERIAL_FLAGS.put(Material.CLAY_BRICK, 0);
MATERIAL_FLAGS.put(Material.CLAY_BALL, 0);
MATERIAL_FLAGS.put(Material.SUGAR_CANE, 0);
MATERIAL_FLAGS.put(Material.PAPER, 0);
MATERIAL_FLAGS.put(Material.BOOK, 0);
MATERIAL_FLAGS.put(Material.SLIME_BALL, 0);
MATERIAL_FLAGS.put(Material.STORAGE_MINECART, 0);
MATERIAL_FLAGS.put(Material.POWERED_MINECART, 0);
MATERIAL_FLAGS.put(Material.EGG, 0);
MATERIAL_FLAGS.put(Material.COMPASS, 0);
MATERIAL_FLAGS.put(Material.FISHING_ROD, 0);
MATERIAL_FLAGS.put(Material.WATCH, 0);
MATERIAL_FLAGS.put(Material.GLOWSTONE_DUST, 0);
MATERIAL_FLAGS.put(Material.RAW_FISH, 0);
MATERIAL_FLAGS.put(Material.COOKED_FISH, 0);
MATERIAL_FLAGS.put(Material.INK_SACK, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.BONE, 0);
MATERIAL_FLAGS.put(Material.SUGAR, 0);
MATERIAL_FLAGS.put(Material.CAKE, 0);
MATERIAL_FLAGS.put(Material.BED, 0);
MATERIAL_FLAGS.put(Material.DIODE, 0);
MATERIAL_FLAGS.put(Material.COOKIE, 0);
MATERIAL_FLAGS.put(Material.MAP, 0);
MATERIAL_FLAGS.put(Material.SHEARS, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.MELON, 0);
MATERIAL_FLAGS.put(Material.PUMPKIN_SEEDS, 0);
MATERIAL_FLAGS.put(Material.MELON_SEEDS, 0);
MATERIAL_FLAGS.put(Material.RAW_BEEF, 0);
MATERIAL_FLAGS.put(Material.COOKED_BEEF, 0);
MATERIAL_FLAGS.put(Material.RAW_CHICKEN, 0);
MATERIAL_FLAGS.put(Material.COOKED_CHICKEN, 0);
MATERIAL_FLAGS.put(Material.ROTTEN_FLESH, 0);
MATERIAL_FLAGS.put(Material.ENDER_PEARL, 0);
MATERIAL_FLAGS.put(Material.BLAZE_ROD, 0);
MATERIAL_FLAGS.put(Material.GHAST_TEAR, 0);
MATERIAL_FLAGS.put(Material.GOLD_NUGGET, 0);
MATERIAL_FLAGS.put(Material.NETHER_STALK, 0);
MATERIAL_FLAGS.put(Material.POTION, 0);
MATERIAL_FLAGS.put(Material.GLASS_BOTTLE, 0);
MATERIAL_FLAGS.put(Material.SPIDER_EYE, 0);
MATERIAL_FLAGS.put(Material.FERMENTED_SPIDER_EYE, 0);
MATERIAL_FLAGS.put(Material.BLAZE_POWDER, 0);
MATERIAL_FLAGS.put(Material.MAGMA_CREAM, 0);
MATERIAL_FLAGS.put(Material.BREWING_STAND_ITEM, 0);
MATERIAL_FLAGS.put(Material.CAULDRON_ITEM, 0);
MATERIAL_FLAGS.put(Material.EYE_OF_ENDER, 0);
MATERIAL_FLAGS.put(Material.SPECKLED_MELON, 0);
MATERIAL_FLAGS.put(Material.MONSTER_EGG, MODIFIES_BLOCKS);
MATERIAL_FLAGS.put(Material.EXP_BOTTLE, 0);
MATERIAL_FLAGS.put(Material.FIREBALL, 0);
MATERIAL_FLAGS.put(Material.BOOK_AND_QUILL, 0);
MATERIAL_FLAGS.put(Material.WRITTEN_BOOK, 0);
MATERIAL_FLAGS.put(Material.EMERALD, 0);
MATERIAL_FLAGS.put(Material.ITEM_FRAME, 0);
MATERIAL_FLAGS.put(Material.FLOWER_POT_ITEM, 0);
MATERIAL_FLAGS.put(Material.CARROT_ITEM, 0);
MATERIAL_FLAGS.put(Material.POTATO_ITEM, 0);
MATERIAL_FLAGS.put(Material.BAKED_POTATO, 0);
MATERIAL_FLAGS.put(Material.POISONOUS_POTATO, 0);
MATERIAL_FLAGS.put(Material.EMPTY_MAP, 0);
MATERIAL_FLAGS.put(Material.GOLDEN_CARROT, 0);
MATERIAL_FLAGS.put(Material.SKULL_ITEM, 0);
MATERIAL_FLAGS.put(Material.CARROT_STICK, 0);
MATERIAL_FLAGS.put(Material.NETHER_STAR, 0);
MATERIAL_FLAGS.put(Material.PUMPKIN_PIE, 0);
MATERIAL_FLAGS.put(Material.FIREWORK, 0);
MATERIAL_FLAGS.put(Material.FIREWORK_CHARGE, 0);
MATERIAL_FLAGS.put(Material.ENCHANTED_BOOK, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_COMPARATOR, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK_ITEM, 0);
MATERIAL_FLAGS.put(Material.QUARTZ, 0);
MATERIAL_FLAGS.put(Material.EXPLOSIVE_MINECART, 0);
MATERIAL_FLAGS.put(Material.HOPPER_MINECART, 0);
MATERIAL_FLAGS.put(Material.IRON_BARDING, 0);
MATERIAL_FLAGS.put(Material.GOLD_BARDING, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_BARDING, 0);
MATERIAL_FLAGS.put(Material.LEASH, 0);
MATERIAL_FLAGS.put(Material.NAME_TAG, 0);
MATERIAL_FLAGS.put(Material.COMMAND_MINECART, 0);
try {
MATERIAL_FLAGS.put(Material.PRISMARINE_SHARD, 0);
MATERIAL_FLAGS.put(Material.PRISMARINE_CRYSTALS, 0);
MATERIAL_FLAGS.put(Material.RABBIT, 0);
MATERIAL_FLAGS.put(Material.COOKED_RABBIT, 0);
MATERIAL_FLAGS.put(Material.RABBIT_STEW, 0);
MATERIAL_FLAGS.put(Material.RABBIT_FOOT, 0);
MATERIAL_FLAGS.put(Material.RABBIT_HIDE, 0);
MATERIAL_FLAGS.put(Material.ARMOR_STAND, 0);
MATERIAL_FLAGS.put(Material.IRON_BARDING, 0);
MATERIAL_FLAGS.put(Material.GOLD_BARDING, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_BARDING, 0);;
MATERIAL_FLAGS.put(Material.MUTTON, 0);
MATERIAL_FLAGS.put(Material.COOKED_MUTTON, 0);
MATERIAL_FLAGS.put(Material.BANNER, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_DOOR_ITEM, 0);
MATERIAL_FLAGS.put(Material.BIRCH_DOOR_ITEM, 0);
MATERIAL_FLAGS.put(Material.JUNGLE_DOOR_ITEM, 0);
MATERIAL_FLAGS.put(Material.ACACIA_DOOR_ITEM, 0);
MATERIAL_FLAGS.put(Material.DARK_OAK_DOOR_ITEM, 0);
} catch (NoSuchFieldError ignored) {
}
MATERIAL_FLAGS.put(Material.GOLD_RECORD, 0);
MATERIAL_FLAGS.put(Material.GREEN_RECORD, 0);
MATERIAL_FLAGS.put(Material.RECORD_3, 0);
MATERIAL_FLAGS.put(Material.RECORD_4, 0);
MATERIAL_FLAGS.put(Material.RECORD_5, 0);
MATERIAL_FLAGS.put(Material.RECORD_6, 0);
MATERIAL_FLAGS.put(Material.RECORD_7, 0);
MATERIAL_FLAGS.put(Material.RECORD_8, 0);
MATERIAL_FLAGS.put(Material.RECORD_9, 0);
MATERIAL_FLAGS.put(Material.RECORD_10, 0);
MATERIAL_FLAGS.put(Material.RECORD_11, 0);
MATERIAL_FLAGS.put(Material.RECORD_12, 0);
//DAMAGE_EFFECTS.add(PotionEffectType.ABSORPTION);
DAMAGE_EFFECTS.add(PotionEffectType.BLINDNESS);
DAMAGE_EFFECTS.add(PotionEffectType.CONFUSION);
//DAMAGE_EFFECTS.add(PotionEffectType.DAMAGE_RESISTANCE);
//DAMAGE_EFFECTS.add(PotionEffectType.FAST_DIGGING);
//DAMAGE_EFFECTS.add(PotionEffectType.FIRE_RESISTANCE);
DAMAGE_EFFECTS.add(PotionEffectType.HARM);
//DAMAGE_EFFECTS.add(PotionEffectType.HEAL);
//DAMAGE_EFFECTS.add(PotionEffectType.HEALTH_BOOST);
DAMAGE_EFFECTS.add(PotionEffectType.HUNGER);
//DAMAGE_EFFECTS.add(PotionEffectType.INCREASE_DAMAGE);
//DAMAGE_EFFECTS.add(PotionEffectType.INVISIBILITY);
//DAMAGE_EFFECTS.add(PotionEffectType.JUMP);
//DAMAGE_EFFECTS.add(PotionEffectType.NIGHT_VISION);
DAMAGE_EFFECTS.add(PotionEffectType.POISON);
//DAMAGE_EFFECTS.add(PotionEffectType.REGENERATION);
//DAMAGE_EFFECTS.add(PotionEffectType.SATURATION);
DAMAGE_EFFECTS.add(PotionEffectType.SLOW);
DAMAGE_EFFECTS.add(PotionEffectType.SLOW_DIGGING);
//DAMAGE_EFFECTS.add(PotionEffectType.SPEED);
//DAMAGE_EFFECTS.add(PotionEffectType.WATER_BREATHING);
DAMAGE_EFFECTS.add(PotionEffectType.WEAKNESS);
DAMAGE_EFFECTS.add(PotionEffectType.WITHER);
}
private Materials() {
}
/**
* Get the related material for an entity type.
*
* @param type the entity type
* @return the related material or {@code null} if one is not known or exists
*/
@Nullable
public static Material getRelatedMaterial(EntityType type) {
return ENTITY_ITEMS.get(type);
}
/**
* Get the material of the block placed by the given bucket, defaulting
* to water if the bucket type is not known.
*
* <p>If a non-bucket material is given, it will be assumed to be
* an unknown bucket type. If the given bucket doesn't have a block form
* (it can't be placed), then water will be returned (i.e. for milk).
* Be aware that either the stationary or non-stationary material may be
* returned.</p>
*
* @param type the bucket material
* @return the block material
*/
public static Material getBucketBlockMaterial(Material type) {
switch (type) {
case LAVA_BUCKET:
return Material.LAVA;
case MILK_BUCKET:
return Material.WATER;
default:
return Material.WATER;
}
}
/**
* Test whether the given material is a mushroom.
*
* @param material the material
* @return true if a mushroom block
*/
public static boolean isMushroom(Material material) {
return material == Material.RED_MUSHROOM || material == Material.BROWN_MUSHROOM;
}
/**
* Test whether the given material is a leaf block.
*
* @param material the material
* @return true if a leaf block
*/
public static boolean isLeaf(Material material) {
return material == Material.LEAVES || material == Material.LEAVES_2;
}
/**
* Test whether the given material is a liquid block.
*
* @param material the material
* @return true if a liquid block
*/
public static boolean isLiquid(Material material) {
return isWater(material) || isLava(material);
}
/**
* Test whether the given material is water.
*
* @param material the material
* @return true if a water block
*/
public static boolean isWater(Material material) {
return material == Material.WATER || material == Material.STATIONARY_WATER;
}
/**
* Test whether the given material is lava.
*
* @param material the material
* @return true if a lava block
*/
public static boolean isLava(Material material) {
return material == Material.LAVA || material == Material.STATIONARY_LAVA;
}
/**
* Test whether the given material is a portal material.
*
* @param material the material
* @return true if a portal block
*/
public static boolean isPortal(Material material) {
return material == Material.PORTAL || material == Material.ENDER_PORTAL;
}
/**
* Test whether the given material data is of the given dye color.
*
* <p>Returns false for non-dyed items.</p>
*
* @param data the data
* @return true if it is the provided dye color
*/
public static boolean isDyeColor(MaterialData data, DyeColor color) {
return data instanceof Dye && ((Dye) data).getColor() == color;
}
/**
* Test whether the given material is a rail block.
*
* @param material the material
* @return true if a rail block
*/
public static boolean isRailBlock(Material material) {
return material == Material.RAILS
|| material == Material.ACTIVATOR_RAIL
|| material == Material.DETECTOR_RAIL
|| material == Material.POWERED_RAIL;
}
/**
* Test whether the given material is a piston block, not including
* the "technical blocks" such as the piston extension block.
*
* @param material the material
* @return true if a piston block
*/
public static boolean isPistonBlock(Material material) {
return material == Material.PISTON_BASE
|| material == Material.PISTON_STICKY_BASE;
}
/**
* Test whether the given material is a Minecart.
*
* @param material the material
* @return true if a Minecart item
*/
public static boolean isMinecart(Material material) {
return material == Material.MINECART
|| material == Material.COMMAND_MINECART
|| material == Material.EXPLOSIVE_MINECART
|| material == Material.HOPPER_MINECART
|| material == Material.POWERED_MINECART
|| material == Material.STORAGE_MINECART;
}
/**
* Test whether the given material is an inventory block.
*
* @param material the material
* @return true if an inventory block
*/
public static boolean isInventoryBlock(Material material) {
return material == Material.CHEST
|| material == Material.JUKEBOX
|| material == Material.DISPENSER
|| material == Material.FURNACE
|| material == Material.BURNING_FURNACE
|| material == Material.BREWING_STAND
|| material == Material.TRAPPED_CHEST
|| material == Material.HOPPER
|| material == Material.DROPPER;
}
/**
* Test whether the given material is affected by
* {@link DefaultFlag#USE}.
*
* <p>Generally, materials that are considered by this method are those
* that are not inventories but can be used.</p>
*
* @param material the material
* @return true if covered by the use flag
*/
public static boolean isUseFlagApplicable(Material material) {
switch (material) {
case LEVER: return true;
case STONE_BUTTON: return true;
case WOOD_BUTTON: return true;
case TRIPWIRE: return true;
case WOODEN_DOOR: return true;
case TRAP_DOOR: return true;
case FENCE_GATE: return true;
case WORKBENCH: return true;
case ENCHANTMENT_TABLE: return true;
case ENDER_CHEST: return true;
case BEACON: return true;
case ANVIL: return true;
case WOOD_PLATE: return true;
case STONE_PLATE: return true;
case IRON_PLATE: return true;
case GOLD_PLATE: return true;
case SPRUCE_FENCE_GATE: return true;
case BIRCH_FENCE_GATE: return true;
case JUNGLE_FENCE_GATE: return true;
case DARK_OAK_FENCE_GATE: return true;
case ACACIA_FENCE_GATE: return true;
case SPRUCE_DOOR: return true;
case BIRCH_DOOR: return true;
case JUNGLE_DOOR: return true;
case ACACIA_DOOR: return true;
case DARK_OAK_DOOR: return true;
default: return false;
}
}
/**
* Test whether the given type is Redstone ore.
*
* @param type the material
* @return true if Redstone ore
*/
public static boolean isRedstoneOre(Material type) {
return type == Material.GLOWING_REDSTONE_ORE || type == Material.REDSTONE_ORE;
}
/**
* Test whether the given material is a block that is modified when it is
* left or right clicked.
*
* <p>This test is conservative, returning true for blocks that it is not
* aware of.</p>
*
* @param material the material
* @param rightClick whether it is a right click
* @return true if the block is modified
*/
public static boolean isBlockModifiedOnClick(Material material, boolean rightClick) {
Integer flags = MATERIAL_FLAGS.get(material);
return flags == null
|| (rightClick && (flags & MODIFIED_ON_RIGHT) == MODIFIED_ON_RIGHT)
|| (!rightClick && (flags & MODIFIED_ON_LEFT) == MODIFIED_ON_LEFT);
}
/**
* Test whether the given item modifies a given block when right clicked.
*
* <p>This test is conservative, returning true for items that it is not
* aware of or does not have the details for.</p>
*
* @param item the item
* @param block the block
* @return true if the item is applied to the block
*/
public static boolean isItemAppliedToBlock(Material item, Material block) {
Integer flags = MATERIAL_FLAGS.get(item);
return flags == null || (flags & MODIFIES_BLOCKS) == MODIFIES_BLOCKS;
}
/**
* Test whether the given material should be tested as "building" when
* it is used.
*
* @param type the type
* @return true to be considered as used
*/
public static boolean isConsideredBuildingIfUsed(Material type) {
return type == Material.SAPLING
|| type == Material.DIODE_BLOCK_OFF
|| type == Material.DIODE_BLOCK_ON
|| type == Material.REDSTONE_COMPARATOR_OFF
|| type == Material.REDSTONE_COMPARATOR_ON;
}
/**
* Test whether a list of potion effects contains one or more potion
* effects used for doing damage.
*
* @param effects A collection of effects
* @return True if at least one damage effect exists
*/
public static boolean hasDamageEffect(Collection<PotionEffect> effects) {
for (PotionEffect effect : effects) {
if (DAMAGE_EFFECTS.contains(effect.getType())) {
return true;
}
}
return false;
}
}
@@ -1,159 +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/>.
*/
package com.sk89q.worldguard.chest;
import com.sk89q.worldedit.blocks.BlockID;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
/**
* Sign-based chest protection.
*
* @author sk89q
*/
public class SignChestProtection implements ChestProtection {
public boolean isProtected(Block block, Player player) {
if (isChest(block.getTypeId())) {
Block below = block.getRelative(0, -1, 0);
return isProtectedSignAround(below, player);
} else if (block.getTypeId() == BlockID.SIGN_POST) {
return isProtectedSignAndChestBinary(block, player);
} else {
Block above = block.getRelative(0, 1, 0);
Boolean res = isProtectedSign(above, player);
if (res != null) return res;
return false;
}
}
public boolean isProtectedPlacement(Block block, Player player) {
return isProtectedSignAround(block, player);
}
private boolean isProtectedSignAround(Block searchBlock, Player player) {
Block side;
Boolean res;
side = searchBlock;
res = isProtectedSign(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtectedSignAndChest(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtectedSignAndChest(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtectedSignAndChest(side, player);
if (res != null && res) return res;
return false;
}
private Boolean isProtectedSign(Sign sign, Player player) {
if (sign.getLine(0).equalsIgnoreCase("[Lock]")) {
if (player == null) { // No player, no access
return true;
}
String name = player.getName();
if (name.equalsIgnoreCase(sign.getLine(1).trim())
|| name.equalsIgnoreCase(sign.getLine(2).trim())
|| name.equalsIgnoreCase(sign.getLine(3).trim())) {
return false;
}
// No access!
return true;
}
return null;
}
private Boolean isProtectedSign(Block block, Player player) {
BlockState state = block.getState();
if (state == null || !(state instanceof Sign)) {
return null;
}
return isProtectedSign((Sign) state, player);
}
private Boolean isProtectedSignAndChest(Block block, Player player) {
if (!isChest(block.getRelative(0, 1, 0).getTypeId())) {
return null;
}
return isProtectedSign(block, player);
}
private boolean isProtectedSignAndChestBinary(Block block, Player player) {
Boolean res = isProtectedSignAndChest(block, player);
return !(res == null || !res);
}
public boolean isAdjacentChestProtected(Block searchBlock, Player player) {
Block side;
Boolean res;
side = searchBlock;
res = isProtected(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtected(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtected(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtected(side, player);
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtected(side, player);
if (res != null && res) return res;
return false;
}
@Deprecated
public boolean isChest(Material material) {
return isChest(material.getId());
}
public boolean isChest(int type) {
return type == BlockID.CHEST
|| type == BlockID.DISPENSER
|| type == BlockID.FURNACE
|| type == BlockID.BURNING_FURNACE;
}
}
@@ -1,91 +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/>.
*/
package com.sk89q.worldguard.domains;
import com.sk89q.worldguard.LocalPlayer;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
/**
* @deprecated not used by WorldGuard and not maintained
*/
@Deprecated
public class DomainCollection implements Domain {
private Set<Domain> domains;
public DomainCollection() {
domains = new LinkedHashSet<Domain>();
}
public void add(Domain domain) {
domains.add(domain);
}
public void remove(Domain domain) {
domains.remove(domain);
}
@Override
public int size() {
return domains.size();
}
@Override
public void clear() {
domains.clear();
}
@Override
public boolean contains(LocalPlayer player) {
for (Domain domain : domains) {
if (domain.contains(player)) {
return true;
}
}
return false;
}
@Override
public boolean contains(UUID uniqueId) {
for (Domain domain : domains) {
if (domain.contains(uniqueId)) {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
for (Domain domain : domains) {
if (domain.contains(playerName)) {
return true;
}
}
return false;
}
}
@@ -1,230 +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/>.
*/
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.RegionContainer;
import com.sk89q.worldguard.bukkit.RegionQuery;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* This is the legacy class for accessing region data.
*
* @deprecated use {@link WorldGuardPlugin#getRegionContainer()}
*/
@Deprecated
public class GlobalRegionManager {
private final WorldGuardPlugin plugin;
private final RegionContainer container;
/**
* Create a new instance.
*
* @param plugin the plugin
* @param container the container
*/
public GlobalRegionManager(WorldGuardPlugin plugin, RegionContainer container) {
checkNotNull(plugin);
checkNotNull(container);
this.plugin = plugin;
this.container = container;
}
/**
* Get the region manager for a world if one exists.
*
* <p>This method may return {@code null} if region data for the given
* world has not been loaded, has failed to load, or support for regions
* has been disabled.</p>
*
* @param world the world
* @return a region manager, or {@code null} if one is not available
*/
@Nullable
public RegionManager get(World world) {
return container.get(world);
}
/**
* Get an immutable list of loaded {@link RegionManager}s.
*
* @return a list of managers
*/
public List<RegionManager> getLoaded() {
return Collections.unmodifiableList(container.getLoaded());
}
/**
* Create a new region query.
*
* @return a new query
*/
private RegionQuery createQuery() {
return container.createQuery();
}
/**
* Test whether the given player has region protection bypass permission.
*
* @param player the player
* @param world the world
* @return true if a bypass is permitted
* @deprecated use {@link RegionContainer#createQuery()}
*/
@Deprecated
public boolean hasBypass(LocalPlayer player, World world) {
return player.hasPermission("worldguard.region.bypass." + world.getName());
}
/**
* Test whether the given player has region protection bypass permission.
*
* @param player the player
* @param world the world
* @return true if a bypass is permitted
* @deprecated use {@link RegionContainer#createQuery()}
*/
@Deprecated
public boolean hasBypass(Player player, World world) {
return plugin.hasPermission(player, "worldguard.region.bypass." + world.getName());
}
/**
* Test whether the player can build (place, use, destroy blocks and
* entities) at the given position, considering only the build flag
* and the region's members.
*
* <p>This method is not an absolute test as to whether WorldGuard
* would allow or block an event because this method doesn't
* consider flags (i.e. chest-access flags when concerning a chest) or
* other modules in WorldGuard (i.e chest protection).</p>
*
* @param player the player
* @param block the block
* @return true if a bypass is permitted
* @deprecated use {@link RegionContainer#createQuery()}
*/
@SuppressWarnings("deprecation")
@Deprecated
public boolean canBuild(Player player, Block block) {
return canBuild(player, block.getLocation());
}
/**
* Test whether the player can build (place, use, destroy blocks and
* entities) at the given position, considering only the build flag
* and the region's members.
*
* <p>This method is not an absolute test as to whether WorldGuard
* would allow or block an event because this method doesn't
* consider flags (i.e. chest-access flags when concerning a chest) or
* other modules in WorldGuard (i.e chest protection).</p>
*
* @param player the player
* @param location the location
* @return true if a bypass is permitted
* @deprecated use {@link RegionContainer#createQuery()}
*/
@Deprecated
public boolean canBuild(Player player, Location location) {
return hasBypass(player, location.getWorld()) || createQuery().testState(location, player, DefaultFlag.BUILD);
}
/**
* Test whether the player can place blocks at the given position.
*
* @param player the player
* @param block the block
* @return true if permitted
* @deprecated the construct flag is being removed
*/
@Deprecated
@SuppressWarnings("deprecation")
public boolean canConstruct(Player player, Block block) {
return canBuild(player, block.getLocation());
}
/**
* Test whether the player can place blocks at the given position.
*
* @param player the player
* @param location the location
* @return true if permitted
* @deprecated the construct flag is being removed
*/
@Deprecated
public boolean canConstruct(Player player, Location location) {
return canBuild(player, location);
}
/**
* Test the value of a state flag at a location.
*
* @param flag the flag
* @param location the location
* @return true if set to true
* @deprecated use {@link RegionContainer#createQuery()}
*/
@Deprecated
@SuppressWarnings("deprecation")
public boolean allows(StateFlag flag, Location location) {
return allows(flag, location, null);
}
/**
* Test the value of a state flag at a location, using the player as the
* relevant actor.
*
* @param flag the flag
* @param location the location
* @param player the actor
* @return true if set to true
* @deprecated use {@link RegionContainer#createQuery()}
*/
@Deprecated
public boolean allows(StateFlag flag, Location location, @Nullable LocalPlayer player) {
if (player == null) {
return StateFlag.test(createQuery().queryState(location, (RegionAssociable) null, flag));
} else if (player instanceof BukkitPlayer) {
Player p = ((BukkitPlayer) player).getPlayer();
return StateFlag.test(createQuery().queryState(location, p, flag));
} else {
throw new IllegalArgumentException("Can't take a non-Bukkit player");
}
}
}
@@ -1,182 +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/>.
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.EntityType;
/**
* The flags that are used in WorldGuard.
*/
public final class DefaultFlag {
// Overrides membership check
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", false);
/**
* @deprecated This flag is being removed because group flags can now be
* set on all flags.
*/
@Deprecated
public static final RegionGroupFlag CONSTRUCT = new RegionGroupFlag("construct", RegionGroup.MEMBERS);
// This flag is unlike the others. It forces the checking of region membership
public static final StateFlag BUILD = new BuildFlag("build", true);
// These flags are used in tandem with the BUILD flag - if the player can
// build, then the following flags do not need to be checked (although they
// are still checked for DENY), so they are false by default
public static final StateFlag BLOCK_BREAK = new StateFlag("block-break", false);
public static final StateFlag BLOCK_PLACE = new StateFlag("block-place", false);
public static final StateFlag USE = new StateFlag("use", false);
public static final StateFlag INTERACT = new StateFlag("interact", false);
public static final StateFlag DAMAGE_ANIMALS = new StateFlag("damage-animals", false);
public static final StateFlag PVP = new StateFlag("pvp", false);
public static final StateFlag SLEEP = new StateFlag("sleep", false);
public static final StateFlag TNT = new StateFlag("tnt", false);
public static final StateFlag CHEST_ACCESS = new StateFlag("chest-access", false);
public static final StateFlag PLACE_VEHICLE = new StateFlag("vehicle-place", false);
public static final StateFlag DESTROY_VEHICLE = new StateFlag("vehicle-destroy", false);
public static final StateFlag LIGHTER = new StateFlag("lighter", false);
public static final StateFlag RIDE = new StateFlag("ride", false);
public static final StateFlag POTION_SPLASH = new StateFlag("potion-splash", false);
// These flags are similar to the ones above (used in tandem with BUILD),
// but their defaults are set to TRUE because it is more user friendly.
// However, it is not possible to disable these flags by default in all
// regions because setting DENY in __global__ would also override the
// BUILD flag. In the future, StateFlags will need a DISALLOW state.
public static final StateFlag ITEM_PICKUP = new StateFlag("item-pickup", true); // Intentionally true
public static final StateFlag ITEM_DROP = new StateFlag("item-drop", true); // Intentionally true
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", true); // Intentionally true
// These flags adjust behavior and are not checked in tandem with the
// BUILD flag so they need to be TRUE for their defaults.
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", true);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", true);
public static final StateFlag ENDERDRAGON_BLOCK_DAMAGE = new StateFlag("enderdragon-block-damage", true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true);
public static final StateFlag OTHER_EXPLOSION = new StateFlag("other-explosion", true);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", true);
public static final StateFlag LIGHTNING = new StateFlag("lightning", true);
public static final StateFlag WATER_FLOW = new StateFlag("water-flow", true);
public static final StateFlag LAVA_FLOW = new StateFlag("lava-flow", true);
public static final StateFlag PISTONS = new StateFlag("pistons", true);
public static final StateFlag SNOW_FALL = new StateFlag("snow-fall", true);
public static final StateFlag SNOW_MELT = new StateFlag("snow-melt", true);
public static final StateFlag ICE_FORM = new StateFlag("ice-form", true);
public static final StateFlag ICE_MELT = new StateFlag("ice-melt", true);
public static final StateFlag MUSHROOMS = new StateFlag("mushroom-growth", true);
public static final StateFlag LEAF_DECAY = new StateFlag("leaf-decay", true);
public static final StateFlag GRASS_SPREAD = new StateFlag("grass-growth", true);
public static final StateFlag MYCELIUM_SPREAD = new StateFlag("mycelium-spread", true);
public static final StateFlag VINE_GROWTH = new StateFlag("vine-growth", true);
public static final StateFlag SOIL_DRY = new StateFlag("soil-dry", true);
public static final StateFlag ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false);
public static final StateFlag SEND_CHAT = new StateFlag("send-chat", true);
public static final StateFlag RECEIVE_CHAT = new StateFlag("receive-chat", true);
public static final StateFlag ENTRY = new StateFlag("entry", true, RegionGroup.NON_MEMBERS);
public static final StateFlag EXIT = new StateFlag("exit", true, RegionGroup.NON_MEMBERS);
public static final StateFlag ENDERPEARL = new StateFlag("enderpearl", true);
public static final StateFlag ENTITY_PAINTING_DESTROY = new StateFlag("entity-painting-destroy", true);
public static final StateFlag ENTITY_ITEM_FRAME_DESTROY = new StateFlag("entity-item-frame-destroy", true);
public static final StateFlag FALL_DAMAGE = new StateFlag("fall-damage", true);
// Flags that adjust behaviors that aren't state flags
public static final StringFlag DENY_MESSAGE = new StringFlag("deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " Sorry, but you can't %what% here.");
public static final StringFlag ENTRY_DENY_MESSAGE = new StringFlag("entry-deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " You are not permitted to enter this area.");
public static final StringFlag EXIT_DENY_MESSAGE = new StringFlag("exit-deny-message",
"" + ChatColor.RED + ChatColor.BOLD + "Hey!" + ChatColor.GRAY + " You are not permitted to leave this area.");
public static final BooleanFlag EXIT_OVERRIDE = new BooleanFlag("exit-override");
public static final StateFlag EXIT_VIA_TELEPORT = new StateFlag("exit-via-teleport", true);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter");
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave");
public static final SetFlag<EntityType> DENY_SPAWN = new SetFlag<EntityType>("deny-spawn", new EntityTypeFlag(null));
public static final EnumFlag<GameMode> GAME_MODE = new EnumFlag<GameMode>("game-mode", GameMode.class);
public static final StringFlag TIME_LOCK = new StringFlag("time-lock");
public static final EnumFlag<WeatherType> WEATHER_LOCK = new EnumFlag<WeatherType>("weather-lock", WeatherType.class);
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final DoubleFlag MIN_HEAL = new DoubleFlag("heal-min-health");
public static final DoubleFlag MAX_HEAL = new DoubleFlag("heal-max-health");
public static final IntegerFlag FEED_DELAY = new IntegerFlag("feed-delay");
public static final IntegerFlag FEED_AMOUNT = new IntegerFlag("feed-amount");
public static final IntegerFlag MIN_FOOD = new IntegerFlag("feed-min-hunger");
public static final IntegerFlag MAX_FOOD = new IntegerFlag("feed-max-hunger");
// public static final IntegerFlag MAX_PLAYERS = new IntegerFlag("max-players-allowed");
// public static final StringFlag MAX_PLAYERS_MESSAGE = new StringFlag("max-players-reject-message");
public static final LocationFlag TELE_LOC = new LocationFlag("teleport", RegionGroup.MEMBERS);
public static final LocationFlag SPAWN_LOC = new LocationFlag("spawn", RegionGroup.MEMBERS);
public static final StateFlag ENABLE_SHOP = new StateFlag("allow-shop", false);
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", new CommandStringFlag(null));
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, CONSTRUCT, BLOCK_BREAK, BLOCK_PLACE, PVP, CHEST_ACCESS, PISTONS,
TNT, LIGHTER, RIDE, USE, INTERACT, PLACE_VEHICLE, DESTROY_VEHICLE, DAMAGE_ANIMALS, SLEEP,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY, EXP_DROPS,
CREEPER_EXPLOSION, OTHER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
DENY_MESSAGE, ENTRY_DENY_MESSAGE, EXIT_DENY_MESSAGE, EXIT_OVERRIDE, EXIT_VIA_TELEPORT,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY, ENDERPEARL,
ENTITY_ITEM_FRAME_DESTROY, FALL_DAMAGE, ITEM_PICKUP, ITEM_DROP, /*MAX_PLAYERS, MAX_PLAYERS_MESSAGE,*/
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, SOIL_DRY, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, MYCELIUM_SPREAD, VINE_GROWTH,
SEND_CHAT, RECEIVE_CHAT, FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, SPAWN_LOC, POTION_SPLASH, TIME_LOCK, WEATHER_LOCK,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE, ENABLE_SHOP
};
private DefaultFlag() {
}
public static Flag<?>[] getFlags() {
return flagsList;
}
/**
* Try to match the flag with the given ID using a fuzzy name match.
*
* @param id the flag ID
* @return a flag, or null
*/
public static Flag<?> fuzzyMatchFlag(String id) {
for (Flag<?> flag : DefaultFlag.getFlags()) {
if (flag.getName().replace("-", "").equalsIgnoreCase(id.replace("-", ""))) {
return flag;
}
}
return null;
}
}
@@ -1,53 +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/>.
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.entity.EntityType;
/**
* Stores an entity type.
*/
public class EntityTypeFlag extends EnumFlag<EntityType> {
public EntityTypeFlag(String name, RegionGroup defaultGroup) {
super(name, EntityType.class, defaultGroup);
}
public EntityTypeFlag(String name) {
super(name, EntityType.class);
}
@Override
public EntityType detectValue(String input) {
EntityType lowMatch = null;
for (EntityType type : EntityType.values()) {
if (type.name().equalsIgnoreCase(input.trim())) {
return type;
}
if (type.name().toLowerCase().startsWith(input.toLowerCase().trim())) {
lowMatch = type;
}
}
return lowMatch;
}
}
@@ -1,72 +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/>.
*/
package com.sk89q.worldguard.protection.flags;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import org.bukkit.Bukkit;
import javax.annotation.Nullable;
/**
* A location that stores the name of the world in case the world is unloaded.
*/
class LazyLocation extends Location {
private final String worldName;
@Nullable
private static LocalWorld findWorld(String worldName) {
return BukkitUtil.getLocalWorld(Bukkit.getServer().getWorld(worldName));
}
public LazyLocation(String worldName, Vector position, float yaw, float pitch) {
super(findWorld(worldName), position, yaw, pitch);
this.worldName = worldName;
}
public LazyLocation(String worldName, Vector position) {
super(findWorld(worldName), position);
this.worldName = worldName;
}
public String getWorldName() {
return worldName;
}
public LazyLocation setAngles(float yaw, float pitch) {
return new LazyLocation(worldName, getPosition(), yaw, pitch);
}
public LazyLocation setPosition(Vector position) {
return new LazyLocation(worldName, position, getYaw(), getPitch());
}
public LazyLocation add(Vector other) {
return this.setPosition(getPosition().add(other));
}
public LazyLocation add(double x, double y, double z) {
return this.setPosition(getPosition().add(x, y, z));
}
}
@@ -1,221 +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/>.
*/
package com.sk89q.worldguard.session;
import com.sk89q.guavabackport.cache.CacheBuilder;
import com.sk89q.guavabackport.cache.CacheLoader;
import com.sk89q.guavabackport.cache.LoadingCache;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.session.handler.*;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Keeps tracks of sessions and also does session-related handling
* (flags, etc.).
*/
public class SessionManager implements Runnable, Listener {
public static final int RUN_DELAY = 20;
public static final long SESSION_LIFETIME = 10;
private final WorldGuardPlugin plugin;
private final LoadingCache<WorldPlayerTuple, Boolean> bypassCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(2, TimeUnit.SECONDS)
.build(new CacheLoader<WorldPlayerTuple, Boolean>() {
@Override
public Boolean load(WorldPlayerTuple tuple) throws Exception {
return plugin.getGlobalRegionManager().hasBypass(tuple.player, tuple.world);
}
});
private final LoadingCache<CacheKey, Session> sessions = CacheBuilder.newBuilder()
.expireAfterAccess(SESSION_LIFETIME, TimeUnit.MINUTES)
.build(new CacheLoader<CacheKey, Session>() {
@Override
public Session load(CacheKey key) throws Exception {
return createSession(key.playerRef.get());
}
});
/**
* Create a new instance.
*
* @param plugin The plugin
*/
public SessionManager(WorldGuardPlugin plugin) {
checkNotNull(plugin, "plugin");
this.plugin = plugin;
}
/**
* Get the plugin.
*
* @return The plugin
*/
public WorldGuardPlugin getPlugin() {
return plugin;
}
/**
* Check whether a player has the region bypass permission.
*
* <p>The return value may be cached for a few seconds.</p>
*
* @param player The player
* @param world The world
* @return A value
*/
public boolean hasBypass(Player player, World world) {
return bypassCache.getUnchecked(new WorldPlayerTuple(world, player));
}
/**
* Re-initialize handlers and clear "last position," "last state," etc.
* information for all players.
*/
public void resetAllStates() {
Collection<? extends Player> players = BukkitUtil.getOnlinePlayers();
for (Player player : players) {
Session session = sessions.getIfPresent(new CacheKey(player));
if (session != null) {
session.resetState(player);
}
}
}
/**
* Re-initialize handlers and clear "last position," "last state," etc.
* information.
*
* @param player The player
*/
public void resetState(Player player) {
checkNotNull(player, "player");
@Nullable Session session = sessions.getIfPresent(new CacheKey(player));
if (session != null) {
session.resetState(player);
}
}
/**
* Create a session for a player.
*
* @param player The player
* @return The new session
*/
private Session createSession(Player player) {
Session session = new Session(this);
session.register(new HealFlag(session));
session.register(new FeedFlag(session));
session.register(new NotifyEntryFlag(session));
session.register(new NotifyExitFlag(session));
session.register(new EntryFlag(session));
session.register(new ExitFlag(session));
session.register(new GreetingFlag(session));
session.register(new FarewellFlag(session));
session.register(new GameModeFlag(session));
session.register(new InvincibilityFlag(session));
session.register(new TimeLockFlag(session));
session.register(new WeatherLockFlag(session));
session.register(new GodMode(session));
session.register(new WaterBreathing(session));
session.initialize(player);
return session;
}
/**
* Get a player's session, if one exists.
*
* @param player The player
* @return The session
*/
@Nullable
public Session getIfPresent(Player player) {
return sessions.getIfPresent(player);
}
/**
* Get a player's session. A session will be created if there is no
* existing session for the player.
*
* <p>This method can only be called from the main thread. While the
* session manager itself is thread-safe, some of the handlers may
* require initialization that requires the server main thread.</p>
*
* @param player The player to get a session for
* @return The {@code player}'s session
*/
public Session get(Player player) {
return sessions.getUnchecked(new CacheKey(player));
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
// Pre-load a session
get(event.getPlayer());
}
@Override
public void run() {
for (Player player : BukkitUtil.getOnlinePlayers()) {
get(player).tick(player);
}
}
private static final class CacheKey {
private final WeakReference<Player> playerRef;
private final UUID uuid;
private CacheKey(Player player) {
playerRef = new WeakReference<Player>(player);
uuid = player.getUniqueId();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
return uuid.equals(cacheKey.uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
}
}
@@ -1,81 +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/>.
*/
package com.sk89q.worldguard.session.handler;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.bukkit.commands.CommandUtils;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.Set;
public class FarewellFlag extends Handler {
private Set<String> lastMessageStack = Collections.emptySet();
public FarewellFlag(Session session) {
super(session);
}
private Set<String> getMessages(Player player, ApplicableRegionSet set) {
return Sets.newLinkedHashSet(set.queryAllValues(getPlugin().wrapPlayer(player), DefaultFlag.FAREWELL_MESSAGE));
}
@Override
public void initialize(Player player, Location current, ApplicableRegionSet set) {
lastMessageStack = getMessages(player, set);
}
@Override
public boolean onCrossBoundary(Player player, Location from, Location to, ApplicableRegionSet toSet, Set<ProtectedRegion> entered, Set<ProtectedRegion> exited, MoveType moveType) {
Set<String> messages = getMessages(player, toSet);
if (!messages.isEmpty()) {
// Due to flag priorities, we have to collect the lower
// priority flag values separately
for (ProtectedRegion region : toSet) {
String message = region.getFlag(DefaultFlag.FAREWELL_MESSAGE);
if (message != null) {
messages.add(message);
}
}
}
for (String message : lastMessageStack) {
if (!messages.contains(message)) {
String effective = CommandUtils.replaceColorMacros(message);
effective = getPlugin().replaceMacros(player, effective);
player.sendMessage(effective.replaceAll("\\\\n", "\n").split("\\n"));
break;
}
}
lastMessageStack = messages;
return true;
}
}
@@ -1,72 +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/>.
*/
package com.sk89q.worldguard.session.handler;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.bukkit.commands.CommandUtils;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
public class GreetingFlag extends Handler {
private Set<String> lastMessageStack = Collections.emptySet();
public GreetingFlag(Session session) {
super(session);
}
@Override
public boolean onCrossBoundary(Player player, Location from, Location to, ApplicableRegionSet toSet, Set<ProtectedRegion> entered, Set<ProtectedRegion> exited, MoveType moveType) {
Collection<String> messages = toSet.queryAllValues(getPlugin().wrapPlayer(player), DefaultFlag.GREET_MESSAGE);
for (String message : messages) {
if (!lastMessageStack.contains(message)) {
String effective = CommandUtils.replaceColorMacros(message);
effective = getPlugin().replaceMacros(player, effective);
player.sendMessage(effective.replaceAll("\\\\n", "\n").split("\\n"));
break;
}
}
lastMessageStack = Sets.newHashSet(messages);
if (!lastMessageStack.isEmpty()) {
// Due to flag priorities, we have to collect the lower
// priority flag values separately
for (ProtectedRegion region : toSet) {
String message = region.getFlag(DefaultFlag.GREET_MESSAGE);
if (message != null) {
lastMessageStack.add(message);
}
}
}
return true;
}
}
@@ -1,124 +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/>.
*/
package com.sk89q.worldguard.util.logging;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.security.CodeSource;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Validates that certain specified classes came from the same source as
* a plugin.
*/
public class ClassSourceValidator {
private static final Logger log = Logger.getLogger(ClassSourceValidator.class.getCanonicalName());
private static final String separatorLine = Strings.repeat("*", 46);
private final Plugin plugin;
@Nullable
private final CodeSource expectedCodeSource;
/**
* Create a new instance.
*
* @param plugin The plugin
*/
public ClassSourceValidator(Plugin plugin) {
checkNotNull(plugin, "plugin");
this.plugin = plugin;
this.expectedCodeSource = plugin.getClass().getProtectionDomain().getCodeSource();
}
/**
* Return a map of classes that been loaded from a different source.
*
* @param classes A list of classes to check
* @return The results
*/
public Map<Class<?>, CodeSource> findMismatches(List<Class<?>> classes) {
checkNotNull(classes, "classes");
Map<Class<?>, CodeSource> mismatches = Maps.newHashMap();
if (expectedCodeSource != null) {
for (Class<?> testClass : classes) {
CodeSource testSource = testClass.getProtectionDomain().getCodeSource();
if (!expectedCodeSource.equals(testSource)) {
mismatches.put(testClass, testSource);
}
}
}
return mismatches;
}
/**
* Reports classes that have come from a different source.
*
* <p>The warning is emitted to the log.</p>
*
* @param classes The list of classes to check
*/
public void reportMismatches(List<Class<?>> classes) {
Map<Class<?>, CodeSource> mismatches = findMismatches(classes);
if (!mismatches.isEmpty()) {
StringBuilder builder = new StringBuilder("\n");
builder.append(separatorLine).append("\n");
builder.append("** /!\\ SEVERE WARNING /!\\\n");
builder.append("** \n");
builder.append("** A plugin developer has copied and pasted a portion of \n");
builder.append("** ").append(plugin.getName()).append(" into their own plugin, so rather than using\n");
builder.append("** the version of ").append(plugin.getName()).append(" that you downloaded, you\n");
builder.append("** will be using a broken mix of old ").append(plugin.getName()).append(" (that came\n");
builder.append("** with the plugin) and your downloaded version. THIS MAY\n");
builder.append("** SEVERELY BREAK ").append(plugin.getName().toUpperCase()).append(" AND ALL OF ITS FEATURES.\n");
builder.append("**\n");
builder.append("** This may have happened because the developer is using\n");
builder.append("** the ").append(plugin.getName()).append(" API and thinks that including\n");
builder.append("** ").append(plugin.getName()).append(" is necessary. However, it is not!\n");
builder.append("**\n");
builder.append("** Here are some files that have been overridden:\n");
builder.append("** \n");
for (Map.Entry<Class<?>, CodeSource> entry : mismatches.entrySet()) {
CodeSource codeSource = entry.getValue();
String url = codeSource != null ? codeSource.getLocation().toExternalForm() : "(unknown)";
builder.append("** '").append(entry.getKey().getSimpleName()).append("' came from '").append(url).append("'\n");
}
builder.append("**\n");
builder.append("** Please report this to the plugins' developers.\n");
builder.append(separatorLine).append("\n");
log.log(Level.SEVERE, builder.toString());
}
}
}
@@ -1,496 +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/>.
*/
package com.sk89q.worldguard.util.net;
import com.sk89q.worldguard.util.io.Closer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpRequest implements Closeable {
private static final int CONNECT_TIMEOUT = 1000 * 5;
private static final int READ_TIMEOUT = 1000 * 5;
private static final int READ_BUFFER_SIZE = 1024 * 8;
private final Map<String, String> headers = new HashMap<String, String>();
private final String method;
private final URL url;
private String contentType;
private byte[] body;
private HttpURLConnection conn;
private InputStream inputStream;
private long contentLength = -1;
private long readBytes = 0;
/**
* Create a new HTTP request.
*
* @param method the method
* @param url the URL
*/
private HttpRequest(String method, URL url) {
this.method = method;
this.url = url;
}
/**
* Submit data.
*
* @return this object
*/
public HttpRequest body(String data) {
body = data.getBytes();
return this;
}
/**
* Submit form data.
*
* @param form the form
* @return this object
*/
public HttpRequest bodyForm(Form form) {
contentType = "application/x-www-form-urlencoded";
body = form.toString().getBytes();
return this;
}
/**
* Add a header.
*
* @param key the header key
* @param value the header value
* @return this object
*/
public HttpRequest header(String key, String value) {
if (key.equalsIgnoreCase("Content-Type")) {
contentType = value;
} else {
headers.put(key, value);
}
return this;
}
/**
* Execute the request.
* <p/>
* After execution, {@link #close()} should be called.
*
* @return this object
* @throws java.io.IOException on I/O error
*/
public HttpRequest execute() throws IOException {
boolean successful = false;
try {
if (conn != null) {
throw new IllegalArgumentException("Connection already executed");
}
conn = (HttpURLConnection) reformat(url).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java)");
if (body != null) {
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Content-Length", Integer.toString(body.length));
conn.setDoInput(true);
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.setRequestMethod(method);
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
conn.connect();
if (body != null) {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(body);
out.flush();
out.close();
}
inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ?
conn.getInputStream() : conn.getErrorStream();
successful = true;
} finally {
if (!successful) {
close();
}
}
return this;
}
/**
* Require that the response code is one of the given response codes.
*
* @param codes a list of codes
* @return this object
* @throws java.io.IOException if there is an I/O error or the response code is not expected
*/
public HttpRequest expectResponseCode(int... codes) throws IOException {
int responseCode = getResponseCode();
for (int code : codes) {
if (code == responseCode) {
return this;
}
}
close();
throw new IOException("Did not get expected response code, got " + responseCode + " for " + url);
}
/**
* Get the response code.
*
* @return the response code
* @throws java.io.IOException on I/O error
*/
public int getResponseCode() throws IOException {
if (conn == null) {
throw new IllegalArgumentException("No connection has been made");
}
return conn.getResponseCode();
}
/**
* Get the input stream.
*
* @return the input stream
*/
public InputStream getInputStream() {
return inputStream;
}
/**
* Buffer the returned response.
*
* @return the buffered response
* @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/
public BufferedResponse returnContent() throws IOException, InterruptedException {
if (inputStream == null) {
throw new IllegalArgumentException("No input stream available");
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b = 0;
while ((b = inputStream.read()) != -1) {
bos.write(b);
}
return new BufferedResponse(bos.toByteArray());
} finally {
close();
}
}
/**
* Save the result to a file.
*
* @param file the file
* @return this object
* @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/
public HttpRequest saveContent(File file) throws IOException, InterruptedException {
Closer closer = Closer.create();
try {
FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
saveContent(bos);
} finally {
closer.close();
}
return this;
}
/**
* Save the result to an output stream.
*
* @param out the output stream
* @return this object
* @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/
public HttpRequest saveContent(OutputStream out) throws IOException, InterruptedException {
BufferedInputStream bis;
try {
String field = conn.getHeaderField("Content-Length");
if (field != null) {
long len = Long.parseLong(field);
if (len >= 0) { // Let's just not deal with really big numbers
contentLength = len;
}
}
} catch (NumberFormatException ignored) {
}
try {
bis = new BufferedInputStream(inputStream);
byte[] data = new byte[READ_BUFFER_SIZE];
int len = 0;
while ((len = bis.read(data, 0, READ_BUFFER_SIZE)) >= 0) {
out.write(data, 0, len);
readBytes += len;
}
} finally {
close();
}
return this;
}
@Override
public void close() throws IOException {
if (conn != null) conn.disconnect();
}
/**
* Perform a GET request.
*
* @param url the URL
* @return a new request object
*/
public static HttpRequest get(URL url) {
return request("GET", url);
}
/**
* Perform a POST request.
*
* @param url the URL
* @return a new request object
*/
public static HttpRequest post(URL url) {
return request("POST", url);
}
/**
* Perform a request.
*
* @param method the method
* @param url the URL
* @return a new request object
*/
public static HttpRequest request(String method, URL url) {
return new HttpRequest(method, url);
}
/**
* Create a new {@link java.net.URL} and throw a {@link RuntimeException} if the URL
* is not valid.
*
* @param url the url
* @return a URL object
* @throws RuntimeException if the URL is invalid
*/
public static URL url(String url) {
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
/**
* URL may contain spaces and other nasties that will cause a failure.
*
* @param existing the existing URL to transform
* @return the new URL, or old one if there was a failure
*/
private static URL reformat(URL existing) {
try {
URL url = new URL(existing.toString());
URI uri = new URI(
url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
return url;
} catch (MalformedURLException e) {
return existing;
} catch (URISyntaxException e) {
return existing;
}
}
/**
* Used with {@link #bodyForm(Form)}.
*/
public final static class Form {
public final List<String> elements = new ArrayList<String>();
private Form() {
}
/**
* Add a key/value to the form.
*
* @param key the key
* @param value the value
* @return this object
*/
public Form add(String key, String value) {
try {
elements.add(URLEncoder.encode(key, "UTF-8") +
"=" + URLEncoder.encode(value, "UTF-8"));
return this;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String element : elements) {
if (first) {
first = false;
} else {
builder.append("&");
}
builder.append(element);
}
return builder.toString();
}
/**
* Create a new form.
*
* @return a new form
*/
public static Form create() {
return new Form();
}
}
/**
* Used to buffer the response in memory.
*/
public class BufferedResponse {
private final byte[] data;
private BufferedResponse(byte[] data) {
this.data = data;
}
/**
* Return the result as bytes.
*
* @return the data
*/
public byte[] asBytes() {
return data;
}
/**
* Return the result as a string.
*
* @param encoding the encoding
* @return the string
* @throws java.io.IOException on I/O error
*/
public String asString(String encoding) throws IOException {
return new String(data, encoding);
}
/**
* Return the result as an instance of the given class that has been
* deserialized from a XML payload.
*
* @return the object
* @throws java.io.IOException on I/O error
*/
@SuppressWarnings("unchecked")
public <T> T asXml(Class<T> cls) throws IOException {
try {
JAXBContext context = JAXBContext.newInstance(cls);
Unmarshaller um = context.createUnmarshaller();
return (T) um.unmarshal(new ByteArrayInputStream(data));
} catch (JAXBException e) {
throw new IOException(e);
}
}
/**
* Save the result to a file.
*
* @param file the file
* @return this object
* @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/
public BufferedResponse saveContent(File file) throws IOException, InterruptedException {
Closer closer = Closer.create();
file.getParentFile().mkdirs();
try {
FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
saveContent(bos);
} finally {
closer.close();
}
return this;
}
/**
* Save the result to an output stream.
*
* @param out the output stream
* @return this object
* @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/
public BufferedResponse saveContent(OutputStream out) throws IOException, InterruptedException {
out.write(data);
return this;
}
}
}
@@ -1,79 +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/>.
*/
package com.sk89q.worldguard.util.paste;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.net.HttpRequest;
import com.sk89q.worldguard.util.net.HttpRequest.Form;
import org.json.simple.JSONValue;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EngineHubPaste implements Paster {
private static final Pattern URL_PATTERN = Pattern.compile("https?://.+$");
@Override
public ListenableFuture<URL> paste(String content) {
return Pasters.getExecutor().submit(new PasteTask(content));
}
private final class PasteTask implements Callable<URL> {
private final String content;
private PasteTask(String content) {
this.content = content;
}
@Override
public URL call() throws IOException, InterruptedException {
Form form = Form.create();
form.add("content", content);
form.add("from", "worldguard");
URL url = HttpRequest.url("http://paste.enginehub.org/paste");
String result = HttpRequest.post(url)
.bodyForm(form)
.execute()
.expectResponseCode(200)
.returnContent()
.asString("UTF-8").trim();
Object object = JSONValue.parse(result);
if (object instanceof Map) {
@SuppressWarnings("unchecked")
String urlString = String.valueOf(((Map<Object, Object>) object).get("url"));
Matcher m = URL_PATTERN.matcher(urlString);
if (m.matches()) {
return new URL(urlString);
}
}
throw new IOException("Failed to save paste; instead, got: " + result);
}
}
}
@@ -1,96 +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/>.
*/
package com.sk89q.worldguard.util.paste;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.net.HttpRequest;
import com.sk89q.worldguard.util.net.HttpRequest.Form;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pastebin implements Paster {
private static final Pattern URL_PATTERN = Pattern.compile("https?://pastebin.com/([^/]+)$");
private boolean mungingLinks = true;
public boolean isMungingLinks() {
return mungingLinks;
}
public void setMungingLinks(boolean mungingLinks) {
this.mungingLinks = mungingLinks;
}
@Override
public ListenableFuture<URL> paste(String content) {
if (mungingLinks) {
content = content.replaceAll("http://", "http_//");
}
return Pasters.getExecutor().submit(new PasteTask(content));
}
private final class PasteTask implements Callable<URL> {
private final String content;
private PasteTask(String content) {
this.content = content;
}
@Override
public URL call() throws IOException, InterruptedException {
Form form = Form.create();
form.add("api_option", "paste");
form.add("api_dev_key", "4867eae74c6990dbdef07c543cf8f805");
form.add("api_paste_code", content);
form.add("api_paste_private", "0");
form.add("api_paste_name", "");
form.add("api_paste_expire_date", "1W");
form.add("api_paste_format", "text");
form.add("api_user_key", "");
URL url = HttpRequest.url("http://pastebin.com/api/api_post.php");
String result = HttpRequest.post(url)
.bodyForm(form)
.execute()
.expectResponseCode(200)
.returnContent()
.asString("UTF-8").trim();
Matcher m = URL_PATTERN.matcher(result);
if (m.matches()) {
return new URL("http://pastebin.com/raw.php?i=" + m.group(1));
} else if (result.matches("^https?://.+")) {
return new URL(result);
} else {
throw new IOException("Failed to save paste; instead, got: " + result);
}
}
}
}
@@ -1,30 +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/>.
*/
package com.sk89q.worldguard.util.paste;
import com.google.common.util.concurrent.ListenableFuture;
import java.net.URL;
public interface Paster {
ListenableFuture<URL> paste(String content);
}
@@ -1,44 +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/>.
*/
package com.sk89q.worldguard.util.paste;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
final class Pasters {
private static final ListeningExecutorService executor =
MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(0, Integer.MAX_VALUE,
2L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()));
private Pasters() {
}
static ListeningExecutorService getExecutor() {
return executor;
}
}
@@ -1,177 +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/>.
*/
package com.sk89q.worldguard.util.report;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
public class DataReport implements Report {
private final String title;
private final List<Line> lines = Lists.newArrayList();
public DataReport(String title) {
checkNotNull(title, "title");
this.title = title;
}
public void append(String key, String message) {
checkNotNull(key, "key");
lines.add(new Line(key, message));
}
public void append(String key, String message, Object... values) {
checkNotNull(message, "values");
checkNotNull(values, "values");
append(key, String.format(message, values));
}
public void append(String key, byte value) {
append(key, String.valueOf(value));
}
public void append(String key, short value) {
append(key, String.valueOf(value));
}
public void append(String key, int value) {
append(key, String.valueOf(value));
}
public void append(String key, long value) {
append(key, String.valueOf(value));
}
public void append(String key, float value) {
append(key, String.valueOf(value));
}
public void append(String key, double value) {
append(key, String.valueOf(value));
}
public void append(String key, boolean value) {
append(key, String.valueOf(value));
}
public void append(String key, char value) {
append(key, String.valueOf(value));
}
public void append(String key, Object value) {
append(key, getStringValue(value, Sets.newHashSet()));
}
private static String getStringValue(Object value, Set<Object> seen) {
if (seen.contains(value)) {
return "<Recursive>";
} else {
seen.add(value);
}
if (value instanceof Object[]) {
value = Arrays.asList(value);
}
if (value instanceof Collection<?>) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Object entry : (Collection<?>) value) {
if (first) {
first = false;
} else {
builder.append("\n");
}
builder.append(getStringValue(entry, Sets.newHashSet(seen)));
}
return builder.toString();
} else if (value instanceof Map<?, ?>) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
if (first) {
first = false;
} else {
builder.append("\n");
}
String key = getStringValue(entry.getKey(), Sets.newHashSet(seen)).replaceAll("[\r\n]", "");
if (key.length() > 60) {
key = key.substring(0, 60) + "...";
}
builder
.append(key)
.append(": ")
.append(getStringValue(entry.getValue(), Sets.newHashSet(seen)));
}
return builder.toString();
} else {
return String.valueOf(value);
}
}
@Override
public String getTitle() {
return title;
}
@Override
public String toString() {
if (!lines.isEmpty()) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Line line : lines) {
if (first) {
first = false;
} else {
builder.append("\n");
}
builder.append(line.key).append(": ");
if (line.value == null) {
builder.append("null");
} else if (line.value.contains("\n")) {
builder.append("\n");
builder.append(line.value.replaceAll("(?m)^", "\t"));
} else {
builder.append(line.value);
}
}
return builder.toString();
} else {
return "No data.";
}
}
private static class Line {
private final String key;
private final String value;
public Line(String key, String value) {
this.key = key;
this.value = value;
}
}
}
@@ -1,186 +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/>.
*/
package com.sk89q.worldguard.util.report;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ReportList implements Report, List<Report> {
private final String title;
private final List<Report> reports = Lists.newArrayList();
public ReportList(String title) {
this.title = title;
}
@Override
public String getTitle() {
return title;
}
@Override
public int size() {
return reports.size();
}
@Override
public boolean isEmpty() {
return reports.isEmpty();
}
@Override
public boolean contains(Object o) {
return reports.contains(o);
}
@Override
public Iterator<Report> iterator() {
return reports.iterator();
}
@Override
public Object[] toArray() {
return reports.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return reports.toArray(a);
}
@Override
public boolean add(Report report) {
return reports.add(report);
}
@Override
public boolean remove(Object o) {
return reports.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return reports.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Report> c) {
return reports.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends Report> c) {
return reports.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return reports.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return reports.retainAll(c);
}
@Override
public void clear() {
reports.clear();
}
@Override
public boolean equals(Object o) {
return reports.equals(o);
}
@Override
public int hashCode() {
return reports.hashCode();
}
@Override
public Report get(int index) {
return reports.get(index);
}
@Override
public Report set(int index, Report element) {
return reports.set(index, element);
}
@Override
public void add(int index, Report element) {
reports.add(index, element);
}
@Override
public Report remove(int index) {
return reports.remove(index);
}
@Override
public int indexOf(Object o) {
return reports.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return reports.lastIndexOf(o);
}
@Override
public ListIterator<Report> listIterator() {
return reports.listIterator();
}
@Override
public ListIterator<Report> listIterator(int index) {
return reports.listIterator(index);
}
@Override
public List<Report> subList(int fromIndex, int toIndex) {
return reports.subList(fromIndex, toIndex);
}
@Override
public String toString() {
if (!reports.isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Report report : reports) {
builder.append("================================\n")
.append(report.getTitle())
.append("\n================================")
.append("\n\n")
.append(report.toString())
.append("\n\n");
}
return builder.toString();
} else {
return "No reports.";
}
}
}
@@ -1,58 +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/>.
*/
package com.sk89q.worldguard.util.report;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
public class ShallowObjectReport extends DataReport {
private static final Logger log = Logger.getLogger(ShallowObjectReport.class.getCanonicalName());
public ShallowObjectReport(String title, Object object) {
super(title);
checkNotNull(object, "object");
Class<?> type = object.getClass();
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
if (field.getAnnotation(Unreported.class) != null) {
continue;
}
field.setAccessible(true);
try {
Object value = field.get(object);
append(field.getName(), String.valueOf(value));
} catch (IllegalAccessException e) {
log.log(Level.WARNING, "Failed to get value of '" + field.getName() + "' on " + type);
}
}
}
}
@@ -1,64 +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/>.
*/
package com.sk89q.worldguard.util.report;
import static com.google.common.base.Preconditions.checkNotNull;
public class StackTraceReport implements Report {
private final StackTraceElement[] stackTrace;
public StackTraceReport(StackTraceElement[] stackTrace) {
checkNotNull(stackTrace, "stackTrace");
this.stackTrace = stackTrace;
}
@Override
public String getTitle() {
return "Stack Trace";
}
@Override
public String toString() {
if (stackTrace.length > 0) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (StackTraceElement element : stackTrace) {
if (first) {
first = false;
} else {
builder.append("\n");
}
builder.append(element.getClassName())
.append(".")
.append(element.getMethodName())
.append("() (")
.append(element.getFileName())
.append(":")
.append(element.getLineNumber())
.append(")");
}
return builder.toString();
} else {
return "No stack trace available.";
}
}
}
@@ -1,91 +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/>.
*/
package com.sk89q.worldguard.util.report;
import java.lang.management.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SystemInfoReport extends DataReport {
public SystemInfoReport() {
super("System Information");
Runtime runtime = Runtime.getRuntime();
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();
List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
append("Java", "%s %s (%s)",
System.getProperty("java.vendor"),
System.getProperty("java.version"),
System.getProperty("java.vendor.url"));
append("Operating System", "%s %s (%s)",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
append("Available Processors", runtime.availableProcessors());
append("Free Memory", runtime.freeMemory() / 1024 / 1024 + " MB");
append("Max Memory", runtime.maxMemory() / 1024 / 1024 + " MB");
append("Total Memory", runtime.totalMemory() / 1024 / 1024 + " MB");
append("System Load Average", osBean.getSystemLoadAverage());
append("Java Uptime", TimeUnit.MINUTES.convert(runtimeBean.getUptime(), TimeUnit.MILLISECONDS) + " minutes");
DataReport startup = new DataReport("Startup");
startup.append("Input Arguments", runtimeBean.getInputArguments());
append(startup.getTitle(), startup);
DataReport vm = new DataReport("Virtual Machine");
vm.append("Name", runtimeBean.getVmName());
vm.append("Vendor", runtimeBean.getVmVendor());
vm.append("Version", runtimeBean.getVmVendor());
append(vm.getTitle(), vm);
DataReport spec = new DataReport("Specification");
spec.append("Name", runtimeBean.getSpecName());
spec.append("Vendor", runtimeBean.getSpecVendor());
spec.append("Version", runtimeBean.getSpecVersion());
append(spec.getTitle(), spec);
DataReport classLoader = new DataReport("Class Loader");
classLoader.append("Loaded Class Count", classLoadingBean.getLoadedClassCount());
classLoader.append("Total Loaded Class Count", classLoadingBean.getTotalLoadedClassCount());
classLoader.append("Unloaded Class Count", classLoadingBean.getUnloadedClassCount());
append(classLoader.getTitle(), classLoader);
DataReport gc = new DataReport("Garbage Collectors");
for (GarbageCollectorMXBean bean : gcBeans) {
DataReport thisGC = new DataReport(bean.getName());
thisGC.append("Collection Count", bean.getCollectionCount());
thisGC.append("Collection Time", bean.getCollectionTime() + "ms");
gc.append(thisGC.getTitle(), thisGC);
}
append(gc.getTitle(), gc);
DataReport threads = new DataReport("Threads");
for (ThreadInfo threadInfo : threadBean.dumpAllThreads(false, false)) {
threads.append("#" + threadInfo.getThreadId() + " " + threadInfo.getThreadName(), threadInfo.getThreadState());
}
append(threads.getTitle(), threads);
}
}
@@ -1,33 +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/>.
*/
package com.sk89q.worldguard.util.report;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotates properties that should not be exposed in the report.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Unreported {
}
@@ -1,74 +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/>.
*/
package com.sk89q.worldguard.util.task;
import com.google.common.util.concurrent.AbstractFuture;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An abstract task that stores a name and owner.
*
* @param <V> the type returned
*/
public abstract class AbstractTask<V> extends AbstractFuture<V> implements Task<V> {
private final UUID uniqueId = UUID.randomUUID();
private final String name;
private final Object owner;
private final Date creationDate = new Date();
/**
* Create a new instance.
*
* @param name the name
* @param owner the owner
*/
protected AbstractTask(String name, @Nullable Object owner) {
checkNotNull(name);
this.name = name;
this.owner = owner;
}
@Override
public UUID getUniqueId() {
return uniqueId;
}
@Override
public String getName() {
return name;
}
@Nullable
@Override
public Object getOwner() {
return owner;
}
@Override
public Date getCreationDate() {
return creationDate;
}
}
@@ -1,121 +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/>.
*/
package com.sk89q.worldguard.util.task;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.task.progress.Progress;
import javax.annotation.Nullable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A task that wraps a {@code ListenableFuture}.
*
* <p>{@link State#SCHEDULED} is never returned because it is not possible
* to test whether the future has "started," so {@link State#RUNNING} is
* returned in its place.</p>
*
* <p>Use {@link #create(ListenableFuture, String, Object)} to create a new
* instance.</p>
*
* @param <V> the type returned
*/
public class FutureForwardingTask<V> extends AbstractTask<V> {
private final ListenableFuture<V> future;
private FutureForwardingTask(ListenableFuture<V> future, String name, @Nullable Object owner) {
super(name, owner);
checkNotNull(future);
this.future = future;
}
@Override
public void addListener(Runnable listener, Executor executor) {
future.addListener(listener, executor);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return future.isCancelled();
}
@Override
public boolean isDone() {
return future.isDone();
}
@Override
public V get() throws InterruptedException, ExecutionException {
return future.get();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
@Override
public State getState() {
if (isCancelled()) {
return State.CANCELLED;
} else if (isDone()) {
try {
get();
return State.SUCCEEDED;
} catch (InterruptedException e) {
return State.CANCELLED;
} catch (ExecutionException e) {
return State.FAILED;
}
} else {
return State.RUNNING;
}
}
@Override
public Progress getProgress() {
return Progress.indeterminate();
}
/**
* Create a new instance.
*
* @param future the future
* @param name the name of the task
* @param owner the owner of the task, or {@code null}
* @param <V> the type returned by the future
* @return a new instance
*/
public static <V> com.sk89q.worldguard.util.task.FutureForwardingTask<V> create(ListenableFuture<V> future, String name, @Nullable Object owner) {
return new com.sk89q.worldguard.util.task.FutureForwardingTask<V>(future, name, owner);
}
}
@@ -1,62 +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/>.
*/
package com.sk89q.worldguard.util.task;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An implementation of a {@code Supervisor}.
*/
public class SimpleSupervisor implements Supervisor {
private final List<Task<?>> monitored = new ArrayList<Task<?>>();
private final Object lock = new Object();
@Override
public List<Task<?>> getTasks() {
synchronized (lock) {
return new ArrayList<Task<?>>(monitored);
}
}
@Override
public void monitor(final Task<?> task) {
checkNotNull(task);
synchronized (lock) {
monitored.add(task);
}
task.addListener(new Runnable() {
@Override
public void run() {
synchronized (lock) {
monitored.remove(task);
}
}
}, MoreExecutors.sameThreadExecutor());
}
}
@@ -1,44 +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/>.
*/
package com.sk89q.worldguard.util.task;
import java.util.List;
/**
* Manages running tasks and informs users of their progress, but does not
* execute the task.
*/
public interface Supervisor {
/**
* Get a list of running or queued tasks.
*
* @return a list of tasks
*/
List<Task<?>> getTasks();
/**
* Monitor the given task.
*
* @param task the task
*/
void monitor(Task<?> task);
}
@@ -1,97 +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/>.
*/
package com.sk89q.worldguard.util.task;
import com.google.common.util.concurrent.ListenableFuture;
import com.sk89q.worldguard.util.task.progress.ProgressObservable;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.UUID;
/**
* A task is a job that can be scheduled, run, or cancelled. Tasks can report
* on their own status. Tasks have owners.
*/
public interface Task<V> extends ListenableFuture<V>, ProgressObservable {
/**
* Get the unique ID of this task.
*
* @return this task's unique ID
*/
UUID getUniqueId();
/**
* Get the name of the task so it can be printed to the user.
*
* @return the name of the task
*/
String getName();
/**
* Get the owner of the task.
*
* @return an owner object, if one is known or valid, otherwise {@code null}
*/
@Nullable
Object getOwner();
/**
* Get the state of the task.
*
* @return the state of the task
*/
State getState();
/**
* Get the time at which the task was created.
*
* @return a date
*/
Date getCreationDate();
/**
* Represents the state of a task.
*/
public enum State {
/**
* The task has been scheduled to run but is not running yet.
*/
SCHEDULED,
/**
* The task has been cancelled and may be stopped or will stop.
*/
CANCELLED,
/**
* The task is currently running.
*/
RUNNING,
/**
* The task has failed.
*/
FAILED,
/**
* The task has succeeded.
*/
SUCCEEDED
}
}
@@ -1,43 +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/>.
*/
package com.sk89q.worldguard.util.task;
import java.util.Comparator;
/**
* Compares task states according to the order of the {@link com.sk89q.worldguard.util.task.Task.State}
* enumeration.
*/
public class TaskStateComparator implements Comparator<com.sk89q.worldguard.util.task.Task<?>> {
@Override
public int compare(com.sk89q.worldguard.util.task.Task<?> o1, Task<?> o2) {
int ordinal1 = o1.getState().ordinal();
int ordinal2 = o2.getState().ordinal();
if (ordinal1 < ordinal2) {
return -1;
} else if (ordinal1 > ordinal2) {
return 1;
} else {
return 0;
}
}
}
Loaded 100 of 454 files, more files were not shown because too many files have changed in this diff. Show more