Compare commits

...
354 Commits
Author SHA1 Message Date
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
427 changed files with 19626 additions and 17705 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
*.java diff=java
*.java diff=java
+12 -8
View File
@@ -1,13 +1,17 @@
/.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/
+5 -4
View File
@@ -1,7 +1,8 @@
language: java
dist: trusty
jdk:
- oraclejdk7
- openjdk7
- openjdk6
- oraclejdk8
notifications:
email: false
email: false
before_install: chmod +x gradlew
script: ./gradlew build -S
+97
View File
@@ -1,5 +1,102 @@
# Changelog
## 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.
+1 -1
View File
@@ -4,7 +4,7 @@ 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
+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.
+46 -46
View File
@@ -1,46 +1,46 @@
# ![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)
# ![WorldGuard](worldguard-logo.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 8 and our build process makes use of
[Gradle](http://gradle.org).
Dependencies are automatically handled by Gradle.
Contributing
------------
We happily accept contributions, especially through pull requests on GitHub.
Please read CONTRIBUTING.md for important guidelines to follow.
Submissions must be licensed under the GNU Lesser General Public License v3.
Links
-----
* [Homepage](http://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [IRC channel](https://webchat.esper.net/?join=sk89q) (#sk89q on irc.esper.net)
* [Issue tracker](https://dev.enginehub.org/issues/WORLDGUARD)
* [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 {
(ext["grgit"] as Grgit?)?.head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no_git_id"
}
}
+19
View File
@@ -0,0 +1,19 @@
plugins {
`kotlin-dsl`
kotlin("jvm") version embeddedKotlinVersion
}
repositories {
jcenter()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation("gradle.plugin.net.minecrell:licenser:0.4.1")
implementation("org.ajoberstar.grgit:grgit-gradle:3.1.1")
implementation("com.github.jengelman.gradle.plugins:shadow:5.1.0")
implementation("net.ltgt.apt-eclipse:net.ltgt.apt-eclipse.gradle.plugin:0.21")
implementation("net.ltgt.apt-idea:net.ltgt.apt-idea.gradle.plugin:0.21")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7")
}
@@ -0,0 +1,40 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.named
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
private const val ARTIFACTORY_USER = "artifactory_user"
private const val ARTIFACTORY_PASSWORD = "artifactory_password"
fun Project.applyRootArtifactoryConfig() {
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
apply(plugin = "com.jfrog.artifactory")
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
isSkip = true
}
}
fun Project.applyCommonArtifactoryConfig() {
val named = tasks.named<ArtifactoryTask>("artifactoryPublish") {
publishConfigs("archives")
}
}
+18
View File
@@ -0,0 +1,18 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.repositories
fun Project.applyCommonConfiguration() {
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven { url = uri("https://maven.sk89q.com/repo/") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(5, "minutes")
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.sourceSets: SourceSetContainer
get() = the<JavaPluginConvention>().sourceSets
+96
View File
@@ -0,0 +1,96 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.internal.HasConvention
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
import org.gradle.api.tasks.Upload
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getPlugin
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.register
fun Project.applyLibrariesConfiguration() {
applyCommonConfiguration()
apply(plugin = "java-base")
apply(plugin = "maven")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
configurations {
create("shade")
getByName("archives").extendsFrom(getByName("default"))
}
group = "${rootProject.group}.worldguard-libs"
tasks.register<ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
dependencies {
exclude(dependency("com.google.code.findbugs:jsr305:1.3.9"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
val filePattern = Regex("(.*)com/sk89q/squirrelid((?:/|$).*)")
val textPattern = Regex("com\\.sk89q\\.squirrelid")
eachFile {
filter {
it.replaceFirst(textPattern, "com.sk89q.worldguard.util.profile")
}
path = path.replaceFirst(filePattern, "$1com/sk89q/worldguard/util/profile$2")
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
artifacts {
val jar = tasks.named("jar")
add("default", jar) {
builtBy(jar)
}
val sourcesJar = tasks.named("sourcesJar")
add("archives", sourcesJar) {
builtBy(sourcesJar)
}
}
tasks.register<Upload>("install") {
configuration = configurations["archives"]
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.version = project.version.toString()
pom.artifactId = project.name
}
}
applyCommonArtifactoryConfig()
}
+119
View File
@@ -0,0 +1,119 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import net.minecrell.gradle.licenser.LicenseExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.CoreJavadocOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getByName
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
fun Project.applyPlatformAndCoreConfiguration() {
applyCommonConfiguration()
apply(plugin = "java")
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "maven")
apply(plugin = "checkstyle")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
apply(plugin = "net.minecrell.licenser")
ext["internalVersion"] = "$version;${rootProject.ext["gitCommitHash"]}"
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "7.6.1"
}
tasks.withType<Test>().configureEach {
useJUnit()
}
dependencies {
"testCompile"("junit:junit:${Versions.JUNIT}")
// TODO switch to jupiter - doesn't support abstract test classes so tests need rewriting
//"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
//"testRuntime"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
(options as CoreJavadocOptions).addStringOption("Xdoclint:none", "-quiet")
}
tasks.register<Jar>("javadocJar") {
dependsOn("javadoc")
archiveClassifier.set("javadoc")
from(tasks.getByName<Javadoc>("javadoc").destinationDir)
}
tasks.named("assemble").configure {
dependsOn("javadocJar")
}
artifacts {
add("archives", tasks.named("jar"))
add("archives", tasks.named("javadocJar"))
}
if (name == "worldguard-core" || name == "worldguard-bukkit") {
tasks.register<Jar>("sourcesJar") {
dependsOn("classes")
archiveClassifier.set("sources")
from(sourceSets["main"].allSource)
}
artifacts {
add("archives", tasks.named("sourcesJar"))
}
tasks.named("assemble").configure {
dependsOn("sourcesJar")
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
applyCommonArtifactoryConfig()
configure<LicenseExtension> {
header = rootProject.file("HEADER.txt")
include("**/*.java")
}
}
fun Project.applyShadowConfiguration() {
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
//include(project(":worldguard-libs:${project.name.replace("worldguard-", "")}"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core:3.0"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
}
}
+6
View File
@@ -0,0 +1,6 @@
object Versions {
// const val PISTON = "0.4.3"
// const val AUTO_VALUE = "1.6.5"
const val JUNIT = "4.11"
const val SQUIRRELID = "0.2.0"
}
-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>
+61
View File
@@ -0,0 +1,61 @@
<?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="${basedir}/config/checkstyle/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="${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 -->
<!-- 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/>.
*/
+25 -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,31 @@
<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="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
</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">
+2
View File
@@ -0,0 +1,2 @@
group=com.sk89q.worldguard
version=7.0.1
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
Vendored
+84
View File
@@ -0,0 +1,84 @@
@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=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
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 init
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
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
: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,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,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,146 +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.bukkit.RegionQuery;
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.util.Materials;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import javax.annotation.Nullable;
public class RegionFlagsListener extends AbstractListener {
/**
* Construct the listener.
*
* @param plugin an instance of WorldGuardPlugin
*/
public RegionFlagsListener(WorldGuardPlugin plugin) {
super(plugin);
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
// ================================================================
// PISTONS flag
// ================================================================
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
WorldConfiguration config = getWorldConfig(event.getWorld());
RegionQuery query = getPlugin().getRegionContainer().createQuery();
Block block;
if ((block = event.getCause().getFirstBlock()) != null) {
// ================================================================
// PISTONS flag
// ================================================================
if (Materials.isPistonBlock(block.getType())) {
event.filter(testState(query, DefaultFlag.PISTONS), false);
}
}
Entity entity;
if ((entity = event.getCause().getFirstNonPlayerEntity()) != null) {
// ================================================================
// CREEPER_EXPLOSION flag
// ================================================================
if (entity instanceof Creeper) { // Creeper
event.filter(testState(query, DefaultFlag.CREEPER_EXPLOSION), config.explosionFlagCancellation);
}
// ================================================================
// ENDERDRAGON_BLOCK_DAMAGE flag
// ================================================================
if (entity instanceof EnderDragon) { // Enderdragon
event.filter(testState(query, DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE), config.explosionFlagCancellation);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
World world = entity.getWorld();
if (!isRegionSupportEnabled(world)) return; // Region support disabled
RegionQuery query = getPlugin().getRegionContainer().createQuery();
if (entity instanceof Player && event.getCause() == DamageCause.FALL) {
if (!query.testState(entity.getLocation(), (Player) entity, DefaultFlag.FALL_DAMAGE)) {
event.setCancelled(true);
}
}
}
/**
* Create a new predicate to test a state flag for each location.
*
* @param query the query
* @param flag the flag
* @return a predicate
*/
private Predicate<Location> testState(final RegionQuery query, final StateFlag flag) {
return new Predicate<Location>() {
@Override
public boolean apply(@Nullable Location location) {
return query.testState(location, (RegionAssociable) null, flag);
}
};
}
}
@@ -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,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,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.protection;
/**
* Thrown when an intersection between two different types of regions is not
* supported.
*
* @deprecated no longer utilized
*/
@Deprecated
public class UnsupportedIntersectionException extends Exception {
}
@@ -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,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,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;
}
}
}
@@ -1,183 +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.progress;
import java.util.Arrays;
import java.util.Collection;
/**
* A progress object describes the progress of an operation, specifying
* either a percentage of completion or a status of indeterminacy.
*
* <p>Progress objects are immutable.</p>
*
* <p>To create a new instance, use one of the static constructors
* on this class.</p>
*/
public abstract class Progress {
/**
* Create a new instance.
*/
private Progress() {
}
/**
* Return whether the current progress is indeterminate.
*
* @return true if indeterminate
*/
public abstract boolean isIndeterminate();
/**
* Get the progress percentage.
*
* <p>If {@link #isIndeterminate()} returns {@code true}, the behavior
* of this method is undefined.</p>
*
* @return a number in the range [0, 1]
*/
public abstract double getProgress();
/**
* Get a static progress object that is indeterminate.
*
* @return a progress object
*/
public static com.sk89q.worldguard.util.task.progress.Progress indeterminate() {
return INDETERMINATE;
}
/**
* Get a static progress object that is complete.
*
* @return a progress object
*/
public static com.sk89q.worldguard.util.task.progress.Progress completed() {
return COMPLETED;
}
/**
* Create a new progress object with the given percentage.
*
* @param value the percentage, which will be clamped to [0, 1]
* @return a progress object
*/
public static com.sk89q.worldguard.util.task.progress.Progress of(double value) {
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
final double finalValue = value;
return new com.sk89q.worldguard.util.task.progress.Progress() {
@Override
public boolean isIndeterminate() {
return false;
}
@Override
public double getProgress() {
return finalValue;
}
};
}
/**
* Create a new progress object with progress split equally between the
* given progress objects.
*
* @param objects an array of progress objects
* @return a new progress value
*/
public static com.sk89q.worldguard.util.task.progress.Progress split(com.sk89q.worldguard.util.task.progress.Progress... objects) {
return split(Arrays.asList(objects));
}
/**
* Create a new progress object with progress split equally between the
* given progress objects.
*
* @param progress a collection of progress objects
* @return a new progress value
*/
public static com.sk89q.worldguard.util.task.progress.Progress split(Collection<com.sk89q.worldguard.util.task.progress.Progress> progress) {
int count = 0;
double total = 0;
for (com.sk89q.worldguard.util.task.progress.Progress p : progress) {
if (p.isIndeterminate()) {
return indeterminate();
}
total += p.getProgress();
}
return of(total / count);
}
/**
* Create a new progress object with progress split equally between the
* given {@link com.sk89q.worldguard.util.task.progress.ProgressObservable}s.
*
* @param observables an array of observables
* @return a new progress value
*/
public static com.sk89q.worldguard.util.task.progress.Progress splitObservables(com.sk89q.worldguard.util.task.progress.ProgressObservable... observables) {
return splitObservables(Arrays.asList(observables));
}
/**
* Create a new progress object with progress split equally between the
* given {@link com.sk89q.worldguard.util.task.progress.ProgressObservable}s.
*
* @param observables a collection of observables
* @return a new progress value
*/
public static com.sk89q.worldguard.util.task.progress.Progress splitObservables(Collection<? extends com.sk89q.worldguard.util.task.progress.ProgressObservable> observables) {
int count = 0;
double total = 0;
for (ProgressObservable observable : observables) {
com.sk89q.worldguard.util.task.progress.Progress p = observable.getProgress();
if (p.isIndeterminate()) {
return indeterminate();
}
total += p.getProgress();
}
return of(total / count);
}
private static final com.sk89q.worldguard.util.task.progress.Progress COMPLETED = of(1);
private static final com.sk89q.worldguard.util.task.progress.Progress INDETERMINATE = new com.sk89q.worldguard.util.task.progress.Progress() {
@Override
public boolean isIndeterminate() {
return true;
}
@Override
public double getProgress() {
return 0;
}
};
}
@@ -1,100 +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.progress;
import java.util.Iterator;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An iterator that keeps track of how many entries have been visited and
* calculates a "percent completed" using a provided total count.
*
* <p>The returned progress percentage will always be between 0 or 1
* (inclusive). If the iterator returns more entries than the total count,
* then 100% will be returned for the progress.</p>
*
* @param <V> the type
*/
public class ProgressIterator<V> implements Iterator<V>, ProgressObservable {
private final Iterator<V> iterator;
private final int count;
private int visited = 0;
/**
* Create a new instance.
*
* @param iterator the iterator
* @param count the count
*/
private ProgressIterator(Iterator<V> iterator, int count) {
checkNotNull(iterator);
this.iterator = iterator;
this.count = count;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public V next() {
V value = iterator.next();
visited++;
return value;
}
@Override
public void remove() {
iterator.remove();
}
@Override
public Progress getProgress() {
return Progress.of(count > 0 ? Math.min(1, Math.max(0, (visited / (double) count))) : 1);
}
/**
* Create a new instance.
*
* @param iterator the iterator
* @param count the number of objects
* @param <V> the type
* @return an instance
*/
public static <V> com.sk89q.worldguard.util.task.progress.ProgressIterator<V> create(Iterator<V> iterator, int count) {
return new com.sk89q.worldguard.util.task.progress.ProgressIterator<V>(iterator, count);
}
/**
* Create a new instance from a list.
*
* @param list a list
* @param <V> the type
* @return an instance
*/
public static <V> com.sk89q.worldguard.util.task.progress.ProgressIterator<V> create(List<V> list) {
return create(list.iterator(), list.size());
}
}
@@ -1,34 +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.progress;
/**
* An object that is able to report on its progress.
*/
public interface ProgressObservable {
/**
* Get the current percentage of completion.
*
* @return a progress object
*/
Progress getProgress();
}
-4
View File
@@ -1,4 +0,0 @@
name: WorldGuard
main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${project.version}"
softdepend: [WorldEdit, CommandBook]
@@ -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;
import com.sk89q.worldedit.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@org.junit.Ignore
public class TestPlayer extends LocalPlayer {
private final UUID uuid = UUID.randomUUID();
private final String name;
private final Set<String> groups = new HashSet<String>();
public TestPlayer(String name) {
this.name = name;
}
public void addGroup(String group) {
groups.add(group.toLowerCase());
}
@Override
public String getName() {
return name;
}
@Override
public UUID getUniqueId() {
return uuid;
}
@Override
public boolean hasGroup(String group) {
return groups.contains(group.toLowerCase());
}
@Override
public Vector getPosition() {
return new Vector(0, 0, 0);
}
@Override
public void kick(String msg) {
System.out.println("TestPlayer{" + this.name + "} kicked!");
}
@Override
public void ban(String msg) {
System.out.println("TestPlayer{" + this.name + "} banned!");
}
@Override
public void printRaw(String msg) {
System.out.println("-> TestPlayer{" + this.name + "}: " + msg);
}
@Override
public String[] getGroups() {
return groups.toArray(new String[groups.size()]);
}
@Override
public boolean hasPermission(String perm) {
return true;
}
}
+74
View File
@@ -0,0 +1,74 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.internal.HasConvention
plugins {
id("java-library")
id("net.ltgt.apt-eclipse")
id("net.ltgt.apt-idea")
}
applyPlatformAndCoreConfiguration()
applyShadowConfiguration()
repositories {
maven {
name = "paper"
url = uri("https://papermc.io/repo/repository/maven-public/")
}
maven {
name = "bstats"
url = uri("https://repo.codemc.org/repository/maven-public")
}
}
dependencies {
"compile"(project(":worldguard-core"))
//"compile"(project(":worldguard-libs:bukkit"))
"api"("com.destroystokyo.paper:paper-api:1.14.4-R0.1-SNAPSHOT")
"implementation"("io.papermc:paperlib:1.0.2")
"api"("com.sk89q.worldedit:worldedit-bukkit:7.0.1-SNAPSHOT") { isTransitive = false }
"implementation"("com.sk89q:commandbook:2.3") { isTransitive = false }
"implementation"("org.bstats:bstats-bukkit:1.5")
}
tasks.named<Upload>("install") {
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.whenConfigured {
dependencies.firstOrNull { dep ->
dep!!.withGroovyBuilder {
getProperty("groupId") == "com.destroystokyo.paper" && getProperty("artifactId") == "paper-api"
}
}?.withGroovyBuilder {
setProperty("groupId", "org.bukkit")
setProperty("artifactId", "bukkit")
}
}
}
}
tasks.named<Copy>("processResources") {
filesMatching("plugin.yml") {
expand("internalVersion" to project.ext["internalVersion"])
}
}
tasks.named<Jar>("jar") {
manifest {
attributes("Implementation-Version" to project.version)
}
}
tasks.named<ShadowJar>("shadowJar") {
dependencies {
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats") {
include(dependency("org.bstats:bstats-bukkit:1.5"))
}
relocate ("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib") {
include(dependency("io.papermc:paperlib:1.0.2"))
}
}
}
tasks.named("assemble").configure {
dependsOn("shadowJar")
}
File renamed without changes.
@@ -0,0 +1,123 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.config.YamlConfigurationManager;
import com.sk89q.worldedit.util.report.Unreported;
import java.io.File;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class BukkitConfigurationManager extends YamlConfigurationManager {
@Unreported private WorldGuardPlugin plugin;
@Unreported private ConcurrentMap<String, BukkitWorldConfiguration> worlds = new ConcurrentHashMap<>();
private boolean hasCommandBookGodMode;
boolean extraStats;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public BukkitConfigurationManager(WorldGuardPlugin plugin) {
super();
this.plugin = plugin;
}
public Collection<BukkitWorldConfiguration> getWorldConfigs() {
return worlds.values();
}
@Override
public void load() {
super.load();
this.extraStats = getConfig().getBoolean("custom-metrics-charts", true);
}
@Override
public File getDataFolder() {
return plugin.getDataFolder();
}
@Override
public void copyDefaults() {
// Create the default configuration file
plugin.createDefaultConfiguration(new File(plugin.getDataFolder(), "config.yml"), "config.yml");
}
@Override
public void unload() {
worlds.clear();
}
@Override
public void postLoad() {
// Load configurations for each world
for (World world : WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds()) {
get(world);
}
getConfig().save();
}
/**
* Get the configuration for a world.
*
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
@Override
public BukkitWorldConfiguration get(World world) {
String worldName = world.getName();
BukkitWorldConfiguration config = worlds.get(worldName);
BukkitWorldConfiguration newConfig = null;
while (config == null) {
if (newConfig == null) {
newConfig = new BukkitWorldConfiguration(plugin, worldName, this.getConfig());
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
}
public void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
hasCommandBookGodMode = true;
return;
}
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -17,12 +17,24 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.commands;
package com.sk89q.worldguard.bukkit;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.debug.*;
import com.sk89q.worldguard.util.report.CancelReport;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.paste.ActorCallbackPaste;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.event.debug.CancelLogging;
import com.sk89q.worldguard.bukkit.event.debug.LoggingBlockBreakEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingBlockPlaceEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingEntityDamageByEntityEvent;
import com.sk89q.worldguard.bukkit.event.debug.LoggingPlayerInteractEvent;
import com.sk89q.worldguard.bukkit.util.report.CancelReport;
import com.sk89q.worldguard.internal.platform.DebugHandler;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@@ -34,68 +46,22 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.util.BlockIterator;
import java.util.logging.Logger;
public class DebuggingCommands {
public class BukkitDebugHandler implements DebugHandler {
private static final Logger log = Logger.getLogger(DebuggingCommands.class.getCanonicalName());
private static final Logger log = Logger.getLogger(BukkitDebugHandler.class.getCanonicalName());
private static final int MAX_TRACE_DISTANCE = 20;
private final WorldGuardPlugin plugin;
/**
* Create a new instance.
*
* @param plugin The plugin instance
*/
public DebuggingCommands(WorldGuardPlugin plugin) {
BukkitDebugHandler(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"testbreak"}, usage = "[player]", desc = "Simulate a block break", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireBreakEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK BREAK at " + ChatColor.DARK_AQUA + block);
LoggingBlockBreakEvent event = new LoggingBlockBreakEvent(block, target);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testplace"}, usage = "[player]", desc = "Simulate a block place", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void firePlaceEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK PLACE at " + ChatColor.DARK_AQUA + block);
LoggingBlockPlaceEvent event = new LoggingBlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), target.getItemInHand(), target, true);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testinteract"}, usage = "[player]", desc = "Simulate a block interact", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireInteractEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Block block = traceBlock(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing BLOCK INTERACT at " + ChatColor.DARK_AQUA + block);
LoggingPlayerInteractEvent event = new LoggingPlayerInteractEvent(target, Action.RIGHT_CLICK_BLOCK, target.getItemInHand(), block, BlockFace.SOUTH);
testEvent(sender, target, event, args.hasFlag('s'));
}
@Command(aliases = {"testdamage"}, usage = "[player]", desc = "Simulate an entity damage", min = 1, max = 1, flags = "ts")
@CommandPermissions("worldguard.debug.event")
public void fireDamageEvent(CommandContext args, final CommandSender sender) throws CommandException {
Player target = plugin.matchSinglePlayer(sender, args.getString(0));
Entity entity = traceEntity(sender, target, args.hasFlag('t'));
sender.sendMessage(ChatColor.AQUA + "Testing ENTITY DAMAGE on " + ChatColor.DARK_AQUA + entity);
LoggingEntityDamageByEntityEvent event = new LoggingEntityDamageByEntityEvent(target, entity, DamageCause.ENTITY_ATTACK, 1);
testEvent(sender, target, event, args.hasFlag('s'));
}
/**
* Simulate an event and print its report.
*
@@ -105,7 +71,8 @@ public class DebuggingCommands {
* @param stacktraceMode Whether stack traces should be generated and posted
* @param <T> The type of event
*/
private <T extends Event & CancelLogging> void testEvent(CommandSender receiver, Player target, T event, boolean stacktraceMode) throws CommandPermissionsException {
private <T extends Event & CancelLogging> void testEvent(CommandSender receiver, Player target, T event, boolean stacktraceMode) throws
CommandPermissionsException {
boolean isConsole = receiver instanceof ConsoleCommandSender;
if (!receiver.equals(target)) {
@@ -128,7 +95,8 @@ public class DebuggingCommands {
log.info("Event report for " + receiver.getName() + ":\n\n" + result);
plugin.checkPermission(receiver, "worldguard.debug.pastebin");
CommandUtils.pastebin(plugin, receiver, result, "Event debugging report: %s.txt");
ActorCallbackPaste.pastebin(WorldGuard.getInstance().getSupervisor(), plugin.wrapCommandSender(receiver),
result, "Event debugging report: %s.txt");
} else {
receiver.sendMessage(result.replaceAll("(?m)^", ChatColor.AQUA.toString()));
@@ -217,4 +185,46 @@ public class DebuggingCommands {
throw new CommandException("Not currently looking at an entity that is close enough.");
}
@Override
public void testBreak(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK BREAK at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingBlockBreakEvent event = new LoggingBlockBreakEvent(block, bukkitTarget);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testPlace(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK PLACE at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingBlockPlaceEvent event = new LoggingBlockPlaceEvent(block, block.getState(), block.getRelative(BlockFace.DOWN), bukkitTarget.getItemInHand(), bukkitTarget, true);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testInteract(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Block block = traceBlock(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing BLOCK INTERACT at ", TextColor.AQUA).append(TextComponent.of(block.toString(), TextColor.DARK_AQUA)));
LoggingPlayerInteractEvent event = new LoggingPlayerInteractEvent(bukkitTarget, Action.RIGHT_CLICK_BLOCK, bukkitTarget.getItemInHand(), block, BlockFace.SOUTH);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
@Override
public void testDamage(Actor sender, LocalPlayer target, boolean fromTarget, boolean stackTraceMode) throws CommandException {
CommandSender bukkitSender = plugin.unwrapActor(sender);
Player bukkitTarget = BukkitAdapter.adapt(target);
Entity entity = traceEntity(bukkitSender, bukkitTarget, fromTarget);
sender.print(TextComponent.of("Testing ENTITY DAMAGE at ", TextColor.AQUA).append(TextComponent.of(entity.toString(), TextColor.DARK_AQUA)));
LoggingEntityDamageByEntityEvent event = new LoggingEntityDamageByEntityEvent(bukkitTarget, entity, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 1);
testEvent(bukkitSender, bukkitTarget, event, stackTraceMode);
}
}
@@ -0,0 +1,241 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.session.SessionKey;
import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.weather.WeatherType;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
import javax.annotation.Nullable;
class BukkitOfflinePlayer extends BukkitPlayer {
private final OfflinePlayer player;
BukkitOfflinePlayer(WorldGuardPlugin plugin, OfflinePlayer offlinePlayer) {
super(plugin, offlinePlayer.getPlayer()); // null if they are offline
this.player = offlinePlayer;
}
/// ========================================
/// These are checked for RegionAssociable
/// (to see if a player belongs to a region)
/// ========================================
@Override
public String getName() {
return player.getName();
}
@Override
public UUID getUniqueId() {
return player.getUniqueId();
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(player, group);
}
@Override
public String[] getGroups() {
return plugin.getGroups(player);
}
/// ==========================================
/// None of the following should ever be used.
/// ==========================================
@Override
public boolean hasPermission(String perm) {
throw new UnsupportedOperationException();
}
@Override
public void kick(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void ban(String msg) {
throw new UnsupportedOperationException();
}
@Override
public double getHealth() {
throw new UnsupportedOperationException();
}
@Override
public void setHealth(double health) {
throw new UnsupportedOperationException();
}
@Override
public double getMaxHealth() {
throw new UnsupportedOperationException();
}
@Override
public double getFoodLevel() {
throw new UnsupportedOperationException();
}
@Override
public void setFoodLevel(double foodLevel) {
throw new UnsupportedOperationException();
}
@Override
public double getSaturation() {
throw new UnsupportedOperationException();
}
@Override
public void setSaturation(double saturation) {
throw new UnsupportedOperationException();
}
@Override
public float getExhaustion() {
throw new UnsupportedOperationException();
}
@Override
public void setExhaustion(float exhaustion) {
throw new UnsupportedOperationException();
}
@Override
public WeatherType getPlayerWeather() {
throw new UnsupportedOperationException();
}
@Override
public void setPlayerWeather(WeatherType weather) {
throw new UnsupportedOperationException();
}
@Override
public void resetPlayerWeather() {
throw new UnsupportedOperationException();
}
@Override
public boolean isPlayerTimeRelative() {
throw new UnsupportedOperationException();
}
@Override
public long getPlayerTimeOffset() {
throw new UnsupportedOperationException();
}
@Override
public void setPlayerTime(long time, boolean relative) {
throw new UnsupportedOperationException();
}
@Override
public void resetPlayerTime() {
throw new UnsupportedOperationException();
}
@Override
public void printRaw(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void printDebug(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void print(String msg) {
throw new UnsupportedOperationException();
}
@Override
public void printError(String msg) {
throw new UnsupportedOperationException();
}
@Override
public World getWorld() {
throw new UnsupportedOperationException();
}
@Override
public BaseItemStack getItemInHand(HandSide handSide) {
throw new UnsupportedOperationException();
}
@Override
public void giveItem(BaseItemStack itemStack) {
throw new UnsupportedOperationException();
}
@Override
public BlockBag getInventoryBlockBag() {
throw new UnsupportedOperationException();
}
@Override
public void setPosition(Vector3 pos, float pitch, float yaw) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public BaseEntity getState() {
throw new UnsupportedOperationException();
}
@Override
public Location getLocation() {
throw new UnsupportedOperationException();
}
@Override
public void setCompassTarget(Location location) {
throw new UnsupportedOperationException();
}
@Override
public SessionKey getSessionKey() {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public <T> T getFacet(Class<? extends T> cls) {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,212 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import com.sk89q.worldguard.LocalPlayer;
import io.papermc.lib.PaperLib;
import org.bukkit.BanList.Type;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class BukkitPlayer extends com.sk89q.worldedit.bukkit.BukkitPlayer implements LocalPlayer {
protected final WorldGuardPlugin plugin;
private final boolean silenced;
private String name;
public BukkitPlayer(WorldGuardPlugin plugin, Player player) {
this(plugin, player, false);
}
BukkitPlayer(WorldGuardPlugin plugin, Player player, boolean silenced) {
super(player);
this.plugin = plugin;
this.silenced = silenced;
}
@Override
public String getName() {
if (this.name == null) {
// getName() takes longer than before in newer versions of Minecraft
this.name = getPlayer().getName();
}
return name;
}
@Override
public boolean hasGroup(String group) {
return plugin.inGroup(getPlayer(), group);
}
@Override
public void kick(String msg) {
if (!silenced) {
getPlayer().kickPlayer(msg);
}
}
@Override
public void ban(String msg) {
if (!silenced) {
Bukkit.getBanList(Type.NAME).addBan(getName(), null, null, null);
getPlayer().kickPlayer(msg);
}
}
@Override
public double getHealth() {
return getPlayer().getHealth();
}
@Override
public void setHealth(double health) {
getPlayer().setHealth(health);
}
@Override
public double getMaxHealth() {
return getPlayer().getMaxHealth();
}
@Override
public double getFoodLevel() {
return getPlayer().getFoodLevel();
}
@Override
public void setFoodLevel(double foodLevel) {
getPlayer().setFoodLevel((int) foodLevel);
}
@Override
public double getSaturation() {
return getPlayer().getSaturation();
}
@Override
public void setSaturation(double saturation) {
getPlayer().setSaturation((float) saturation);
}
@Override
public float getExhaustion() {
return getPlayer().getExhaustion();
}
@Override
public void setExhaustion(float exhaustion) {
getPlayer().setExhaustion(exhaustion);
}
@Override
public WeatherType getPlayerWeather() {
org.bukkit.WeatherType playerWeather = getPlayer().getPlayerWeather();
return playerWeather == null ? null : playerWeather == org.bukkit.WeatherType.CLEAR ? WeatherTypes.CLEAR : WeatherTypes.RAIN;
}
@Override
public void setPlayerWeather(WeatherType weather) {
getPlayer().setPlayerWeather(weather == WeatherTypes.CLEAR ? org.bukkit.WeatherType.CLEAR : org.bukkit.WeatherType.DOWNFALL);
}
@Override
public void resetPlayerWeather() {
getPlayer().resetPlayerWeather();
}
@Override
public boolean isPlayerTimeRelative() {
return getPlayer().isPlayerTimeRelative();
}
@Override
public long getPlayerTimeOffset() {
return getPlayer().getPlayerTimeOffset();
}
@Override
public void setPlayerTime(long time, boolean relative) {
getPlayer().setPlayerTime(time, relative);
}
@Override
public void resetPlayerTime() {
getPlayer().resetPlayerTime();
}
@Override
public int getFireTicks() {
return getPlayer().getFireTicks();
}
@Override
public void setFireTicks(int fireTicks) {
getPlayer().setFireTicks(fireTicks);
}
@Override
public void setCompassTarget(Location location) {
getPlayer().setCompassTarget(BukkitAdapter.adapt(location));
}
@Override
public void sendTitle(String title, String subtitle) {
getPlayer().sendTitle(title, subtitle, -1, -1, -1);
}
@Override
public void resetFallDistance() {
getPlayer().setFallDistance(0);
}
@Override
public void teleport(Location location, String successMessage, String failMessage) {
PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location))
.thenApply(success -> {
if (success) {
print(successMessage);
} else {
printError(failMessage);
}
return success;
});
}
@Override
public String[] getGroups() {
return plugin.getGroups(getPlayer());
}
@Override
public void printRaw(String msg) {
if (!silenced) {
super.printRaw(msg);
}
}
@Override
public boolean hasPermission(String perm) {
return plugin.hasPermission(getPlayer(), perm);
}
}
@@ -0,0 +1,132 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class BukkitRegionContainer extends RegionContainer {
/**
* Invalidation frequency in ticks.
*/
private static final int CACHE_INVALIDATION_INTERVAL = 2;
private final WorldGuardPlugin plugin;
/**
* Create a new instance.
*
* @param plugin the plugin
*/
public BukkitRegionContainer(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Override
public void initialize() {
super.initialize();
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
load(BukkitAdapter.adapt(event.getWorld()));
}
@EventHandler
public void onWorldUnload(WorldUnloadEvent event) {
unload(BukkitAdapter.adapt(event.getWorld()));
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
RegionManager manager = get(BukkitAdapter.adapt(event.getWorld()));
if (manager != null) {
Chunk chunk = event.getChunk();
manager.loadChunk(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
RegionManager manager = get(BukkitAdapter.adapt(event.getWorld()));
if (manager != null) {
Chunk chunk = event.getChunk();
manager.unloadChunk(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
}
}, plugin);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, cache::invalidateAll, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
}
public void shutdown() {
container.shutdown();
}
@Override
@Nullable
protected RegionManager load(World world) {
checkNotNull(world);
WorldConfiguration config = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world);
if (!config.useRegions) {
return null;
}
RegionManager manager;
synchronized (lock) {
manager = container.load(world.getName());
if (manager != null) {
// Bias the region data for loaded chunks
List<BlockVector2> positions = new ArrayList<>();
for (Chunk chunk : ((BukkitWorld) world).getWorld().getLoadedChunks()) {
positions.add(BlockVector2.at(chunk.getX(), chunk.getZ()));
}
manager.loadChunks(positions);
}
}
return manager;
}
}
@@ -0,0 +1,246 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.internal.platform.StringMatcher;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class BukkitStringMatcher implements StringMatcher {
@Override
public World matchWorld(Actor sender, String filter) throws CommandException {
List<? extends World> worlds = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds();
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.NORMAL) {
return world;
}
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.NETHER) {
return world;
}
}
throw new CommandException("No nether world found.");
// #end for the first nether world
} else if (filter.equalsIgnoreCase("#end")) {
for (World world : worlds) {
if (BukkitAdapter.adapt(world).getEnvironment() == org.bukkit.World.Environment.THE_END) {
return world;
}
}
throw new CommandException("No end world found.");
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String[] parts = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
@Override
public List<LocalPlayer> matchPlayerNames(String filter) {
List<LocalPlayer> wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(Collectors.toList());
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (LocalPlayer player : wgPlayers) {
if (player.getName().equalsIgnoreCase(filter)) {
List<LocalPlayer> list = new ArrayList<>();
list.add(player);
return list;
}
}
return new ArrayList<>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<LocalPlayer> list = new ArrayList<>();
for (LocalPlayer player : wgPlayers) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<LocalPlayer> list = new ArrayList<>();
for (LocalPlayer player : wgPlayers) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
@Override
public Iterable<? extends LocalPlayer> matchPlayers(Actor source, String filter) throws CommandException {
if (Bukkit.getServer().getOnlinePlayers().isEmpty()) {
throw new CommandException("No players matched query.");
}
List<LocalPlayer> wgPlayers = Bukkit.getServer().getOnlinePlayers().stream().map(player -> WorldGuardPlugin.inst().wrapPlayer(player)).collect(Collectors.toList());
if (filter.equals("*")) {
return checkPlayerMatch(wgPlayers);
}
// Handle special hash tag groups
if (filter.charAt(0) == '#') {
// Handle #world, which matches player of the same world as the
// calling source
if (filter.equalsIgnoreCase("#world")) {
List<LocalPlayer> players = new ArrayList<>();
LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (LocalPlayer player : wgPlayers) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
}
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<LocalPlayer> players = new ArrayList<>();
LocalPlayer sourcePlayer = WorldGuard.getInstance().checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
Vector3 sourceVector = sourcePlayer.getLocation().toVector();
for (LocalPlayer player : wgPlayers) {
if (player.getWorld().equals(sourceWorld) && player.getLocation().toVector().distanceSq(sourceVector) < 900) {
players.add(player);
}
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<LocalPlayer> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
@Override
public Actor matchPlayerOrConsole(Actor sender, String filter) throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return WorldGuardPlugin.inst().wrapCommandSender(Bukkit.getServer().getConsoleSender());
}
return matchSinglePlayer(sender, filter);
}
@Override
public World getWorldByName(String worldName) {
final org.bukkit.World bukkitW = Bukkit.getServer().getWorld(worldName);
if (bukkitW == null) {
return null;
}
return BukkitAdapter.adapt(bukkitW);
}
@Override
public String replaceMacros(Actor sender, String message) {
Collection<? extends Player> online = Bukkit.getServer().getOnlinePlayers();
message = message.replace("%name%", sender.getName());
message = message.replace("%id%", sender.getUniqueId().toString());
message = message.replace("%online%", String.valueOf(online.size()));
if (sender instanceof LocalPlayer) {
LocalPlayer player = (LocalPlayer) sender;
World world = (World) player.getExtent();
message = message.replace("%world%", world.getName());
message = message.replace("%health%", String.valueOf(player.getHealth()));
}
return message;
}
}
Loaded 100 of 427 files, more files were not shown because too many files have changed in this diff. Show more