Compare commits

..
10 Commits
Author SHA1 Message Date
wizjany 4707b7c7f0 Fix infinite loop in addowner checks.
Fixes WORLDGUARD-4138.
2019-09-22 14:29:09 -04:00
wizjany b0ebbee3de Backport minecart-item-type fix from f5467001. 2019-09-03 17:56:52 -04:00
wizjany 8db0053ffc Extract/half-fix addowner checks.
Max-region-count-for-player is super bork.

Fixes WORLDGUARD-4129.
2019-08-12 20:25:18 -04:00
wizjany 6cf3c23b47 Check waterlogged blocks when emptying buckets.
Fixes WORLDGUARD-4119.

(cherry picked from commit 3272759f25)
2019-07-17 07:46:58 -04:00
wizjany de2b673902 Minecarts spawn in the clicked (rail) block. 2019-07-09 08:02:01 -04:00
wizjany e4da479603 Unfix WORLDGUARD-3360.
There's a reason this wasn't done before. This is fundamentally broken.

(cherry picked from commit ab7751e046)
2019-07-02 23:15:07 -04:00
wizjany 76c3405311 Don't replace in comments and strings when you refactor...
(cherry picked from commit a9cd23c6ef)
2019-07-02 23:14:59 -04:00
wizjany eee75778a1 Add config to disable villagers getting zapped to witches.
"weather.disable-villager-witchification"
2019-07-01 07:44:15 -04:00
wizjany 254b85d178 Add TP button to /rg list where applicable. 2019-07-01 07:44:07 -04:00
wizjany 4ff42c81b5 Send CUI changes when using /rg select. 2019-07-01 07:43:58 -04:00
213 changed files with 3445 additions and 8865 deletions

No files matched your search

+1 -33
View File
@@ -1,34 +1,2 @@
* text=auto eol=lf
# Force Batch files to CRLF
*.bat eol=crlf -text
*.java diff=java
# Java sources
*.java text diff=java
*.kt text diff=java
*.gradle text diff=java
*.gradle.kts text diff=java
# These files are text and should be normalized (Convert crlf => lf)
*.css text diff=css
*.df text
*.htm text diff=html
*.html text diff=html
*.js text
*.jsp text
*.jspf text
*.jspx text
*.properties text
*.tld text
*.tag text
*.tagx text
*.xml text
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.dll binary
*.ear binary
*.jar binary
*.so binary
*.war binary
*.jks binary
-1
View File
@@ -1 +0,0 @@
github: enginehub
-93
View File
@@ -1,93 +0,0 @@
name: Bug report
description: Report a way in which WorldGuard is not working as intended
labels: ['type:bug', 'status:pending']
body:
- type: markdown
attributes:
value: |
Please note that this is only for bugs, help with installation or other types of support should
be taken to the Discord Guild instead.
- type: input
attributes:
label: WorldEdit Version
description: The full version of WorldEdit, can be found by using `/we version`.
placeholder: e.g. 7.2.3 or 7.3.0-SNAPSHOT
validations:
required: true
- type: input
attributes:
label: WorldGuard Version
description: The full version of WorldGuard, can be found by using `/wg version`.
placeholder: e.g. 7.0.5 or 7.0.6-SNAPSHOT
validations:
required: true
- type: input
attributes:
label: Platform Version
description: |
The version of the platform you are on, i.e. Spigot or Paper.
Please ensure you are running up-to-date software before making a bug report.
Old versions, paper forks or hybrids will receive little to no support.
placeholder: e.g. git-Spigot-21fe707-e1ebe52, git-Paper-463
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Confirmations
description: Please confirm the following before submitting the bug. Your report will be closed if you are running hybrids or old software.
options:
- label: I am using the most recent Minecraft release.
required: true
- label: I am using a version of WorldEdit compatible with my Minecraft version.
required: true
- label: I am using a version of WorldGuard compatible with my Minecraft version.
required: true
- label: I am using the latest or recommended version of my platform software.
required: true
- label: I am NOT using a hybrid server, e.g. a server that combines Bukkit and Forge. Examples include Arclight, Mohist, and Cardboard.
required: true
- label: I am NOT using a fork of WorldEdit, such as FastAsyncWorldEdit (FAWE) or AsyncWorldEdit (AWE)
required: true
- type: textarea
attributes:
label: Bug Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: The behavior that you expected, instead of the bugged behavior that occurs.
validations:
required: true
- type: textarea
attributes:
label: Reproduction Steps
description: Steps to reproduce the behavior.
value: |
1. ...
2. ...
validations:
required: true
- type: input
attributes:
label: Optional WorldGuard-Report
description: Link to WorldGuard Region report for bugs with regions, received with `/wg report -p`
validations:
required: false
- type: textarea
attributes:
label: Anything Else?
description: Add any additional context you can provide below.
-5
View File
@@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: EngineHub Discord
url: https://discord.gg/EngineHub
about: Please ask and answer questions here.
@@ -1,35 +0,0 @@
name: Feature request
description: Suggest an idea for WorldGuard
labels: ['type:feature-request', 'status:pending']
body:
- type: textarea
attributes:
label: The Problem
description: >
What is making your WorldGuard experience sub-optimal? This should be something that
cannot be easily solved by existing WorldGuard features.
placeholder: It's hard to ... ; I'm unable to ...
validations:
required: true
- type: textarea
attributes:
label: A Solution
description: What is your proposed solution to the above problem?
validations:
required: true
- type: textarea
attributes:
label: Alternatives
description: |
Alternative solutions or workarounds to the problem.
You should also describe why these are not preferable to the given solution.
validations:
required: false
- type: textarea
attributes:
label: Anything Else?
description: Add any additional context you can provide below.
-48
View File
@@ -1,48 +0,0 @@
name: Gradle Build
on:
push:
branches:
- 'master'
- 'version/*'
pull_request:
merge_group:
jobs:
build:
name: Build WorldGuard on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v6
- name: Set up JDK
uses: actions/setup-java@v5
with:
java-version: 25
distribution: 'temurin'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
with:
cache-read-only: ${{ !(github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/version/')) }}
- name: Execute Gradle build
run: ./gradlew build -s
- uses: actions/upload-artifact@v6
name: Archive Reports
if: always()
with:
name: reports for ${{ matrix.os }}
path: '**/build/reports/**'
- uses: actions/upload-artifact@v6
name: Archive Logs
if: always()
with:
name: logs for ${{ matrix.os }}
path: '**/*.log'
-2
View File
@@ -15,5 +15,3 @@ dependency-reduced-pom.xml
.gradle/
**/build/
out/
scripts/
+7
View File
@@ -0,0 +1,7 @@
language: java
jdk:
- oraclejdk8
notifications:
email: false
before_install: chmod +x gradlew
script: ./gradlew build -S
-230
View File
@@ -1,235 +1,5 @@
# Changelog
## 7.0.18
* Add lava-harden flag for cobblestone/stone/obsidian/basalt forming.
* Replace PigZapEvent on Paper to avoid startup warnings.
* Avoid unnecessary NPC checks to improve performance in some situations.
* Filtered "multiple regions" messages in commands to only show regions that the player has permission to use the command on.
* Fixed potential corruption that can occur in extreme region / slow hardware setups where it hasn't finished saving by the next save attempt.
## 7.0.17
* Fix cocoa not being treated as a crop in relevant flags.
* Fix overlapping game mode flags sometimes not storing the expected previous game mode.
* Replace PaperLib functionality that doesn't behave as expected on MC 26.1+.
## 7.0.16
* Update to 1.21.11.
* Added experimental Folia support.
* Workaround an issue where some item/block names aren't adequately translated by the client.
* Workaround a duplication bug in Paper.
## 7.0.15
* Update to 1.21.10
* Improve region file loading compatibility with NIO Java APIs
## 7.0.14
* Update to 1.21.5
* Fix hopper minecarts not being able to take items from containers in protected regions.
* Fix hopper minecarts not being able to take items from other hopper minecarts in protected regions.
* Fix non-members being able to leash boats in protected regions.
* Use new knockback event on Paper servers to better handle mace knockback in pvp and some other knockback situations.
## 7.0.13
* Update to 1.21.4
* Remove max-stack-size bypass in stack command
* Fix a falling block metadata leak. (May still be problematic on Spigot, use Paper.)
* Fix flame enchant being blocked as entity damage on the arrow itself.
* More Paper-specific performance enhancements for hoppers.
* Fix block-windcharge-explosions config option not doing anything.
* Improvements to fishing rod protection.
* More aggressive vehicle protection (vehicle-destroy now needs to be allowed for various non-destructive damage).
* Move decorated pot usage from interact to chest-access.
## 7.0.12
* Fix a change in the default behavior of explosion flag handling.
## 7.0.11
* Add support for MC 1.21.
* Add wind-charge-burst flag which is checked along with `use` (for the interaction) or `pvp` (for the knockback).
* Add breeze-charge-explosion flag for breeze charges (i.e. from the mob, not player wind charges).
* Add moisture-change flag and config options.
* Fix an error if a player logged in to an unloaded world.
* Fix chest boat usage always being counted as ride.
* Consider potions thrown by mobs as mob-damage.
* Workaround spigot no longer sending block change events when a book is placed on a lectern.
* Improve accuracy of target blocks in blacklist/build-perms events.
## 7.0.10
* Add support for MC 1.20.5 and 1.20.6, drop support for other 1.20 versions
## 7.0.9
* Add support for MC 1.20, drop support for MC 1.19
* Made entities spawned via the `/summon` command get treated as plugin-spawned entities
* Add sniffer egg trample protection options
## 7.0.8
* Add support for MC 1.19
* Add skulk-growth flag and config option
* Add copper-fade flag
* Add data packs to report output
* Add protection for allay inventory slot
* Categorize allay item pickups under item-pickup flag
* Categorize dragon egg interaction (teleporting) as building
* Ignore most NPC-based actions for Player events
* Optimize handling of tamed animals where the owner was offline (Paper only)
* Optimize additional InventoryHolder accesses (Paper only)
* Fix an exception that occurred when plugins created portals with non-player entities
* Fix possible error when using Paper's entity origin API
* Update bstats and squirrelid libs
## 7.0.7
* Add rock-growth flag for budding amethyst and pointed dripstone.
* Add /rg migrateheights command. See https://worldguard.enginehub.org/en/latest/regions/commands/#migrate-region-heights
* Add regions.set-parent-on-claim config (set to a region id for /rg claim to automatically assign the parent region).
* Add `-i search` and `-s` flags to /rg list, -c to /rg teleport.
* Fix an error in blacklist logging caused by non-player actions (eg on-dispense)
* Treat unknown causes as known if using paper-entity-origin config option.
* Improve lightning strike handling from channeling tridents (PaperMC only).
* Ignore an error caused by lingering player references of offline players.
* Add red sand to no-physics-sand.
* Fix potion splash events being cancelled if no entities were affected.
## 7.0.6
* Add support for 1.17 blocks/items, drop support for 1.16.
* Add use-dripleaf flag for "toggling" big dripleaf blocks.
* Fix support for fully negative-height regions.
* Fix crop-growth config option.
* Be more rigorous with protecting blocks against dispenser behaviors.
* Fix handling of lingering splash potion effects.
* Handle other-explosion flag consistently for block-like entities (armor frames etc.)
* Allow inheriting values for all flags (previously wasn't used for things like teleport.)
* Region commands that defaulted to the region the player was standing in no longer check parents.
* Fix child regions being unlinked when redefining a parent region.
## 7.0.5
* Add a use-anvil flag and exclude it from the use flag (since they can break on use.)
* Add nonplayer-protection-domains flag which allows merging region borders from the perspective of pistons, saplings, etc.
* Expand crop-related options (crop-growth, etc) to sweet berry bushes, nether wart, and bamboo.
* Add a config option (`mobs.block-vehicle-entry`) to prevent non-players from entering vehicles.
* Add a UUID flag (for developers/API usage).
* Add map query methods with fallback flag (for developers/API usage).
* Add `on` and `off` optional arguments for `/rg toggle-bypass` command.
* Add additional timings info for session handlers.
* Fix sponge-simulation clearing NBT from blocks. Note that if you are using sponge simulation you should switch to something like CraftBook as the feature will be removed from WorldGuard in a future (major) version.
* Fix the `/rg` command showing up as unknown client-side to players without bypass perms.
* Fix error propagation from third-party flag loading causing WG to error.
* Fix a (harmless) exception that occurred when swapping armor slots to the offhand slot.
* Fix empty lines being sent on enderpearl/chorus-fruit teleport if the deny messages were empty.
* Fix an issue with falling blocks when using max-priority-association.
* Fix performance issues with third-party plugins querying protection for offline players.
* Fix dispensing shulkers over region boundaries.
* Fix iron door interaction being denied as if it were a regular door.
* Fix being able to enter/exit regions with the flag denied by using entity mounting functions in other plugins.
## 7.0.4 (including beta1)
* Add support for MC 1.16. Dropped support for previous versions.
* Add respawn-anchors flag mirroring the sleep flag (e.g. to prevent using respawn anchors to cause explosions in the overworld)
* Add nether vines to vine-growth flag.
* Add config option to disable the bypass permission cache.
* Fix water-flow flags not checking waterlogged blocks.
* Add config option to consider non-player causes (e.g. pistons, flowing water) to only be members of the highest priority region. This should be enabled for plots-within-city-like setups to prevent things in plots from modifying the city.
* Fix items dropping from falling blocks that were suppressed by other plugins.
* Add config option to block turtle egg trampling.
* Fix ride flag being checked on striders that didn't have saddles.
* Add config option to have /rg bypass toggled off on login.
* Developer changes: Methods taking names in Domains are now explicitly deprecated (was previously just a javadoc comment.); These will eventually be removed: there is no reason to use names over UUIDs. Offline players and NPCs alike have stable UUIDs.
* Also for developers; The new `com.sk89q.worldguard.protection.util.WorldEditRegionConverter` class has some useful static methods to convert to and from WorldEdit's Region and WorldGuard's ProtectedRegion classes.
## 7.0.3
* This is the last release supporting MC 1.14 and 1.15.
* Decouple chest-access flag from interact flag. IMPORTANT: If you relied on allowing players to access chests via setting
the interact flag to allow, you will now need to set the chest-access flag to allow instead (or as well). This does not
affect any setups where users were *not* supposed to be able to access chests and other inventories.
* Add natural-health-regen and natural-hunger-drain flags. Unlike the heal/feed flags, these can not restore or deplete health/hunger.
* Fix the interact flag allowing breaking of turtle eggs (now tied directly to block-trampling flag).
* Fix a memory leak that could occur with many many explosives.
* Add regions.titles-always-use-default-times config option. Set this to true if you use greeting/farewell titles and another plugin
makes the titles disappear too quickly.
* Add protection for cauldrons water level changing.
* Improve diagnostic hints and information, such as spawn protection warnings, flag colors in region info, etc.
* Fix waterlogged blocks bypassing water-flow flag.
* Workaround for a CraftBukkit change that made no-physics-sand/gravel non-functional.
* Workaround for CraftBukkit throttling move events.
* Track projectiles shot by dispensers.
* Allowed setting passthrough allow on global to unprotect it if members/owners are added.
* Add support for newer forge clients (FML2) in host keys.
* Allow using WorldEdit's `//world <worldname>` command to select a world for region commands. This removes the need to
use `-w <worldname>` in every command when running commands from console.
* Add a teleport-message flag, shown when using `/rg tp`.
* Add coral-fade flag, which prevents corals from drying when out of water.
* Fix spammy deny-message when walking over redstone ore with certain flag setups.
* Improve handling of interacting with various tools in hand that didn't modify blocks. (eg opening a chest with an axe in hand)
* Fix allow-all-interact option not being read from per-world configs.
* Fix misattribution of pets (eg wolves) in PvP.
* Improve performance of hopper checks when on recent builds of Paper.
* Add event-handling.break-hoppers-on-denied-move config option to prevent hoppers from being broken (but items still won't be moved).
* Note to developers using the WorldGuard API: If you specifically relied on flags such as greeting/farewell, deny-message, etc being
StringFlags, be warned that this will change in a future version to support JSON text components. Please plan accordingly.
## 7.0.2
* Update to MC 1.15. Still compatible with 1.14, and incompatible with 1.13, as before.
* Add an informational message when defining a region that overlaps vanilla spawn protection.
* Protect against pushing a piston with another piston on a region border.
* Protect against buckets in dispensers on region borders.
## 7.0.1
* Add `/rg toggle-bypass` command which temporarily turns off region bypassing until used again.
* More improvements to `/rg flag` and `/rg flags` commands.
* Fix some checks for adding owners to unclaimed regions.
* Fix an issue with time-/weather-lock flags when logging in to a region with the flag set.
* Fix cause tracking in vehicles (incl. breaking lilypads in a boat)
* Use async teleports on Paper.
* Include hopper minecarts in the ignore hoppers config setting.
* Add sugar cane and cacti to the crop-growth flag. Bamboo is also included pending Spigot throwing an event for it.
* Specifically track when players ignite creepers with flint and steel.
* Fix fuzziness when using bonemeal near a protected region.
* Fix color codes not applying in greeting, etc flags when placed after a newline (\n).
* Add applicable region information to `/wg report`.
* Fix pistons flag not applying to sticky pistons pulling blocks.
* Add some custom metrics for bStats.
* Everything in the RC/beta changelog below.
## 7.0.1 RC 2 (inc. beta 1)
* Due to breaking changes in important Bukkit API, this is not compatible with MC 1.13!
* Update to MC 1.14. Adds protection for new blocks, etc.
* To allow players to read from lecterns, but not take the book, flag interact allow, and then flag chest-access -g nonmembers deny.
* Add ravager-grief flag.
* Fix overprotection of unsaddled pigs with the ride flag.
* Fix lava fire defaulting to off (won't change existing configs).
* Fix damaged/chipped anvils not respecting use flag like regular anvils.
* Add on-equip blacklist event. Note that it is overprotective due to deficiencies in Bukkit API.
* Update WorldEdit CUI when using /rg select.
* Add config option to disable villagers getting zapped into witches. ("weather.disable-villager-witchification")
* Add entity support to interact-whitelist config option (use the Material of the corresponding item).
* Fix vehicle-place protecting the rails at the very top of region boundaries incorrectly.
* Fix for emptying buckets on waterloggable blocks.
* Whitelist all player -> player interactions (previously was spammy in pvp).
* Fix sleep flag not protecting against explosions in nether/end.
* Add config for the teleport-on-void to reset fall distance.
* Fix config options taking material lists requiring "minecraft:" namespace.
* Fix disallowed-lightning-blocks situationally not working.
* Fix errors that occurred when plugins used falling block entities with non-item materials.
* Add special support for Paper servers (papermc.io): Paper's API allows us to track who launched fireworks.
* Fireworks are now protected by default. On Paper servers, members can use them by default (to deal damage),
on non-Paper servers, flag firework-damage allow to revert to old behavior (everyone can deal damage with fireworks by default).
* Misc performance enhancements for Paper servers.
* Add 'regions.use-paper-entity-origin' as an experimental setting (default off) for Paper servers. Enabling it will make non-player entities be treated as members of the place they spawned, instead of their current location when flags are checked.
## 7.0.0
* Added support for MC 1.13, dropped support for previous versions.
* Added lots of interactive text in e.g. `/rg info` command.
-39
View File
@@ -1,39 +0,0 @@
Compiling
=========
You can compile WorldGuard as long as you have some version of Java greater than or equal to 25 installed.
Gradle will download JDK 25 specifically if needed, but it needs some version of Java to bootstrap from.
The build process uses Gradle, which you do *not* need to download. WorldGuard is a multi-module project with three modules:
* `worldguard-core` contains the WorldGuard API
* `worldguard-bukkit` is the Bukkit plugin
* `worldguard-libs` contains library relocations
## To compile...
### On Windows
1. **Shift** + **right click** the folder with WorldGuard's files and click "Open PowerShell window here".
2. `gradlew build`
### On Linux, BSD, or Mac OS X
1. In your terminal, navigate to the folder with WorldGuard's files (`cd /folder/of/worldguard/files`)
2. `./gradlew build`
## Then you will find...
You will find:
* The core WorldGuard API in **worldguard-core/build/libs**
* WorldGuard for Bukkit in **worldguard-bukkit/build/libs**
If you want to use WorldGuard, use the `-dist` version.
(The -dist version includes WorldGuard + necessary libraries.)
## Other commands
* `gradlew idea` will generate an [IntelliJ IDEA](http://www.jetbrains.com/idea/) module for each folder.
* `gradlew eclipse` will generate an [Eclipse](https://www.eclipse.org/downloads/) project for each folder.
+3 -1
View File
@@ -7,7 +7,9 @@ ask that you make note of the following guidelines.
* **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 16 for source and compilation.**
* **Target Java 6 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
-16
View File
@@ -1,16 +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/>.
+22 -19
View File
@@ -1,29 +1,31 @@
<h1>
<img src="worldguard-logo.svg" alt="WorldGuard" width="400" />
</h1>
# ![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
* Block creeper and wither block damage, falling damage, etc.;
* Disable fire spread, lava fire spread, ice formation, Endermen picking up blocks, etc.;
* Blacklist certain items and blocks so they can't be used;
* Warn moderators when certain items and blocks are used;
* Protect areas of your world so only certain people can build in them;
* Set areas where PVP, TNT, mob damage, and other features are disabled;
* Protect your server from various 'exploits' like magical obsidian creation machines;
* Disable, or enable, various Minecraft features, like sponges from classic;
* Add useful commands like an immediate "STOP ALL FIRE SPREAD" command.
* Enable only features you want! Everything is off by default.
WorldGuard is open source and is available under the GNU Lesser
General Public License v3.
A Bukkit server implementation (such as [Paper](https://papermc.io)) and the [WorldEdit plugin](https://dev.bukkit.org/projects/worldedit) are required to use WorldGuard. You can get a release copy of WorldGuard from the [BukkitDev site](https://dev.bukkit.org/projects/worldguard).
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
---------
See [COMPILING.md](COMPILING.md).
The project is written for Java 8 and our build process makes use of
[Gradle](http://gradle.org). Detailed compilation information
[can be found on the wiki](http://wiki.sk89q.com/wiki/WorldGuard/Development#Compiling).
Dependencies are automatically handled by Gradle.
Contributing
------------
@@ -37,8 +39,9 @@ Submissions must be licensed under the GNU Lesser General Public License v3.
Links
-----
* [Homepage](https://enginehub.org/worldguard)
* [Homepage](http://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](https://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [End-user documentation](https://worldguard.enginehub.org/en/latest/)
* [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://travis-ci.org/EngineHub/WorldGuard.svg?branch=master)](https://travis-ci.org/EngineHub/WorldGuard)
* [End-user documentation](https://worldguard.readthedocs.io/en/latest/) / [Older Wiki](http://wiki.sk89q.com/wiki/WorldGuard)
-37
View File
@@ -1,37 +0,0 @@
plugins {
`kotlin-dsl`
}
repositories {
maven {
name = "EngineHub"
url = uri("https://repo.enginehub.org/libs-release/")
}
mavenCentral()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation(libs.crankcase.java)
implementation(libs.crankcase.javaLibrary)
implementation(libs.crankcase.common)
implementation(libs.crankcase.licensing)
implementation(libs.crankcase.git)
implementation(libs.crankcase.publishing)
implementation(libs.shadow)
implementation(libs.gson)
constraints {
val asmVersion = "[${libs.versions.minimumAsm.get()},)"
implementation("org.ow2.asm:asm:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.ow2.asm:asm-commons:$asmVersion") {
because("Need Java 21 support in shadow")
}
implementation("org.vafer:jdependency:[${libs.versions.minimumJdependency.get()},)") {
because("Need Java 21 support in shadow")
}
}
}
-9
View File
@@ -1,9 +0,0 @@
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}
rootProject.name = "build-logic"
@@ -1,4 +0,0 @@
plugins {
id("org.enginehub.crankcase.java-library")
id("buildlogic.common-java")
}
@@ -1,29 +0,0 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
plugins {
id("eclipse")
id("idea")
id("checkstyle")
id("org.enginehub.crankcase.java")
id("buildlogic.common")
}
crankcaseJava {
javaRelease = 25
disabledLints = listOf("processing", "path", "fallthrough", "serial", "overloads")
}
tasks.withType<JavaCompile>().configureEach {
// TODO Remove this when we're able
options.compilerArgs.remove("-Werror")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "10.16.0"
}
dependencies {
"compileOnly"(stringyLibs.getLibrary("jsr305"))
}
@@ -1,35 +0,0 @@
import buildlogic.getLibrary
import buildlogic.stringyLibs
plugins {
id("org.enginehub.crankcase.common")
id("org.enginehub.crankcase.licensing")
id("org.enginehub.crankcase.git")
}
group = rootProject.group
version = rootProject.version
dependencies {
for (conf in listOf("implementation", "api")) {
if (!configurations.names.contains(conf)) {
continue
}
add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map {
val dep = create(it)
dep.because("Mojang provides Log4j")
dep
})
constraints {
add(conf, stringyLibs.getLibrary("guava")) {
because("Mojang provides Guava")
}
add(conf, stringyLibs.getLibrary("gson")) {
because("Mojang provides Gson")
}
add(conf, stringyLibs.getLibrary("fastutil")) {
because("Mojang provides FastUtil")
}
}
}
}
@@ -1,20 +0,0 @@
plugins {
id("maven-publish")
id("buildlogic.common-java-library")
id("org.enginehub.crankcase.publishing")
}
publishing {
publications {
register<MavenPublication>("maven") {
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
@@ -1,178 +0,0 @@
plugins {
id("java-base")
id("maven-publish")
id("com.gradleup.shadow")
id("buildlogic.common")
id("org.enginehub.crankcase.publishing")
}
// A horrible hack because `softwareComponentFactory` has to be gotten via plugin
// gradle why
internal open class LibsConfigPluginHack @Inject constructor(
private val softwareComponentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(project: Project) {
val libsComponents = softwareComponentFactory.adhoc("libs")
project.components.add(libsComponents)
}
}
configurations {
create("shade")
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile",
)
tasks.register<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
// Yeet module-info's
exclude("module-info.class")
dependencies {
exclude(dependency("com.google.guava:guava"))
exclude(dependency("com.google.code.gson:gson"))
exclude(dependency("com.google.errorprone:error_prone_annotations"))
exclude(dependency("com.google.guava:failureaccess"))
exclude(dependency("org.checkerframework:checker-qual"))
exclude(dependency("org.jetbrains:annotations"))
exclude(dependency("org.apache.logging.log4j:log4j-api"))
exclude(dependency("com.google.code.findbugs:jsr305"))
exclude {
it.moduleGroup == "org.jetbrains.kotlin"
}
}
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
.filterIsInstance<ModuleDependency>()
.map { it.copy() }
.map { dependency ->
val category = dependency.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name
if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) {
return@map dependency
}
try {
dependency.artifact {
name = dependency.name
type = artifactType
extension = "jar"
classifier = artifactType
}
} catch (e: Exception) {
throw RuntimeException("Failed to add artifact to dependency: $dependency", e)
}
dependency
}
files(configurations.detachedConfiguration(*deps.toTypedArray())
.resolvedConfiguration.lenientConfiguration.artifacts
.filter { it.classifier == artifactType }
.map { zipTree(it.file) })
}
tasks.register<Jar>("sourcesJar") {
from({
altConfigFiles("sources")
})
// Yeet module-info's
exclude("module-info.java")
relocations.forEach { (from, to) ->
val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)")
val textPattern = Regex.fromLiteral(from)
eachFile {
filter {
it.replaceFirst(textPattern, to)
}
path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2")
}
}
archiveClassifier.set("sources")
}
tasks.named("assemble").configure {
dependsOn("jar", "sourcesJar")
}
project.apply<LibsConfigPluginHack>()
val libsComponent = project.components["libs"] as AdhocComponentWithVariants
val apiElements = project.configurations.register("apiElements") {
isVisible = false
description = "API elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 25)
}
outgoing.artifact(tasks.named("jar"))
}
val runtimeElements = project.configurations.register("runtimeElements") {
isVisible = false
description = "Runtime elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 25)
}
outgoing.artifact(tasks.named("jar"))
}
val sourcesElements = project.configurations.register("sourcesElements") {
isVisible = false
description = "Source elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES))
}
outgoing.artifact(tasks.named("sourcesJar"))
}
libsComponent.addVariantsFromConfiguration(apiElements.get()) {
mapToMavenScope("compile")
}
libsComponent.addVariantsFromConfiguration(runtimeElements.get()) {
mapToMavenScope("runtime")
}
libsComponent.addVariantsFromConfiguration(sourcesElements.get()) {
mapToMavenScope("runtime")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(libsComponent)
}
}
}
if (project != project(":worldguard-libs:core")) {
evaluationDependsOn(":worldguard-libs:core")
configurations["shade"].shouldResolveConsistentlyWith(project(":worldguard-libs:core").configurations["shade"])
}
@@ -1,38 +0,0 @@
plugins {
id("com.gradleup.shadow")
id("buildlogic.core-and-platform")
}
shadow {
addShadowVariantIntoJavaComponent = false
}
tasks.named<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
include(project(":worldguard-libs:core"))
include(project(":worldguard-core"))
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core"))
}
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
exclude("META-INF/maven/**")
minimize()
}
afterEvaluate {
tasks.named<Jar>("jar") {
val version = project(":worldguard-core").version
inputs.property("version", version)
val attributes = mutableMapOf(
"Implementation-Version" to version,
"WorldGuard-Version" to version,
)
manifest.attributes(attributes)
}
}
@@ -1,32 +0,0 @@
package buildlogic
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.artifacts.VersionConstraint
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.provider.Provider
import org.enginehub.crankcase.git.GitExtension
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.stringyLibs: VersionCatalog
get() = extensions.getByType<VersionCatalogsExtension>().named("libs")
val Project.internalVersion: Provider<String>
get() {
val version = version.toString()
return the<GitExtension>().commitHash.map { "$version+$it" }
}
fun VersionCatalog.getLibrary(name: String): Provider<MinimalExternalModuleDependency> = findLibrary(name).orElseThrow {
error("Library $name not found in version catalog")
}
fun VersionCatalog.getVersion(name: String): VersionConstraint = findVersion(name).orElseThrow {
error("Version $name not found in version catalog")
}
+136
View File
@@ -0,0 +1,136 @@
println """
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Read COMPILING.md if you haven't yet
2) Try running 'build' in a separate Gradle run
3) Use gradlew and not gradle
4) If you still need help, ask on IRC! irc.esper.net #sk89q
Output files will be in [subproject]/build/libs
*******************************************
"""
buildscript {
repositories {
mavenCentral()
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" }
jcenter()
}
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:21.0'
}
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:4.0.3"
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.7.5'
classpath 'org.ajoberstar:gradle-git:1.7.2'
}
}
allprojects {
group = 'com.sk89q.worldguard'
version = '7.0.1-SNAPSHOT'
}
if (!project.hasProperty("artifactory_contextUrl")) ext.artifactory_contextUrl = "http://localhost"
if (!project.hasProperty("artifactory_user")) ext.artifactory_user = "guest"
if (!project.hasProperty("artifactory_password")) ext.artifactory_password = ""
if (!project.hasProperty("gitCommitHash")) {
try {
def repo = org.ajoberstar.grgit.Grgit.open(project.file('.'))
ext.gitCommitHash = repo.head().abbreviatedId
} catch (Exception e) {
ext.gitCommitHash = "no_git_id"
}
}
apply plugin: 'com.jfrog.artifactory'
artifactory {
contextUrl = "${artifactory_contextUrl}"
publish {
repository {
repoKey = project.version.contains("SNAPSHOT") ? 'libs-snapshot-local' : 'libs-release-local'
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
}
}
artifactoryPublish.skip = true
subprojects {
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'maven'
apply plugin: 'checkstyle'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'com.jfrog.artifactory'
ext.internalVersion = version + ";" + gitCommitHash
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
checkstyle.configFile = new File(rootProject.projectDir, "config/checkstyle/checkstyle.xml")
checkstyle.toolVersion = '7.6.1'
repositories {
mavenLocal()
mavenCentral()
maven { url "https://repo.spongepowered.org/maven/" }
maven { url "https://hub.spigotmc.org/nexus/content/groups/public" }
maven { url "https://maven.sk89q.com/repo/" }
maven { url "https://repo.maven.apache.org/maven2" }
}
if (JavaVersion.current().isJava8Compatible()) {
// Java 8 turns on doclint which we fail
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives jar
archives sourcesJar
archives javadocJar
}
build.dependsOn(checkstyleMain)
build.dependsOn(checkstyleTest)
build.dependsOn(sourcesJar)
build.dependsOn(javadocJar)
shadowJar {
classifier 'dist'
dependencies {
include(dependency('org.khelekore:prtree:1.5.0'))
include(dependency('com.sk89q:squirrelid:0.2.0'))
include(dependency('org.flywaydb:flyway-core:3.0'))
}
exclude 'GradleStart**'
exclude '.cache'
exclude 'LICENSE*'
}
artifactoryPublish {
publishConfigs('archives')
}
}
-3
View File
@@ -1,3 +0,0 @@
plugins {
id("buildlogic.common")
}
@@ -1,86 +0,0 @@
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.withType
fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, javaRelease: Int = 8, banSlf4j: Boolean = true) {
applyCommonConfiguration()
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "checkstyle")
tasks
.withType<JavaCompile>()
.matching { it.name == "compileJava" || it.name == "compileTestJava" }
.configureEach {
val disabledLint = listOf(
"processing", "path", "fallthrough", "serial"
)
options.release.set(javaRelease)
options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" })
options.isDeprecation = true
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
}
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "9.1"
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:${Versions.FINDBUGS}")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
options.encoding = "UTF-8"
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
configure<JavaPluginExtension> {
disableAutoTargetJvm()
withJavadocJar()
if (sourcesJar) {
withSourcesJar()
}
}
if (banSlf4j) {
configurations["compileClasspath"].apply {
resolutionStrategy.componentSelection {
withModule("org.slf4j:slf4j-api") {
reject("No SLF4J allowed on compile classpath")
}
}
}
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
}
+8 -4
View File
@@ -7,11 +7,9 @@
<module name="FileTabCharacter"/>
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/suppressions.xml"/>
<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 -->
@@ -22,7 +20,7 @@
It is a bit draconian, so update as necessary!
-->
<module name="ImportControl">
<property name="file" value="${config_loc}/import-control.xml"/>
<property name="file" value="${basedir}/config/checkstyle/import-control.xml"/>
</module>
<!-- Code -->
@@ -60,4 +58,10 @@
<!-- <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>
@@ -16,11 +16,3 @@
* 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.registry;
public class DomainConflictException extends RuntimeException {
public DomainConflictException(String message) {
super(message);
}
}
+12 -11
View File
@@ -7,6 +7,7 @@
<allow pkg="javax"/>
<allow pkg="org.junit"/>
<allow pkg="org.hamcrest"/>
<allow pkg="org.mockito"/>
<allow pkg="junit.framework"/>
<allow pkg="com.sk89q"/>
<allow pkg="com.google.common"/>
@@ -15,24 +16,24 @@
<allow pkg="org.khelekore"/>
<allow pkg="org.flywaydb"/>
<allow pkg="org.yaml"/>
<allow pkg="org.json"/>
<allow pkg="org.enginehub.piston"/>
<subpackage name="util.profile.resolver">
<allow pkg="org.bukkit"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
</subpackage>
<subpackage name="bukkit">
<allow pkg="org.bukkit"/>
<allow pkg="org.bstats.bukkit"/>
<allow pkg="org.bstats.charts"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
<allow pkg="io.papermc.paper"/>
<allow pkg="org.spigotmc" />
</subpackage>
<subpackage name="sponge">
<allow pkg="org.spongepowered"/>
<allow pkg="org.bstats.sponge"/>
<allow pkg="com.flowpowered"/>
</subpackage>
<subpackage name="forge">
<allow pkg="net.minecraft"/>
<allow pkg="net.minecraftforge"/>
</subpackage>
</subpackage>
</import-control>
-4
View File
@@ -1,4 +0,0 @@
group=com.sk89q.worldguard
version=7.1.0-SNAPSHOT
org.gradle.parallel=true
-2
View File
@@ -1,2 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainVersion=25
-65
View File
@@ -1,65 +0,0 @@
[versions]
worldedit = "7.4.4"
crankcase = "0.1.0"
# Minimum versions we apply to make dependencies support newer Java
minimumAsm = "9.7"
minimumJdependency = "2.10"
minimumTinyRemapper = "0.8.11"
# lang-version = ""
[libraries]
crankcase-java = { module = "org.enginehub.crankcase:java", version.ref = "crankcase" }
crankcase-javaLibrary = { module = "org.enginehub.crankcase:java-library", version.ref = "crankcase" }
crankcase-common = { module = "org.enginehub.crankcase:common", version.ref = "crankcase" }
crankcase-licensing = { module = "org.enginehub.crankcase:licensing", version.ref = "crankcase" }
crankcase-git = { module = "org.enginehub.crankcase:git", version.ref = "crankcase" }
crankcase-publishing = { module = "org.enginehub.crankcase:publishing", version.ref = "crankcase" }
shadow = "com.gradleup.shadow:com.gradleup.shadow.gradle.plugin:9.3.2"
squirrelid = "org.enginehub:squirrelid:0.3.2"
autoService = "com.google.auto.service:auto-service:1.1.1"
jsr305 = "com.google.code.findbugs:jsr305:3.0.2"
jetbrains-annotations = "org.jetbrains:annotations:24.1.0"
paperApi = "io.papermc.paper:paper-api:26.2.build.+"
paperLib = "io.papermc:paperlib:1.0.8"
dummypermscompat = "com.sk89q:dummypermscompat:1.10"
bstats-bukkit = "org.bstats:bstats-bukkit:3.2.1"
prtree = "org.khelekore:prtree:1.5.0"
flyway-core = "org.flywaydb:flyway-core:3.0"
commandbook = "com.sk89q:commandbook:2.3"
hamcrest-library = "org.hamcrest:hamcrest-library:2.2"
# Mojang-provided libraries, CHECK AGAINST MINECRAFT for versions
guava = "com.google.guava:guava:33.6.0-jre"
log4j-bom = "org.apache.logging.log4j:log4j-bom:2.25.2"
gson = "com.google.code.gson:gson:2.14.0"
fastutil = "it.unimi.dsi:fastutil:8.5.18"
# Bukkit-provided libraries, CHECK AGAINST SPIGOT for versions
# Note that we need to balance support for older MC versus working at all on newer ones, so the exact versions here
# may not be the same as the ones in the latest Bukkit API.
snakeyaml = "org.yaml:snakeyaml:2.0"
[libraries.worldedit-core]
module = "com.sk89q.worldedit:worldedit-core"
version.ref = "worldedit"
[libraries.worldedit-bukkit]
module = "com.sk89q.worldedit:worldedit-bukkit"
version.ref = "worldedit"
[libraries.worldedit-libs-ap]
module = "com.sk89q.worldedit.worldedit-libs:ap"
version.ref = "worldedit"
Binary file not shown.
+1 -5
View File
@@ -1,9 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+115 -192
View File
@@ -1,127 +1,78 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#!/usr/bin/env sh
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
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
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
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
MAX_FD="maximum"
warn () {
echo "$*"
} >&2
}
die () {
echo
echo "$*"
echo
exit 1
} >&2
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
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
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD=$JAVA_HOME/bin/java
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -130,120 +81,92 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
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
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
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
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
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 "$@")
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command, 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"
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
# 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
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+34 -42
View File
@@ -1,20 +1,4 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,29 +9,25 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
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% equ 0 goto execute
if "%ERRORLEVEL%" == "0" goto init
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
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
@@ -55,36 +35,48 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
if exist "%JAVA_EXE%" goto init
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
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 %*
"%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% equ 0 goto mainEnd
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!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
+3
View File
@@ -0,0 +1,3 @@
rootProject.name = 'worldguard'
include 'worldguard-core', 'worldguard-bukkit'
-82
View File
@@ -1,82 +0,0 @@
pluginManagement {
// pluginManagement repositories resolve plugins before the repo-reconfiguration plugin can
// apply, so they must point at EngineHub mirrors directly rather than upstream URLs.
repositories {
maven {
name = "EngineHub"
url = uri("https://repo.enginehub.org/libs-release/")
mavenContent {
releasesOnly()
includeGroupAndSubgroups("com.sk89q")
includeGroupAndSubgroups("org.enginehub")
}
}
maven {
name = "EngineHub Maven Central Mirror"
url = uri("https://repo.enginehub.org/internal/maven-central-proxy/")
mavenContent {
releasesOnly()
}
}
maven {
name = "EngineHub Gradle Plugin Portal Mirror"
url = uri("https://repo.enginehub.org/internal/plugin-portal-proxy/")
mavenContent {
releasesOnly()
}
}
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
id("org.enginehub.crankcase.repo-reconfiguration") version "0.1.0"
}
dependencyResolutionManagement {
repositories {
maven {
name = "PaperMC"
url = uri("https://repo.papermc.io/repository/maven-public/")
}
maven {
name = "EngineHub (Non-Mirrored)"
url = uri("https://repo.enginehub.org/libs-release/")
}
maven {
name = "EngineHub Legacy Third-Party"
url = uri("https://repo.enginehub.org/artifactory/libs-release/")
content {
includeGroup("org.khelekore")
}
}
mavenCentral()
maven {
name = "Minecraft Libraries"
url = uri("https://libraries.minecraft.net/")
}
}
}
logger.lifecycle("""
*******************************************
You are building WorldGuard!
If you encounter trouble:
1) Read COMPILING.md if you haven't yet
2) Try running 'build' in a separate Gradle run
3) Use gradlew and not gradle
4) If you still need help, ask on Discord! https://discord.gg/enginehub
Output files will be in [subproject]/build/libs
*******************************************
""")
rootProject.name = "worldguard"
includeBuild("build-logic")
include("worldguard-libs")
include("worldguard-libs:core")
listOf("bukkit", "core").forEach {
include("worldguard-$it")
}
+55
View File
@@ -0,0 +1,55 @@
apply plugin: 'eclipse'
apply plugin: 'idea'
repositories {
maven {
name = 'bstats repo'
url = 'https://repo.codemc.org/repository/maven-public'
}
}
dependencies {
compile project(path: ':worldguard-core', configuration: 'shadow')
api 'org.bukkit:bukkit:1.13-R0.1-SNAPSHOT'
api ('com.sk89q.worldedit:worldedit-bukkit:7.0.1-SNAPSHOT') {
exclude group: 'io.papermc', module: 'paperlib'
}
implementation ('com.sk89q:commandbook:2.3') {
exclude group: 'com.sk89q', module: 'worldedit'
exclude group: 'com.zachsthings.libcomponents'
exclude group: 'org.bukkit'
exclude group: 'net.sf.opencsv'
}
implementation 'org.bstats:bstats-bukkit:1.5'
}
processResources {
from (sourceSets.main.resources.srcDirs) {
expand project.properties
include 'plugin.yml'
}
from (sourceSets.main.resources.srcDirs) {
exclude 'plugin.yml'
}
}
jar {
manifest {
attributes("Implementation-Version": version)
}
}
shadowJar {
dependencies {
include(dependency(':worldguard-core'))
relocate ("org.bstats", "com.sk89q.worldguard.bukkit.bstats") {
include(dependency("org.bstats:bstats-bukkit:1.5"))
}
}
relocate('org.flywaydb', 'com.sk89q.worldguard.internal.flywaydb')
}
build.dependsOn(shadowJar)
-56
View File
@@ -1,56 +0,0 @@
import buildlogic.internalVersion
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id("buildlogic.platform")
}
dependencies {
"api"(project(":worldguard-core"))
"api"(libs.worldedit.bukkit) { isTransitive = false }
"compileOnly"(libs.commandbook) { isTransitive = false }
"compileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"testCompileOnly"(libs.jetbrains.annotations) {
because("Resolving Spigot annotations")
}
"compileOnly"(libs.paperApi) {
exclude("org.slf4j", "slf4j-api")
exclude("junit", "junit")
}
"implementation"(libs.paperLib)
"implementation"(libs.bstats.bukkit)
}
tasks.named<Copy>("processResources") {
val internalVersion = project.internalVersion
inputs.property("internalVersion", internalVersion)
filesMatching("plugin.yml") {
expand("internalVersion" to internalVersion.get())
}
}
tasks.named<ShadowJar>("shadowJar") {
dependencies {
include(dependency(":worldguard-core"))
include(dependency("org.bstats:bstats-bukkit"))
include(dependency("org.bstats:bstats-base"))
include(dependency("io.papermc:paperlib"))
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats")
relocate("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib")
}
}
tasks.named("assemble").configure {
dependsOn("shadowJar")
}
configure<PublishingExtension> {
publications.named<MavenPublication>("maven") {
from(components["java"])
}
}
@@ -26,7 +26,6 @@ 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;
@@ -36,7 +35,6 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
@Unreported private ConcurrentMap<String, BukkitWorldConfiguration> worlds = new ConcurrentHashMap<>();
private boolean hasCommandBookGodMode;
boolean extraStats;
/**
* Construct the object.
@@ -48,16 +46,6 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
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();
@@ -80,7 +68,6 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
for (World world : WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds()) {
get(world);
}
getConfig().save();
}
/**
@@ -92,10 +79,6 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
@Override
public BukkitWorldConfiguration get(World world) {
String worldName = world.getName();
return get(worldName);
}
public BukkitWorldConfiguration get(String worldName) {
BukkitWorldConfiguration config = worlds.get(worldName);
BukkitWorldConfiguration newConfig = null;
@@ -103,8 +86,8 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
if (newConfig == null) {
newConfig = new BukkitWorldConfiguration(plugin, worldName, this.getConfig());
}
worlds.putIfAbsent(worldName, newConfig);
config = worlds.get(worldName);
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
}
return config;
@@ -24,10 +24,6 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.util.PaperInterop;
import com.sk89q.worldguard.util.MessagingUtil;
import io.papermc.lib.PaperLib;
import org.bukkit.BanList.Type;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -124,8 +120,7 @@ public class BukkitPlayer extends com.sk89q.worldedit.bukkit.BukkitPlayer implem
@Override
public WeatherType getPlayerWeather() {
org.bukkit.WeatherType playerWeather = getPlayer().getPlayerWeather();
return playerWeather == null ? null : playerWeather == org.bukkit.WeatherType.CLEAR ? WeatherTypes.CLEAR : WeatherTypes.RAIN;
return null;
}
@Override
@@ -175,32 +170,7 @@ public class BukkitPlayer extends com.sk89q.worldedit.bukkit.BukkitPlayer implem
@Override
public void sendTitle(String title, String subtitle) {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(getWorld()).forceDefaultTitleTimes) {
getPlayer().sendTitle(title, subtitle, 10, 70, 20);
} else {
getPlayer().sendTitle(title, subtitle, -1, -1, -1);
}
}
@Override
public void resetFallDistance() {
getPlayer().setFallDistance(0);
}
@Override
public void teleport(Location location, String successMessage, String failMessage) {
PaperInterop.teleportAsync(getPlayer(), BukkitAdapter.adapt(location))
.thenApply(success -> {
if (success) {
// The success message can be cleared via flag
if (!successMessage.isEmpty()) {
MessagingUtil.sendStringToChat(this, successMessage);
}
} else {
printError(failMessage);
}
return success;
});
getPlayer().sendTitle(title, subtitle, -1, -1, -1);
}
@Override
@@ -40,7 +40,6 @@ import org.bukkit.event.world.WorldUnloadEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nullable;
@@ -63,7 +62,6 @@ public class BukkitRegionContainer extends RegionContainer {
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void initialize() {
super.initialize();
Bukkit.getPluginManager().registerEvents(new Listener() {
@@ -96,20 +94,7 @@ public class BukkitRegionContainer extends RegionContainer {
}
}, plugin);
if (WorldGuardPlugin.inst().isFolia()) {
Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, new Consumer() {
@Override
public void accept(Object ignored) {
cache.invalidateAll();
}
}, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
} else {
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, cache::invalidateAll, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
}
}
public void shutdown() {
container.shutdown();
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, cache::invalidateAll, CACHE_INVALIDATION_INTERVAL, CACHE_INVALIDATION_INTERVAL);
}
@Override
@@ -55,6 +55,23 @@ public class BukkitUtil {
return item.getDurability() & 0x3F;
}
/**
* Get a blacklist target for the given block.
*
* @param block the block
* @param effectiveMaterial The effective material, if different
* @return a target
*/
public static Target createTarget(Block block, Material effectiveMaterial) {
checkNotNull(block);
checkNotNull(block.getType());
if (block.getType() == effectiveMaterial) {
return createTarget(block.getType());
} else {
return createTarget(effectiveMaterial);
}
}
/**
* Get a blacklist target for the given block.
*
@@ -40,7 +40,7 @@ import com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.config.YamlWorldConfiguration;
import org.bukkit.potion.PotionEffectType;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.parser.ParserException;
import java.io.File;
import java.io.FileNotFoundException;
@@ -70,7 +70,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
public Set<PotionEffectType> blockPotions;
public TargetMatcherSet allowAllInteract;
public TargetMatcherSet blockUseAtFeet;
public boolean usePaperEntityOrigin;
/* Configuration data end */
/**
@@ -105,13 +104,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
if (inputs == null || inputs.isEmpty()) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
inputs = config.getStringList(node, null);
}
if (inputs == null || inputs.isEmpty()) {
return set;
}
@@ -135,13 +127,11 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
config.load();
} catch (IOException e) {
log.log(Level.SEVERE, "Error reading configuration for world " + worldName + ": ", e);
} catch (YAMLException e) {
} catch (ParserException e) {
log.severe("Error parsing configuration for world " + worldName + ". ");
throw e;
}
boolean needParentSave = false;
summaryOnStart = getBoolean("summary-on-start", true);
opPermissions = getBoolean("op-permissions", true);
@@ -153,17 +143,11 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
allowAllInteract = getTargetMatchers("event-handling.interaction-whitelist");
blockUseAtFeet = getTargetMatchers("event-handling.emit-block-use-at-feet");
ignoreHopperMoveEvents = getBoolean("event-handling.ignore-hopper-item-move-events", false);
breakDeniedHoppers = getBoolean("event-handling.break-hoppers-on-denied-move", true);
usePaperEntityOrigin = getBoolean("regions.use-paper-entity-origin", false);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
needParentSave |= removeProperty("protection.disable-obsidian-generators");
useMaxPriorityAssociation = getBoolean("protection.use-max-priority-association", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
blockPotions = new HashSet<>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
@@ -181,11 +165,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
simulateSponge = getBoolean("simulation.sponge.enable", false);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
if (simulateSponge) {
log.warning("Sponge simulation is deprecated for removal in a future version. We recommend using CraftBook's sponge simulation instead.");
} else {
needParentSave |= removeProperty("simulation");
}
pumpkinScuba = getBoolean("default.pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
@@ -215,7 +194,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
blockWindChargeExplosions = getBoolean("mobs.block-windcharge-explosions", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
allowTamedSpawns = getBoolean("mobs.allow-tamed-spawns", true);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
@@ -227,7 +205,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
blockGroundSlimes = getBoolean("mobs.block-above-ground-slimes", false);
blockOtherExplosions = getBoolean("mobs.block-other-explosions", false);
blockZombieDoorDestruction = getBoolean("mobs.block-zombie-door-destruction", false);
blockEntityVehicleEntry = getBoolean("mobs.block-vehicle-entry", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -239,27 +216,16 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
teleportOnSuffocation = getBoolean("player-damage.teleport-on-suffocation", false);
disableVoidDamage = getBoolean("player-damage.disable-void-damage", false);
teleportOnVoid = getBoolean("player-damage.teleport-on-void-falling", false);
safeFallOnVoid = getBoolean("player-damage.reset-fall-on-void-teleport", false);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
disableDeathMessages = getBoolean("player-damage.disable-death-messages", false);
signChestProtection = getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", true);
if (signChestProtection) {
log.warning("Sign-based chest protection is deprecated for removal in a future version. See https://worldguard.enginehub.org/en/latest/chest-protection/ for details.");
} else {
needParentSave |= removeProperty("chest-protection");
}
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", false);
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disableCreatureTurtleEggTrampling = getBoolean("turtle-egg.disable-creature-trampling", false);
disablePlayerTurtleEggTrampling = getBoolean("turtle-egg.disable-player-trampling", false);
disableCreatureSnifferEggTrampling = getBoolean("sniffer-egg.disable-creature-trampling", false);
disablePlayerSnifferEggTrampling = getBoolean("sniffer-egg.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<>(convertLegacyBlocks(getStringList("weather.prevent-lightning-strike-blocks", null)));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
@@ -279,21 +245,14 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-growth", false);
disableRockGrowth = getBoolean("dynamics.disable-rock-growth", false);
disableSculkGrowth = getBoolean("dynamics.disable-sculk-growth", false);
disableCropGrowth = getBoolean("dynamics.disable-crop-growth", false);
disableSoilDehydration = getBoolean("dynamics.disable-soil-dehydration", false);
disableSoilMoistureChange = getBoolean("dynamics.disable-soil-moisture-change", false);
disableCoralBlockFade = getBoolean("dynamics.disable-coral-block-fade", false);
disableCopperBlockFade = getBoolean("dynamics.disable-copper-block-fade", false);
disableLavaHarden = getBoolean("dynamics.disable-lava-harden", false);
allowedSnowFallOver = new HashSet<>(convertLegacyBlocks(getStringList("dynamics.snow-fall-blocks", null)));
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
regionCancelEmptyChatEvents = getBoolean("regions.cancel-chat-without-recipients", true);
regionNetherPortalProtection = getBoolean("regions.nether-portal-protection", true);
forceDefaultTitleTimes = config.getBoolean("regions.titles-always-use-default-times", true); // note: technically not region-specific, but we only use it for the title flags
regionNetherPortalProtection = getBoolean("regions.nether-portal-protection", false);
fakePlayerBuildOverride = getBoolean("regions.fake-player-build-override", true);
explosionFlagCancellation = getBoolean("regions.explosion-flags-block-entity-damage", true);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
@@ -301,7 +260,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
regionWand = convertLegacyItem(getString("regions.wand", ItemTypes.LEATHER.getId()));
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
setParentOnClaim = getString("regions.set-parent-on-claim", "");
boundedLocationFlags = getBoolean("regions.location-flags-only-inside-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
@@ -423,20 +381,6 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
config.setHeader(CONFIG_HEADER);
config.save();
if (needParentSave) {
parentConfig.save();
}
}
private boolean removeProperty(String prop) {
if (config.getProperty(prop) != null) {
config.removeProperty(prop);
}
if (parentConfig.getProperty(prop) != null) {
parentConfig.removeProperty(prop);
return true;
}
return false;
}
public boolean isChestProtected(Location block, LocalPlayer player) {
@@ -19,22 +19,14 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.report.ReportList;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.profile.resolver.PaperPlayerService;
import com.sk89q.worldguard.bukkit.protection.events.flags.FlagContextCreateEvent;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.report.DatapackReport;
import com.sk89q.worldguard.bukkit.util.report.PerformanceReport;
import com.sk89q.worldguard.bukkit.util.report.PluginReport;
import com.sk89q.worldguard.bukkit.util.report.SchedulerReport;
@@ -47,28 +39,19 @@ import com.sk89q.worldguard.internal.platform.WorldGuardPlatform;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.session.SessionManager;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import com.sk89q.worldguard.util.profile.resolver.BukkitPlayerService;
import com.sk89q.worldguard.util.profile.resolver.CacheForwardingService;
import com.sk89q.worldguard.util.profile.resolver.CombinedProfileService;
import com.sk89q.worldguard.util.profile.resolver.HttpRepositoryService;
import com.sk89q.worldguard.util.profile.resolver.ProfileService;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permissible;
import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
private BukkitSessionManager sessionManager;
private SessionManager sessionManager;
private BukkitConfigurationManager configuration;
private BukkitRegionContainer regionContainer;
private BukkitDebugHandler debugHandler;
@@ -146,9 +129,8 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
@Override
public void unload() {
sessionManager.shutdown();
configuration.unload();
regionContainer.shutdown();
regionContainer.unload();
}
@Override
@@ -171,10 +153,10 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
return WorldGuardPlugin.inst().getDataFolder().toPath();
}
@SuppressWarnings("removal")
@Override
public void stackPlayerInventory(LocalPlayer localPlayer) {
boolean ignoreMax = false; // localPlayer.hasPermission("worldguard.stack.illegitimate");
boolean ignoreMax = localPlayer.hasPermission("worldguard.stack.illegitimate");
boolean ignoreDamaged = localPlayer.hasPermission("worldguard.stack.damaged");
Player player = ((BukkitPlayer) localPlayer).getPlayer();
@@ -192,7 +174,7 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
continue;
}
int max = /*ignoreMax ? 64 :*/ item.getMaxStackSize();
int max = ignoreMax ? 64 : item.getMaxStackSize();
if (item.getAmount() < max) {
int needed = max - item.getAmount(); // Number of needed items until max
@@ -208,7 +190,12 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
}
// Same type?
if (item2.isSimilar(item)) {
// Blocks store their color in the damage value
if (item2.getType() == item.getType() &&
(ignoreDamaged || item.getDurability() == item2.getDurability()) &&
((item.getItemMeta() == null && item2.getItemMeta() == null)
|| (item.getItemMeta() != null &&
item.getItemMeta().equals(item2.getItemMeta())))) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(max);
@@ -240,38 +227,5 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
report.add(new ServicesReport());
report.add(new WorldReport());
report.add(new PerformanceReport());
if (PaperLib.isPaper()) report.add(new DatapackReport());
}
@Override
public ProfileService createProfileService(ProfileCache profileCache) {
List<ProfileService> services = new ArrayList<>();
if (PaperLib.isPaper()) {
// Paper has a shared cache
services.add(PaperPlayerService.getInstance());
} else {
services.add(BukkitPlayerService.getInstance());
}
services.add(HttpRepositoryService.forMinecraft());
return new CacheForwardingService(new CombinedProfileService(services),
profileCache);
}
@Nullable
@Override
public ProtectedRegion getSpawnProtection(World world) {
if (world instanceof BukkitWorld) {
org.bukkit.World bWorld = ((BukkitWorld) world).getWorld();
if (bWorld.getUID().equals(Bukkit.getServer().getWorlds().get(0).getUID())) {
int radius = Bukkit.getServer().getSpawnRadius();
if (radius > 0) {
BlockVector3 spawnLoc = BukkitAdapter.asBlockVector(bWorld.getSpawnLocation());
return new ProtectedCuboidRegion("__spawn_protection__",
spawnLoc.subtract(radius, 0, radius).withY(world.getMinimumPoint().y()),
spawnLoc.add(radius, 0, radius).withY(world.getMaxY()));
}
}
}
return null;
}
}
@@ -33,11 +33,11 @@ import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitCommandSender;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.commands.GeneralCommands;
import com.sk89q.worldguard.commands.ProtectionCommands;
import com.sk89q.worldguard.commands.ToggleCommands;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.listener.BlacklistListener;
import com.sk89q.worldguard.bukkit.listener.BlockedPotionsListener;
@@ -61,28 +61,14 @@ import com.sk89q.worldguard.bukkit.listener.WorldGuardWeatherListener;
import com.sk89q.worldguard.bukkit.listener.WorldGuardWorldListener;
import com.sk89q.worldguard.bukkit.listener.WorldRulesListener;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.ClassSourceValidator;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Events;
import com.sk89q.worldguard.commands.GeneralCommands;
import com.sk89q.worldguard.commands.ProtectionCommands;
import com.sk89q.worldguard.commands.ToggleCommands;
import com.sk89q.worldguard.domains.registry.SimpleDomainRegistry;
import com.sk89q.worldguard.bukkit.util.logging.ClassSourceValidator;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.protection.managers.storage.file.DirectoryYamlDriver;
import com.sk89q.worldguard.protection.managers.storage.sql.SQLDriver;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import io.papermc.lib.PaperLib;
import io.papermc.paper.ServerBuildInfo;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.DrilldownPie;
import org.bstats.charts.SimplePie;
import org.bstats.charts.SingleLineChart;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
@@ -98,25 +84,20 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
/**
* The main class for WorldGuard as a Bukkit plugin.
*/
public class WorldGuardPlugin extends JavaPlugin {
private static final org.apache.logging.log4j.Logger LOGGER = LogManagerCompat.getLogger();
private static WorldGuardPlugin inst;
private static BukkitWorldGuardPlatform platform;
private final CommandsManager<Actor> commands;
private PlayerMoveListener playerMoveListener;
private static final int BSTATS_PLUGIN_ID = 3283;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
@@ -143,12 +124,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* Called on plugin enable.
*/
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void onEnable() {
// Catch bad things being done by naughty plugins that include WorldGuard's classes
ClassSourceValidator verifier = new ClassSourceValidator(this);
verifier.reportMismatches(ImmutableList.of(WorldGuard.class, ProtectedRegion.class, Flag.class));
configureLogger();
getDataFolder().mkdirs(); // Need to create the plugins/WorldGuard folder
@@ -162,25 +138,23 @@ public class WorldGuardPlugin extends JavaPlugin {
// Set the proper command injector
commands.setInjector(new SimpleInjector(WorldGuard.getInstance()));
// Catch bad things being done by naughty plugins that include
// WorldGuard's classes
ClassSourceValidator verifier = new ClassSourceValidator(this);
verifier.reportMismatches(ImmutableList.of(ProtectedRegion.class, ProtectedCuboidRegion.class, Flag.class));
// Register command classes
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
if (!platform.getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> {
if (!platform.getGlobalStateManager().hasCommandBookGodMode()) {
reg.register(GeneralCommands.class);
}
}, 0L);
if (this.isFolia()) {
getServer().getGlobalRegionScheduler().runAtFixedRate(this, new Consumer() {
@Override
public void accept(Object ignored) {
sessionManager.run();
}
}, BukkitSessionManager.RUN_DELAY, BukkitSessionManager.RUN_DELAY);
} else {
getServer().getScheduler().scheduleSyncRepeatingTask(this, sessionManager, BukkitSessionManager.RUN_DELAY, BukkitSessionManager.RUN_DELAY);
}
getServer().getScheduler().scheduleSyncRepeatingTask(this, sessionManager, BukkitSessionManager.RUN_DELAY, BukkitSessionManager.RUN_DELAY);
// Register events
getServer().getPluginManager().registerEvents(sessionManager, this);
@@ -221,85 +195,23 @@ public class WorldGuardPlugin extends JavaPlugin {
}
worldListener.registerEvents();
if (this.isFolia()) {
Bukkit.getScheduler().runTask(this, () -> {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
player.getScheduler().run(this, new Consumer() {
@Override
public void accept(Object ignored) {
ProcessPlayerEvent event = new ProcessPlayerEvent(player);
Events.fire(event);
}
}, null);
ProcessPlayerEvent event = new ProcessPlayerEvent(player);
Events.fire(event);
}
} else {
Bukkit.getScheduler().runTask(this, () -> {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
ProcessPlayerEvent event = new ProcessPlayerEvent(player);
Events.fire(event);
}
});
}
});
((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).setInitialized(true);
((SimpleDomainRegistry) WorldGuard.getInstance().getDomainRegistry()).setInitialized(true);
// Enable metrics
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); // bStats plugin id
if (platform.getGlobalStateManager().extraStats) {
setupCustomCharts(metrics);
}
}
private void setupCustomCharts(Metrics metrics) {
metrics.addCustomChart(new SingleLineChart("region_count", () ->
platform.getRegionContainer().getLoaded().stream().mapToInt(RegionManager::size).sum()));
metrics.addCustomChart(new SimplePie("region_driver", () -> {
RegionDriver driver = platform.getGlobalStateManager().selectedRegionStoreDriver;
return driver instanceof DirectoryYamlDriver ? "yaml" : driver instanceof SQLDriver ? "sql" : "unknown";
}));
metrics.addCustomChart(new DrilldownPie("blacklist", () -> {
int empty = 0;
Map<String, Integer> blacklistMap = new HashMap<>();
Map<String, Integer> whitelistMap = new HashMap<>();
for (BukkitWorldConfiguration worldConfig : platform.getGlobalStateManager().getWorldConfigs()) {
Blacklist blacklist = worldConfig.getBlacklist();
if (blacklist != null && !blacklist.isEmpty()) {
Map<String, Integer> target = blacklist.isWhitelist() ? whitelistMap : blacklistMap;
int floor = ((blacklist.getItemCount() - 1) / 10) * 10;
String range = floor >= 100 ? "101+" : (floor + 1) + " - " + (floor + 10);
target.merge(range, 1, Integer::sum);
} else {
empty++;
}
}
Map<String, Map<String, Integer>> blacklistCounts = new HashMap<>();
Map<String, Integer> emptyMap = new HashMap<>();
emptyMap.put("empty", empty);
blacklistCounts.put("empty", emptyMap);
blacklistCounts.put("blacklist", blacklistMap);
blacklistCounts.put("whitelist", whitelistMap);
return blacklistCounts;
}));
metrics.addCustomChart(new SimplePie("chest_protection", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.signChestProtection)));
metrics.addCustomChart(new SimplePie("build_permissions", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.buildPermissions)));
metrics.addCustomChart(new SimplePie("custom_flags", () ->
"" + (WorldGuard.getInstance().getFlagRegistry().size() > Flags.INBUILT_FLAGS.size())));
metrics.addCustomChart(new SimplePie("custom_handlers", () ->
"" + (WorldGuard.getInstance().getPlatform().getSessionManager().customHandlersRegistered())));
new Metrics(this);
}
@Override
public void onDisable() {
WorldGuard.getInstance().disable();
if (this.isFolia()) {
this.getServer().getGlobalRegionScheduler().cancelTasks(this);
this.getServer().getAsyncScheduler().cancelTasks(this);
} else {
this.getServer().getScheduler().cancelTasks(this);
}
this.getServer().getScheduler().cancelTasks(this);
}
@Override
@@ -422,8 +334,6 @@ public class WorldGuardPlugin extends JavaPlugin {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
} else if (!worldEdit.isEnabled()) {
throw new CommandException("WorldEdit does not appear to be enabled.");
}
if (worldEdit instanceof WorldEditPlugin) {
@@ -455,9 +365,8 @@ public class WorldGuardPlugin extends JavaPlugin {
}
public Actor wrapCommandSender(CommandSender sender) {
if (sender instanceof Player player) {
if (Entities.isNPC(player)) return null;
return wrapPlayer(player);
if (sender instanceof Player) {
return wrapPlayer((Player) sender);
}
try {
@@ -490,13 +399,6 @@ public class WorldGuardPlugin extends JavaPlugin {
return new BukkitOfflinePlayer(this, player);
}
/**
* Internal method. Do not use as API.
*/
public BukkitConfigurationManager getConfigManager() {
return platform.getGlobalStateManager();
}
/**
* Return a protection query helper object that can be used by another
* plugin to test whether WorldGuard permits an action at a particular
@@ -533,25 +435,44 @@ public class WorldGuardPlugin extends JavaPlugin {
return;
}
try (InputStream stream = getResource("defaults/" + defaultName)){
if (stream == null) throw new FileNotFoundException();
copyDefaultConfig(stream, actual, defaultName);
InputStream input = null;
try {
JarFile file = new JarFile(getFile());
ZipEntry copy = file.getEntry("defaults/" + defaultName);
if (copy == null) throw new FileNotFoundException();
input = file.getInputStream(copy);
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
WorldGuard.logger.severe("Unable to read default configuration: " + defaultName);
}
}
if (input != null) {
FileOutputStream output = null;
private void copyDefaultConfig(InputStream input, File actual, String name) {
try (FileOutputStream output = new FileOutputStream(actual)) {
byte[] buf = new byte[8192];
int length;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
try {
output = new FileOutputStream(actual);
byte[] buf = new byte[8192];
int length = 0;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
WorldGuard.logger.info("Default configuration file written: "
+ actual.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException ignore) {
}
try {
if (output != null) {
output.close();
}
} catch (IOException ignore) {
}
}
getLogger().info("Default configuration file written: " + name);
} catch (IOException e) {
getLogger().log(Level.WARNING, "Failed to write default config file", e);
}
}
@@ -559,22 +480,4 @@ public class WorldGuardPlugin extends JavaPlugin {
return playerMoveListener;
}
private final LazyReference<Boolean> folia = LazyReference.from(() -> {
try {
// Folia is Paper-based, so this is a good first check.
if (PaperLib.isPaper()) {
return ServerBuildInfo.buildInfo().isBrandCompatible(net.kyori.adventure.key.Key.key("papermc", "folia"));
}
} catch (Throwable t) {
// Ignore, this likely means an outdated version.
LOGGER.warn("Failed to check if server is running Folia", t);
}
return false;
});
public boolean isFolia() {
return folia.getValue();
}
}
@@ -21,38 +21,16 @@ package com.sk89q.worldguard.bukkit.cause;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.internal.WGMetadata;
import com.sk89q.worldguard.bukkit.util.Entities;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Firework;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.*;
import org.bukkit.metadata.Metadatable;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -98,39 +76,26 @@ public final class Cause {
}
/**
* Return whether a cause is known. This method will return false if
* the list of causes is empty or the root cause is really not known
* (e.g. primed TNT).
* Return whether a cause is known. This method will return true if
* the list of causes is empty or the list of causes only contains
* objects that really are not root causes (i.e primed TNT).
*
* @return true if known
*/
public boolean isKnown() {
Object object = getRootCause();
if (object == null) {
if (causes.isEmpty()) {
return false;
}
if (object instanceof Tameable tameable && tameable.isTamed()) {
// if they're tamed but also the root cause, the owner is offline
// otherwise the owner will be the root cause (and known)
return false;
}
if (object instanceof TNTPrimed || object instanceof Vehicle) {
if (!PaperLib.isPaper()) {
return false;
}
Entity entity = (Entity) object;
BukkitWorldConfiguration config = WorldGuardPlugin.inst().getConfigManager().get(entity.getWorld().getName());
if (!config.usePaperEntityOrigin || entity.getOrigin() == null) {
return false;
boolean found = false;
for (Object object : causes) {
if (!(object instanceof TNTPrimed) && !(object instanceof Vehicle)) {
found = true;
break;
}
}
return true;
return found;
}
@Nullable
@@ -145,8 +110,8 @@ public final class Cause {
@Nullable
public Player getFirstPlayer() {
for (Object object : causes) {
if (object instanceof Player p && !Entities.isNPC(p)) {
return p;
if (object instanceof Player) {
return (Player) object;
}
}
@@ -156,8 +121,8 @@ public final class Cause {
@Nullable
public Entity getFirstEntity() {
for (Object object : causes) {
if (object instanceof Entity e) {
return e;
if (object instanceof Entity) {
return (Entity) object;
}
}
@@ -167,8 +132,8 @@ public final class Cause {
@Nullable
public Entity getFirstNonPlayerEntity() {
for (Object object : causes) {
if (object instanceof Entity e && (!(object instanceof Player) || Entities.isNPC(e))) {
return e;
if (object instanceof Entity && !(object instanceof Player)) {
return (Entity) object;
}
}
@@ -178,8 +143,8 @@ public final class Cause {
@Nullable
public Block getFirstBlock() {
for (Object object : causes) {
if (object instanceof Block b) {
return b;
if (object instanceof Block) {
return (Block) object;
}
}
@@ -259,15 +224,6 @@ public final class Cause {
WGMetadata.put(target, CAUSE_KEY, parent);
}
/**
* Remove a parent cause from a {@code Metadatable} object.
*
* @param target the target
*/
public static void untrackParentCause(Metadatable target) {
WGMetadata.remove(target, CAUSE_KEY);
}
/**
* Builds causes.
*/
@@ -281,82 +237,44 @@ public final class Cause {
}
private void addAll(@Nullable Object... element) {
if (element == null) {
return;
}
for (Object o : element) {
if (o == null || seen.contains(o)) {
continue;
}
if (element != null) {
for (Object o : element) {
if (o == null || seen.contains(o)) {
continue;
}
seen.add(o);
seen.add(o);
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
ProjectileSource shooter = ((Projectile) o).getShooter();
addAll(shooter);
if (shooter == null && o instanceof Firework && PaperLib.isPaper()) {
UUID spawningUUID = ((Firework) o).getSpawningEntity();
if (spawningUUID != null) {
Entity spawningEntity = Bukkit.getEntity(spawningUUID);
if (spawningEntity != null) {
addAll(spawningEntity);
}
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
addAll(((Projectile) o).getShooter());
} else if (o instanceof Vehicle) {
addAll(((Vehicle) o).getPassengers());
} else if (o instanceof AreaEffectCloud) {
indirect = true;
addAll(((AreaEffectCloud) o).getSource());
} else if (o instanceof Creature && ((Creature) o).getTarget() != null) {
indirect = true;
addAll(((Creature) o).getTarget());
} else if (o instanceof Tameable) {
indirect = true;
addAll(((Tameable) o).getOwner());
}
// Add manually tracked parent causes
Object source = o;
int index = causes.size();
while (source instanceof Metadatable && !(source instanceof Block)) {
source = WGMetadata.getIfPresent((Metadatable) source, CAUSE_KEY, Object.class);
if (source != null) {
causes.add(index, source);
seen.add(source);
}
}
} else if (o instanceof Vehicle) {
((Vehicle) o).getPassengers().forEach(this::addAll);
} else if (o instanceof AreaEffectCloud) {
indirect = true;
addAll(((AreaEffectCloud) o).getSource());
} else if (o instanceof Tameable tameable) {
indirect = true;
if (PaperLib.isPaper()) {
UUID ownerId = tameable.getOwnerUniqueId();
if (ownerId != null) {
Player owner = Bukkit.getPlayer(ownerId);
if (owner != null) {
addAll(owner);
}
}
} else {
// this will cause offline player loads if the player is offline
// too bad for spigot users
AnimalTamer owner = tameable.getOwner();
if (owner instanceof OfflinePlayer player) {
addAll(player.getPlayer()); // player object if online, else null
}
}
} else if (o instanceof Creeper c) {
indirect = true;
addAll(c.getTarget(), c.getIgniter());
} else if (o instanceof Creature c) {
indirect = true;
addAll(c.getTarget());
} else if (o instanceof BlockProjectileSource) {
addAll(((BlockProjectileSource) o).getBlock());
} else if (o instanceof LightningStrike && PaperLib.isPaper() &&
((LightningStrike) o).getCausingEntity() != null) {
indirect = true;
addAll(((LightningStrike) o).getCausingEntity());
} else if (o instanceof FallingBlock f && PaperLib.isPaper() && f.getOrigin() != null) {
indirect = true;
addAll(f.getOrigin().getBlock());
}
// Add manually tracked parent causes
Object source = o;
int index = causes.size();
while (source instanceof Metadatable && !(source instanceof Block)) {
source = WGMetadata.getIfPresent((Metadatable) source, CAUSE_KEY, Object.class);
if (source != null) {
causes.add(index, source);
seen.add(source);
}
causes.add(o);
}
causes.add(o);
}
}
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.bukkit.event.block;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldguard.bukkit.cause.Cause;
@@ -29,15 +28,12 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
@@ -48,8 +44,7 @@ import javax.annotation.Nullable;
abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
private final World world;
private List<Block> blocks;
private final List<BlockState> blockStates;
private final List<Block> blocks;
private final Material effectiveMaterial;
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<Block> blocks, Material effectiveMaterial) {
@@ -60,18 +55,6 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
this.world = world;
this.blocks = blocks;
this.effectiveMaterial = effectiveMaterial;
this.blockStates = null;
}
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<BlockState> blocks) {
super(originalEvent, cause);
checkNotNull(world);
checkNotNull(blocks);
checkArgument(!blocks.isEmpty());
this.world = world;
this.blockStates = blocks;
this.blocks = null;
this.effectiveMaterial = blocks.get(0).getType();
}
protected AbstractBlockEvent(@Nullable Event originalEvent, Cause cause, Block block) {
@@ -103,9 +86,6 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
* @return a list of affected block
*/
public List<Block> getBlocks() {
if (blocks == null) { // be lazy here because we often don't call getBlocks internally, just filter
blocks = blockStates.stream().map(BlockState::getBlock).collect(Collectors.toList());
}
return blocks;
}
@@ -119,21 +99,15 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
* @return true if one or more blocks were filtered out
*/
public boolean filter(Predicate<Location> predicate, boolean cancelEventOnFalse) {
return blocks == null
? filterInternal(blockStates, BlockState::getLocation, predicate, cancelEventOnFalse)
: filterInternal(blocks, Block::getLocation, predicate, cancelEventOnFalse);
}
private <B> boolean filterInternal(List<B> blockList, Function<B, Location> locFunc,
Predicate<Location> predicate, boolean cancelEventOnFalse) {
boolean hasRemoval = false;
Iterator<B> it = blockList.iterator();
Iterator<Block> it = blocks.iterator();
while (it.hasNext()) {
if (!predicate.test(locFunc.apply(it.next()))) {
if (!predicate.test(it.next().getLocation())) {
hasRemoval = true;
if (cancelEventOnFalse) {
blockList.clear();
getBlocks().clear();
setCancelled(true);
break;
} else {
@@ -141,6 +115,7 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
}
}
}
return hasRemoval;
}
@@ -172,7 +147,7 @@ abstract class AbstractBlockEvent extends DelegateEvent implements BulkEvent {
@Override
public Result getResult() {
if (blocks == null ? blockStates.isEmpty() : blocks.isEmpty()) {
if (blocks.isEmpty()) {
return Result.DENY;
}
return super.getResult();
@@ -24,7 +24,6 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -41,10 +40,6 @@ public class PlaceBlockEvent extends AbstractBlockEvent {
private static final HandlerList handlers = new HandlerList();
public PlaceBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<BlockState> blocks) {
super(originalEvent, cause, world, blocks);
}
public PlaceBlockEvent(@Nullable Event originalEvent, Cause cause, World world, List<Block> blocks, Material effectiveMaterial) {
super(originalEvent, cause, world, blocks, effectiveMaterial);
}
@@ -75,13 +75,4 @@ public final class WGMetadata {
return null;
}
/**
* Removes metadata from the target.
*
* @param target the target
* @param key the key
*/
public static void remove(Metadatable target, String key) {
target.removeMetadata(key, WorldGuardPlugin.inst());
}
}
@@ -21,27 +21,12 @@ package com.sk89q.worldguard.bukkit.listener;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
/**
@@ -73,8 +58,8 @@ class AbstractListener implements Listener {
*
* @return the plugin
*/
protected static WorldGuardPlugin getPlugin() {
return WorldGuardPlugin.inst();
protected WorldGuardPlugin getPlugin() {
return plugin;
}
/**
@@ -82,8 +67,8 @@ class AbstractListener implements Listener {
*
* @return the configuration
*/
protected static BukkitConfigurationManager getConfig() {
return getPlugin().getConfigManager();
protected ConfigurationManager getConfig() {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager();
}
/**
@@ -92,22 +77,18 @@ class AbstractListener implements Listener {
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected static BukkitWorldConfiguration getWorldConfig(String world) {
protected WorldConfiguration getWorldConfig(World world) {
return getConfig().get(world);
}
protected static BukkitWorldConfiguration getWorldConfig(org.bukkit.World world) {
return getWorldConfig(world.getName());
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected static BukkitWorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig(((BukkitPlayer) player).getPlayer().getWorld());
protected WorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig((World) player.getExtent());
}
/**
@@ -116,41 +97,8 @@ class AbstractListener implements Listener {
* @param world the world
* @return true if region support is enabled
*/
protected static boolean isRegionSupportEnabled(org.bukkit.World world) {
protected boolean isRegionSupportEnabled(World world) {
return getWorldConfig(world).useRegions;
}
protected RegionAssociable createRegionAssociable(Cause cause) {
Object rootCause = cause.getRootCause();
if (!cause.isKnown()) {
return Associables.constant(Association.NON_MEMBER);
} else if (rootCause instanceof Player player && !Entities.isNPC(player)) {
return getPlugin().wrapPlayer(player);
} else if (rootCause instanceof OfflinePlayer offlinePlayer) {
return getPlugin().wrapOfflinePlayer(offlinePlayer);
} else if (rootCause instanceof Entity entity) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
BukkitWorldConfiguration config = getWorldConfig(entity.getWorld());
Location loc;
if (PaperLib.isPaper() && config.usePaperEntityOrigin) {
loc = entity.getOrigin();
// Origin world may be null, and thus a Location with a null world created, which cannot be adapted to a WorldEdit location
if (loc == null || loc.getWorld() == null) {
loc = entity.getLocation();
}
} else {
loc = entity.getLocation();
}
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
config.useMaxPriorityAssociation);
} else if (rootCause instanceof Block block) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Location loc = block.getLocation();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
getWorldConfig(loc.getWorld()).useMaxPriorityAssociation);
} else {
return Associables.constant(Association.NON_MEMBER);
}
}
}
@@ -31,7 +31,6 @@ import com.sk89q.worldguard.blacklist.event.ItemDestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemEquipBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemUseBlacklistEvent;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
@@ -50,7 +49,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockDispenseArmorEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
@@ -60,7 +58,6 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import static com.sk89q.worldguard.bukkit.BukkitUtil.createTarget;
@@ -80,23 +77,24 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
final Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
createTarget(target.getBlock())), false, false)) {
createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false)) {
return false;
} else if (!wcfg.getBlacklist().check(
new ItemDestroyWithBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
@@ -110,12 +108,6 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
@@ -123,18 +115,19 @@ public class BlacklistListener extends AbstractListener {
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
@@ -142,25 +135,33 @@ public class BlacklistListener extends AbstractListener {
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock())), false, false));
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Material material = Materials.getRelatedMaterial(event.getEffectiveType());
if (material != null) {
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
@@ -172,20 +173,21 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Entity target = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (target instanceof Item) {
Item item = (Item) target;
if (!wcfg.getBlacklist().check(
@@ -208,20 +210,21 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ItemStack target = event.getItemStack();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(target)), false, false)) {
event.setCancelled(true);
@@ -236,7 +239,8 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getPlayer().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getPlayer().getWorld()));
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
@@ -251,7 +255,8 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getBlock().getWorld()));
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(new BlockDispenseBlacklistEvent(null, BukkitAdapter.asBlockVector(event.getBlock().getLocation()),
@@ -270,7 +275,8 @@ public class BlacklistListener extends AbstractListener {
if (item != null && inventory.getHolder() != null) {
Player player = (Player) entity;
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -324,16 +330,12 @@ public class BlacklistListener extends AbstractListener {
return cursor;
}
case HOTBAR_SWAP:
if (event.getClick() == ClickType.SWAP_OFFHAND) {
return clickedInventory == null ? null : ((PlayerInventory) clickedInventory).getItemInOffHand();
}
return clickedInventory == null ? null : clickedInventory.getItem(event.getHotbarButton());
default:
break;
}
} else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER
&& (event.getView().getTopInventory().getType() == InventoryType.PLAYER
|| event.getView().getTopInventory().getType() == InventoryType.CRAFTING)
&& event.getView().getTopInventory().getType() == InventoryType.PLAYER
&& event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
return event.getCurrentItem();
}
@@ -347,7 +349,8 @@ public class BlacklistListener extends AbstractListener {
if (item.getType() != Material.AIR && entity instanceof Player) {
Player player = (Player) entity;
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -364,7 +367,8 @@ public class BlacklistListener extends AbstractListener {
ItemStack item = inventory.getItem(event.getNewSlot());
if (item != null) {
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -380,7 +384,8 @@ public class BlacklistListener extends AbstractListener {
Player player = ((Player) event.getTargetEntity());
ItemStack stack = event.getItem();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemEquipBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(stack)), false, true)) {
@@ -17,12 +17,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
package com.sk89q.worldguard.bukkit.listener;
public class InvalidFlagFormatException extends InvalidFlagFormat {
private static final long serialVersionUID = 8101615074524004172L;
import com.google.common.base.Function;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
public InvalidFlagFormatException(String msg) {
super(msg);
import javax.annotation.Nullable;
class BlockStateAsBlockFunction implements Function<BlockState, Block> {
@Override
public Block apply(@Nullable BlockState blockState) {
return blockState != null ? blockState.getBlock() : null;
}
}
@@ -19,26 +19,26 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.DamageEntityEvent;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.entity.SpectralArrow;
import org.bukkit.entity.TippedArrow;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import java.util.ArrayList;
import java.util.List;
/**
* Handles blocked potions.
@@ -54,81 +54,93 @@ public class BlockedPotionsListener extends AbstractListener {
super(plugin);
}
private PotionEffectType getBlockedEffectByArrow(Arrow arrow, BukkitWorldConfiguration wcfg) {
List<PotionEffect> effects = new ArrayList<>();
PotionType potionType = arrow.getBasePotionType();
if (potionType != null) {
effects.addAll(potionType.getPotionEffects());
}
effects.addAll(arrow.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
return potionEffect.getType();
}
}
return null;
}
@EventHandler
public void onProjectile(DamageEntityEvent event) {
if (!(event.getOriginalEvent() instanceof EntityDamageByEntityEvent originalEvent)) {
return;
}
if (!Entities.isPotionArrow(originalEvent.getDamager())) {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof Arrow arrow) {
blockedEffect = getBlockedEffectByArrow(arrow, wcfg);
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
return;
if (event.getOriginalEvent() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent originalEvent = (EntityDamageByEntityEvent) event.getOriginalEvent();
if (Entities.isPotionArrow(originalEvent.getDamager())) { // should take care of backcompat
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
blockedEffect = PotionEffectType.GLOWING;
}
} else if (originalEvent.getDamager() instanceof TippedArrow) {
TippedArrow tippedArrow = (TippedArrow) originalEvent.getDamager();
PotionEffectType baseEffect = tippedArrow.getBasePotionData().getType().getEffectType();
if (wcfg.blockPotions.contains(baseEffect)) {
blockedEffect = baseEffect;
} else {
for (PotionEffect potionEffect : tippedArrow.getCustomEffects()) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
blockedEffect = potionEffect.getType();
break;
}
}
}
}
if (blockedEffect != null) {
Player player = event.getCause().getFirstPlayer();
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
return;
}
player.sendMessage(ChatColor.RED + "Sorry, arrows with "
+ blockedEffect.getName() + " are presently disabled.");
}
event.setCancelled(true);
}
player.sendMessage(ChatColor.RED + "Sorry, arrows with "
+ blockedEffect.getName() + " are presently disabled.");
}
event.setCancelled(true);
}
}
@EventHandler
public void onItemInteract(UseItemEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
ItemStack item = event.getItemStack();
if (item.getType() != Material.POTION
&& item.getType() != Material.SPLASH_POTION
&& item.getType() != Material.LINGERING_POTION) {
return;
// We only care about potions
boolean oldPotions = false;
try {
if (item.getType() != Material.POTION
&& item.getType() != Material.SPLASH_POTION
&& item.getType() != Material.LINGERING_POTION) {
return;
}
} catch (NoSuchFieldError ignored) {
// PotionMeta technically has been around since 1.7, so the code below
// *should* work still. we just have different materials now.
if (item.getType() != Material.POTION) {
return;
}
oldPotions = true;
}
if (!wcfg.blockPotions.isEmpty()) {
PotionEffectType blockedEffect = null;
if (!(item.getItemMeta() instanceof PotionMeta meta)) {
return;
PotionMeta meta;
if (item.getItemMeta() instanceof PotionMeta) {
meta = ((PotionMeta) item.getItemMeta());
} else {
return; // ok...?
}
// Find the first blocked effect
List<PotionEffect> effects = new ArrayList<>();
if (meta.getBasePotionType() != null) {
effects.addAll(meta.getBasePotionType().getPotionEffects());
PotionEffectType baseEffect = meta.getBasePotionData().getType().getEffectType();
if (wcfg.blockPotions.contains(baseEffect)) {
blockedEffect = baseEffect;
}
effects.addAll(meta.getCustomEffects());
for (PotionEffect potionEffect : effects) {
if (wcfg.blockPotions.contains(potionEffect.getType())) {
blockedEffect = potionEffect.getType();
break;
if (blockedEffect == null && meta.hasCustomEffects()) {
for (PotionEffect effect : meta.getCustomEffects()) {
if (wcfg.blockPotions.contains(effect.getType())) {
blockedEffect = effect.getType();
break;
}
}
}
@@ -137,8 +149,13 @@ public class BlockedPotionsListener extends AbstractListener {
if (player != null) {
if (getPlugin().hasPermission(player, "worldguard.override.potions")) {
if (wcfg.blockPotionsAlways && (item.getType() == Material.SPLASH_POTION
|| item.getType() == Material.LINGERING_POTION)) {
boolean isSplash = false;
try {
isSplash = (!oldPotions && (item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION));
} catch (NoSuchFieldError ignored) {
}
isSplash |= (oldPotions && (Potion.fromItemStack(item).isSplash()));
if (isSplash && wcfg.blockPotionsAlways) {
player.sendMessage(ChatColor.RED + "Sorry, potions with " +
blockedEffect.getName() + " can't be thrown, " +
"even if you have a permission to bypass it, " +
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
@@ -51,7 +52,7 @@ public class BuildPermissionListener extends AbstractListener {
}
private void tellErrorMessage(CommandSender sender, World world) {
String message = getWorldConfig(world).buildPermissionDenyMessage;
String message = getWorldConfig(BukkitAdapter.adapt(world)).buildPermissionDenyMessage;
if (!message.isEmpty()) {
sender.sendMessage(message);
}
@@ -59,7 +60,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -77,7 +78,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -95,27 +96,25 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
if (rootCause instanceof Player) {
final Player player = (Player) rootCause;
final Material material = event.getEffectiveMaterial();
boolean blocked = event.filter(loc -> {
String blacklistName = loc.getBlock().getType().name().toLowerCase();
return hasBuildPermission(player, "block." + blacklistName + ".interact") ||
hasBuildPermission(player, "block.interact." + blacklistName);
}, true);
if (blocked && !event.isSilent()) {
if (!hasBuildPermission(player, "block." + material.name().toLowerCase() + ".interact")
&& !hasBuildPermission(player, "block.interact." + material.name().toLowerCase())) {
tellErrorMessage(player, event.getWorld());
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -133,7 +132,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -151,7 +150,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -169,7 +168,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -187,7 +186,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -29,7 +29,6 @@ import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.UseBlockEvent;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.SignChangeEvent;
@@ -59,7 +58,7 @@ public class ChestProtectionListener extends AbstractListener {
final Player player = event.getCause().getFirstPlayer();
if (player != null) {
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
// Early guard
if (!wcfg.signChestProtection) {
@@ -82,7 +81,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
// Early guard
if (!wcfg.signChestProtection) {
@@ -108,7 +107,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onUseBlock(final UseBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
// Early guard
if (!wcfg.signChestProtection) {
@@ -133,10 +132,10 @@ public class ChestProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
if (wcfg.signChestProtection) {
if ("[Lock]".equalsIgnoreCase(event.getLine(0))) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(BukkitAdapter.adapt(event.getBlock().getLocation()), WorldGuardPlugin.inst().wrapPlayer(player))) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
event.getBlock().breakNaturally();
@@ -144,7 +143,7 @@ public class ChestProtectionListener extends AbstractListener {
return;
}
if (!Tag.STANDING_SIGNS.isTagged(event.getBlock().getType())) {
if (event.getBlock().getType() != Material.SIGN) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
@@ -153,7 +152,7 @@ public class ChestProtectionListener extends AbstractListener {
return;
}
if (!player.getName().equalsIgnoreCase(event.getLine(1))) {
if (!event.getLine(1).equalsIgnoreCase(player.getName())) {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
@@ -165,7 +164,7 @@ public class ChestProtectionListener extends AbstractListener {
Material below = event.getBlock().getRelative(0, -1, 0).getType();
if (below == Material.TNT || below == Material.SAND
|| below == Material.GRAVEL || Tag.STANDING_SIGNS.isTagged(below)) {
|| below == Material.GRAVEL || below == Material.SIGN) {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
@@ -179,7 +178,7 @@ public class ChestProtectionListener extends AbstractListener {
+ "A chest or double chest above is now protected.");
}
} else if (!wcfg.disableSignChestProtectionCheck) {
if ("[Lock]".equalsIgnoreCase(event.getLine(0))) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
@@ -19,10 +19,11 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Entities;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
@@ -58,27 +59,31 @@ public class InvincibilityListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity victim = event.getEntity();
if (!(victim instanceof Player player)) return;
if (Entities.isNPC(player)) return;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (victim instanceof Player) {
Player player = (Player) victim;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(localPlayer)) {
player.setFireTicks(0);
event.setCancelled(true);
BukkitWorldConfiguration worldConfig =
(BukkitWorldConfiguration) WorldGuard.getInstance().getPlatform().getGlobalStateManager().get((World) localPlayer.getExtent());
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent byEntityEvent = (EntityDamageByEntityEvent) event;
Entity attacker = byEntityEvent.getDamager();
if (isInvincible(localPlayer)) {
player.setFireTicks(0);
event.setCancelled(true);
if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Entity) {
attacker = (Entity) ((Projectile) attacker).getShooter();
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent byEntityEvent = (EntityDamageByEntityEvent) event;
Entity attacker = byEntityEvent.getDamager();
if (getWorldConfig(player.getWorld()).regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
if (attacker instanceof Projectile && ((Projectile) attacker).getShooter() instanceof Entity) {
attacker = (Entity) ((Projectile) attacker).getShooter();
}
if (worldConfig.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
}
}
}
@@ -87,25 +92,26 @@ public class InvincibilityListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Player player)) return;
if (Entities.isNPC(player)) return;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (entity instanceof Player) {
Player player = (Player) entity;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (isInvincible(localPlayer)) {
event.setCancelled(true);
if (isInvincible(localPlayer)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (!(event.getEntity() instanceof Player player)) return;
if (Entities.isNPC(player)) return;
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(localPlayer)) {
event.setCancelled(true);
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(localPlayer)) {
event.setCancelled(true);
}
}
}
@@ -23,45 +23,41 @@ import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.PaperInterop;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.AbstractHorse;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityMountEvent;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.Vector;
import java.util.function.Consumer;
public class PlayerMoveListener implements Listener {
public class PlayerMoveListener extends AbstractListener {
private final WorldGuardPlugin plugin;
public PlayerMoveListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
public void registerEvents() {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().usePlayerMove) {
PluginManager pm = getPlugin().getServer().getPluginManager();
pm.registerEvents(this, getPlugin());
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
}
@EventHandler(priority = EventPriority.MONITOR)
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
LocalPlayer player = getPlugin().wrapPlayer(event.getPlayer());
LocalPlayer player = plugin.wrapPlayer(event.getPlayer());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
session.testMoveTo(player, BukkitAdapter.adapt(event.getRespawnLocation()), MoveType.RESPAWN, true);
@@ -71,7 +67,7 @@ public class PlayerMoveListener extends AbstractListener {
public void onVehicleEnter(VehicleEnterEvent event) {
Entity entity = event.getEntered();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
LocalPlayer player = plugin.wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getVehicle().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
@@ -80,18 +76,9 @@ public class PlayerMoveListener extends AbstractListener {
}
@EventHandler(priority = EventPriority.HIGH)
@SuppressWarnings({"rawtypes", "unchecked"})
public void onPlayerMove(PlayerMoveEvent event) {
Location from = event.getFrom();
Location to = event.getTo();
if (from.getBlockX() == to.getBlockX()
&& from.getBlockY() == to.getBlockY()
&& from.getBlockZ() == to.getBlockZ()) {
return;
}
final Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
MoveType moveType = MoveType.MOVE;
@@ -99,18 +86,18 @@ public class PlayerMoveListener extends AbstractListener {
moveType = MoveType.GLIDE;
} else if (event.getPlayer().isSwimming()) {
moveType = MoveType.SWIM;
} else if (event.getPlayer().getVehicle() != null && event.getPlayer().getVehicle() instanceof AbstractHorse) {
} else if (event.getPlayer().getVehicle() != null && event.getPlayer().getVehicle() instanceof Horse) {
moveType = MoveType.RIDE;
}
com.sk89q.worldedit.util.Location weLocation = session.testMoveTo(localPlayer, BukkitAdapter.adapt(to), moveType);
com.sk89q.worldedit.util.Location weLocation = session.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), moveType);
if (weLocation != null) {
final Location override = BukkitAdapter.adapt(weLocation);
override.setX(override.getBlockX() + 0.5);
override.setY(override.getBlockY());
override.setZ(override.getBlockZ() + 0.5);
override.setPitch(to.getPitch());
override.setYaw(to.getYaw());
override.setPitch(event.getTo().getPitch());
override.setYaw(event.getTo().getYaw());
event.setTo(override.clone());
@@ -123,79 +110,18 @@ public class PlayerMoveListener extends AbstractListener {
current.eject();
vehicle.setVelocity(new Vector());
if (vehicle instanceof LivingEntity) {
Location vehicleTeleportLocation = override.clone();
teleport(vehicle, vehicleTeleportLocation);
vehicle.teleport(override.clone());
} else {
Location dismountLocation = override.clone().add(0, 1, 0);
teleport(vehicle, dismountLocation);
vehicle.teleport(override.clone().add(0, 1, 0));
}
current = current.getVehicle();
}
Location playerDismountLocation = override.clone().add(0, 1, 0);
teleport(player, playerDismountLocation);
player.teleport(override.clone().add(0, 1, 0));
Location delayedDismountLocation = override.clone().add(0, 1, 0);
Runnable task = () -> teleport(player, delayedDismountLocation);
if (getPlugin().isFolia()) {
player.getScheduler().runDelayed(getPlugin(), new Consumer() {
@Override
public void accept(Object ignored) {
task.run();
}
}, null, 1);
} else {
Bukkit.getScheduler().runTaskLater(getPlugin(), task, 1);
}
Bukkit.getScheduler().runTaskLater(plugin, () -> player.teleport(override.clone().add(0, 1, 0)), 1);
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
final Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
com.sk89q.worldedit.util.Location loc = session.testMoveTo(localPlayer,
BukkitAdapter.adapt(event.getPlayer().getLocation()), MoveType.OTHER_CANCELLABLE); // white lie
if (loc != null) {
if (getPlugin().isFolia()) {
PaperInterop.teleportAsync(player, BukkitAdapter.adapt(loc));
} else {
player.teleport(BukkitAdapter.adapt(loc));
}
}
session.uninitialize(localPlayer);
}
/**
* Small utility method to teleport via async or sync methods depending on platform.
*
* <p>Ideally we can make this use PaperLib in the future once it's better tested.</p>
*
* @param entity The entity to teleport
* @param location The location to teleport to
*/
private void teleport(Entity entity, Location location) {
if (getPlugin().isFolia()) {
PaperInterop.teleportAsync(entity, location);
} else {
entity.teleport(location);
}
}
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getMount().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
}
@@ -25,7 +25,6 @@ import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
@@ -40,6 +39,7 @@ import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
@@ -58,7 +58,8 @@ public class RegionFlagsListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
@@ -69,7 +70,7 @@ public class RegionFlagsListener extends AbstractListener {
}
}
if (event.getCause().find(EntityType.SNOW_GOLEM) != null) {
if (event.getCause().find(EntityType.SNOWMAN) != null) {
event.filter(testState(query, Flags.SNOWMAN_TRAILS), false);
}
@@ -80,9 +81,10 @@ public class RegionFlagsListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
WorldConfiguration config = getWorldConfig(event.getWorld());
WorldConfiguration config = getWorldConfig(weWorld);
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
@@ -100,41 +102,49 @@ public class RegionFlagsListener extends AbstractListener {
event.filter(testState(query, Flags.ENDERDRAGON_BLOCK_DAMAGE), config.explosionFlagCancellation);
}
if (event.getCause().find(EntityType.END_CRYSTAL) != null) { // EnderCrystal
if (event.getCause().find(EntityType.ENDER_CRYSTAL) != null) { // EnderCrystal
event.filter(testState(query, Flags.OTHER_EXPLOSION), config.explosionFlagCancellation);
}
if (event.getCause().find(EntityType.ENDERMAN) != null) {
event.filter(testState(query, Flags.ENDER_BUILD), false);
}
if (event.getCause().find(EntityType.RAVAGER) != null) {
event.filter(testState(query, Flags.RAVAGER_RAVAGE), false);
}
}
@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
if (!(entity instanceof Player player)) return;
if (Entities.isNPC(player)) return;
if (!isRegionSupportEnabled(BukkitAdapter.adapt(world))) return; // Region support disabled
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (event.getCause() == DamageCause.FALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (entity instanceof Player && event.getCause() == DamageCause.FALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer((Player) entity);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
}
} else if (event.getCause() == DamageCause.FLY_INTO_WALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
} else {
try {
if (entity instanceof Player && event.getCause() == DamageCause.FLY_INTO_WALL) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer((Player) entity);
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), localPlayer, Flags.FALL_DAMAGE)) {
event.setCancelled(true);
return;
}
}
} catch (NoSuchFieldError ignored) {
}
}
if (event instanceof EntityDamageByEntityEvent) {
Entity damager = (((EntityDamageByEntityEvent) event)).getDamager();
if (damager != null && damager.getType() == EntityType.FIREWORK) {
if (!query.testState(BukkitAdapter.adapt(entity.getLocation()), (RegionAssociable) null, Flags.FIREWORK_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
}
@@ -41,6 +41,10 @@ import com.sk89q.worldguard.bukkit.util.InteropUtils;
import com.sk89q.worldguard.bukkit.util.Materials;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
@@ -49,6 +53,7 @@ import com.sk89q.worldguard.protection.regions.RegionQuery;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
@@ -58,14 +63,8 @@ import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityMountEvent;
import org.bukkit.event.entity.PlayerLeashEntityEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import java.util.ArrayList;
@@ -140,23 +139,43 @@ public class RegionProtectionListener extends AbstractListener {
if (rootCause instanceof Player) {
Player player = (Player) rootCause;
WorldConfiguration config = getWorldConfig(world);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(world));
if (config.fakePlayerBuildOverride && InteropUtils.isFakePlayer(player)) {
return true;
}
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
return !pvp && WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld());
return !pvp && new RegionPermissionModel(localPlayer).mayIgnoreRegionProtection(BukkitAdapter.adapt(world));
} else {
return false;
}
}
private RegionAssociable createRegionAssociable(Cause cause) {
Object rootCause = cause.getRootCause();
if (!cause.isKnown()) {
return Associables.constant(Association.NON_MEMBER);
} else if (rootCause instanceof Player) {
return getPlugin().wrapPlayer((Player) rootCause);
} else if (rootCause instanceof OfflinePlayer) {
return getPlugin().wrapOfflinePlayer((OfflinePlayer) rootCause);
} else if (rootCause instanceof Entity) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(((Entity) rootCause).getLocation()));
} else if (rootCause instanceof Block) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(((Block) rootCause).getLocation()));
} else {
return Associables.constant(Association.NON_MEMBER);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
@@ -166,7 +185,7 @@ public class RegionProtectionListener extends AbstractListener {
// Don't check liquid flow unless it's enabled
if (event.getCause().getRootCause() instanceof Block
&& Materials.isLiquid(type)
&& !getWorldConfig(event.getWorld()).checkLiquidFlow) {
&& !getWorldConfig(BukkitAdapter.adapt(event.getWorld())).checkLiquidFlow) {
return;
}
@@ -175,9 +194,9 @@ public class RegionProtectionListener extends AbstractListener {
String what;
/* Flint and steel, fire charge, etc. */
if (Materials.isFire(type)) {
if (type == Material.FIRE) {
Block block = event.getCause().getFirstBlock();
boolean fire = block != null && Materials.isFire(block.getType());
boolean fire = block != null && block.getType() == Material.FIRE;
boolean lava = block != null && Materials.isLava(block.getType());
List<StateFlag> flags = new ArrayList<>();
flags.add(Flags.BLOCK_PLACE);
@@ -209,7 +228,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
@@ -222,7 +241,7 @@ public class RegionProtectionListener extends AbstractListener {
String what;
/* TNT */
if (event.getCause().find(EntityType.TNT, EntityType.TNT_MINECART) != null) {
if (event.getCause().find(EntityType.PRIMED_TNT, EntityType.MINECART_TNT) != null) {
canBreak = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.BLOCK_BREAK, Flags.TNT));
what = "use dynamite";
@@ -245,16 +264,16 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final RegionAssociable associable = createRegionAssociable(event.getCause());
event.filter((Predicate<Location>) target -> {
boolean canUse;
String what;
final Material type = target.getBlock().getType();
/* Saplings, etc. */
if (Materials.isConsideredBuildingIfUsed(type)) {
@@ -263,29 +282,14 @@ public class RegionProtectionListener extends AbstractListener {
/* Inventory */
} else if (Materials.isInventoryBlock(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.CHEST_ACCESS));
what = "open that";
/* Inventory for blocks with the possibility to be only use, e.g. lectern */
} else if (handleAsInventoryUsage(event.getOriginalEvent())) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "take that";
/* Anvils */
} else if (Materials.isAnvil(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.USE_ANVIL));
what = "use that";
/* Beds */
} else if (Materials.isBed(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.SLEEP));
what = "sleep";
/* Respawn Anchors */
} else if(type == Material.RESPAWN_ANCHOR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.RESPAWN_ANCHORS));
what = "use anchors";
/* TNT */
} else if (type == Material.TNT) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.TNT));
@@ -314,7 +318,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -348,7 +352,12 @@ public class RegionProtectionListener extends AbstractListener {
/* Everything else */
} else {
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "place things";
if (event.getEntity() instanceof Item) {
what = "drop items";
} else {
what = "place things";
}
}
if (!canSpawn) {
@@ -360,7 +369,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -396,7 +405,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -407,22 +416,18 @@ public class RegionProtectionListener extends AbstractListener {
String what;
/* Hostile / ambient mob override */
final Entity entity = event.getEntity();
final EntityType type = entity.getType();
if (Entities.isHostile(entity) || Entities.isAmbient(entity)
|| entity instanceof Player || Entities.isNPC(entity)) {
final EntityType type = event.getEntity().getType();
if (Entities.isHostile(event.getEntity()) || Entities.isAmbient(event.getEntity())
|| Entities.isNPC(event.getEntity())) {
canUse = event.getRelevantFlags().isEmpty() || query.queryState(BukkitAdapter.adapt(target), associable, combine(event)) != State.DENY;
what = "use that";
/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(entity)
// weird case since sneak+interact is chest access and not ride
|| event.getOriginalEvent() instanceof InventoryOpenEvent) {
if ((type == EntityType.ITEM_FRAME || type == EntityType.GLOW_ITEM_FRAME)
&& event.getCause().getFirstPlayer() != null
&& ((ItemFrame) entity).getItem().getType() != Material.AIR) {
} else if (Entities.isConsideredBuildingIfUsed(event.getEntity())) {
if (type == EntityType.ITEM_FRAME && event.getCause().getFirstPlayer() != null
&& ((ItemFrame) event.getEntity()).getItem().getType() != Material.AIR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_FRAME_ROTATE));
what = "change that";
} else if (event.getOriginalEvent() instanceof InventoryOpenEvent || event.getOriginalEvent() instanceof InventoryMoveItemEvent) {
} else if (Entities.isMinecart(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "open that";
} else {
@@ -430,16 +435,10 @@ public class RegionProtectionListener extends AbstractListener {
what = "change that";
}
/* Ridden on use */
} else if (Entities.isRiddenOnUse(entity)) {
if (event.getOriginalEvent() instanceof PlayerLeashEntityEvent) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
what = "use that";
} else {
// this is bypassed here as it's handled by the entity mount listener below
// bukkit actually gives three events in this case - in order: PlayerInteractAtEntity, VehicleEnter, EntityMount
canUse = true;
what = "ride that";
}
} else if (Entities.isRiddenOnUse(event.getEntity())) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.RIDE, Flags.INTERACT));
what = "ride that";
/* Everything else */
} else {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT));
@@ -455,7 +454,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
// Whitelist check is below
com.sk89q.worldedit.util.Location target = BukkitAdapter.adapt(event.getTarget());
@@ -475,12 +474,11 @@ public class RegionProtectionListener extends AbstractListener {
}
/* Hostile / ambient mob override */
if (Entities.isHostile(event.getEntity()) || Entities.isAmbient(event.getEntity())) {
if (Entities.isHostile(event.getEntity()) || Entities.isAmbient(event.getEntity())
|| Entities.isVehicle(event.getEntity().getType())) {
canDamage = event.getRelevantFlags().isEmpty() || query.queryState(target, associable, combine(event)) != State.DENY;
what = "hit that";
} else if (Entities.isVehicle(event.getEntity().getType())) {
canDamage = query.testBuild(target, associable, combine(event, Flags.DESTROY_VEHICLE));
what = "change that";
/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(event.getEntity())) {
canDamage = query.testBuild(target, associable, combine(event));
@@ -529,34 +527,14 @@ public class RegionProtectionListener extends AbstractListener {
}
}
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity vehicle = event.getMount();
if (!isRegionSupportEnabled(vehicle.getWorld())) return; // Region support disabled
if (!(event.getEntity() instanceof Player player)) {
return;
}
Cause cause = Cause.create(player);
if (isWhitelisted(cause, vehicle.getWorld(), false)) {
return;
}
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Location location = vehicle.getLocation();
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (!query.testBuild(BukkitAdapter.adapt(location), localPlayer, Flags.RIDE, Flags.INTERACT)) {
event.setCancelled(true);
DelegateEvent dummy = new UseEntityEvent(event, cause, vehicle);
tellErrorMessage(dummy, cause, vehicle.getLocation(), "ride that");
}
}
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) {
Entity vehicle = event.getVehicle();
if (!isRegionSupportEnabled(vehicle.getWorld())) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(vehicle.getWorld()))) return; // Region support disabled
Entity exited = event.getExited();
if (vehicle instanceof Tameable && exited instanceof Player player && !Entities.isNPC(player)) {
if (vehicle instanceof Tameable && exited instanceof Player) {
Player player = (Player) exited;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (!isWhitelisted(Cause.create(player), vehicle.getWorld(), false)) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
@@ -575,6 +553,10 @@ public class RegionProtectionListener extends AbstractListener {
}
}
private boolean isWhitelistedEntity(Entity entity) {
return Entities.isNonPlayerCreature(entity);
}
/**
* Combine the flags from a delegate event with an array of flags.
*
@@ -593,14 +575,4 @@ public class RegionProtectionListener extends AbstractListener {
return flags;
}
/**
* Check if that event should be handled as inventory usage, e.g. if a player takes a book from a lectern
*
* @param event the event to handle
* @return whether it should be handled as inventory usage
*/
private static boolean handleAsInventoryUsage(Event event) {
return event instanceof PlayerTakeLecternBookEvent;
}
}
@@ -31,16 +31,14 @@ import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.util.SpongeUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowman;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockExplodeEvent;
@@ -56,16 +54,18 @@ import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.MoistureChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener extends AbstractListener {
public class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
@@ -73,7 +73,34 @@ public class WorldGuardBlockListener extends AbstractListener {
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
private WorldConfiguration getWorldConfig(World world) {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(world));
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link BukkitWorldConfiguration} for the player's world
*/
private WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
/*
@@ -82,7 +109,7 @@ public class WorldGuardBlockListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
WorldConfiguration wcfg = getWorldConfig(player);
if (!wcfg.itemDurability) {
ItemStack held = player.getInventory().getItemInMainHand();
@@ -104,20 +131,18 @@ public class WorldGuardBlockListener extends AbstractListener {
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
ConfigurationManager cfg = getConfig();
boolean isWater = blockFrom.getType() == Material.WATER;
boolean isLava = blockFrom.getType() == Material.LAVA;
boolean isAir = blockFrom.getType() == Material.AIR;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material fromType = blockFrom.getType();
boolean isWater = Materials.isWater(fromType);
boolean isLava = fromType == Material.LAVA;
boolean isAir = fromType == Material.AIR;
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
@@ -169,7 +194,7 @@ public class WorldGuardBlockListener extends AbstractListener {
}
}
if (wcfg.highFreqFlags && (isWater || blockFrom.getBlockData() instanceof Waterlogged)
if (wcfg.highFreqFlags && isWater
&& WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(blockFrom.getLocation()), (RegionAssociable) null, Flags.WATER_FLOW) == StateFlag.State.DENY) {
event.setCancelled(true);
return;
@@ -180,6 +205,13 @@ public class WorldGuardBlockListener extends AbstractListener {
event.setCancelled(true);
return;
}
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& (blockTo.getType() == Material.REDSTONE_WIRE
|| blockTo.getType() == Material.TRIPWIRE)) {
blockTo.setType(Material.AIR);
return;
}
}
/*
@@ -191,14 +223,13 @@ public class WorldGuardBlockListener extends AbstractListener {
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(world);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(world);
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
@@ -218,7 +249,7 @@ public class WorldGuardBlockListener extends AbstractListener {
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !getPlugin().hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
@@ -279,15 +310,14 @@ public class WorldGuardBlockListener extends AbstractListener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
@@ -296,7 +326,7 @@ public class WorldGuardBlockListener extends AbstractListener {
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), Material.FIRE);
return;
}
@@ -305,7 +335,7 @@ public class WorldGuardBlockListener extends AbstractListener {
if (wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(block.getType()).getId())) {
event.setCancelled(true);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), Material.FIRE);
return;
}
}
@@ -324,24 +354,24 @@ public class WorldGuardBlockListener extends AbstractListener {
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (!set.testState(null, Flags.FIRE_SPREAD)) {
checkAndDestroyFireAround(block.getWorld(), x, y, z);
checkAndDestroyAround(block.getWorld(), x, y, z, Material.FIRE);
event.setCancelled(true);
}
}
}
private void checkAndDestroyFireAround(World world, int x, int y, int z) {
checkAndDestroyFire(world, x, y, z + 1);
checkAndDestroyFire(world, x, y, z - 1);
checkAndDestroyFire(world, x, y + 1, z);
checkAndDestroyFire(world, x, y - 1, z);
checkAndDestroyFire(world, x + 1, y, z);
checkAndDestroyFire(world, x - 1, y, z);
private void checkAndDestroyAround(World world, int x, int y, int z, Material required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
private void checkAndDestroyFire(World world, int x, int y, int z) {
if (Materials.isFire(world.getBlockAt(x, y, z).getType())) {
private void checkAndDestroy(World world, int x, int y, int z, Material required) {
if (world.getBlockAt(x, y, z).getType() == required) {
world.getBlockAt(x, y, z).setType(Material.AIR);
}
}
@@ -351,22 +381,22 @@ public class WorldGuardBlockListener extends AbstractListener {
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
final Material id = event.getBlock().getType();
Material id = event.getBlock().getType();
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if ((id == Material.SAND || id == Material.RED_SAND) && wcfg.noPhysicsSand) {
if (id == Material.SAND && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
@@ -376,7 +406,7 @@ public class WorldGuardBlockListener extends AbstractListener {
return;
}
if (id == Material.LADDER && wcfg.ropeLadders) {
if (wcfg.ropeLadders && event.getBlock().getType() == Material.LADDER) {
if (event.getBlock().getRelative(0, 1, 0).getType() == Material.LADDER) {
event.setCancelled(true);
return;
@@ -443,15 +473,14 @@ public class WorldGuardBlockListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
@@ -469,17 +498,15 @@ public class WorldGuardBlockListener extends AbstractListener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material oldType = event.getBlock().getType();
Material newType = event.getNewState().getType();
Material type = event.getNewState().getType();
if (event instanceof EntityBlockFormEvent) {
if (((EntityBlockFormEvent) event).getEntity() instanceof Snowman) {
@@ -491,7 +518,7 @@ public class WorldGuardBlockListener extends AbstractListener {
return;
}
if (newType == Material.ICE) {
if (type == Material.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
@@ -503,7 +530,7 @@ public class WorldGuardBlockListener extends AbstractListener {
}
}
if (newType == Material.SNOW) {
if (type == Material.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
@@ -522,31 +549,6 @@ public class WorldGuardBlockListener extends AbstractListener {
return;
}
}
if (Materials.isUnwaxedCopper(oldType)) {
if (wcfg.disableCopperBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.COPPER_FADE))) {
event.setCancelled(true);
return;
}
}
if (oldType == Material.LAVA && !Materials.isLiquid(newType)) {
if (wcfg.disableLavaHarden) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.LAVA_HARDEN))) {
event.setCancelled(true);
return;
}
}
}
/*
@@ -554,14 +556,14 @@ public class WorldGuardBlockListener extends AbstractListener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material newType = event.getNewState().getType(); // craftbukkit randomly gives AIR as event.getSource even if that block is not air
if (Materials.isMushroom(newType)) {
@@ -601,7 +603,7 @@ public class WorldGuardBlockListener extends AbstractListener {
}
}
if (Materials.isVine(newType)) {
if (newType == Material.VINE || newType == Material.KELP) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
@@ -613,54 +615,21 @@ public class WorldGuardBlockListener extends AbstractListener {
return;
}
}
if (Materials.isAmethystGrowth(newType) || newType == Material.POINTED_DRIPSTONE) {
if (wcfg.disableRockGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.ROCK_GROWTH))) {
event.setCancelled(true);
return;
}
}
if (Materials.isSculkGrowth(newType)) {
if (wcfg.disableSculkGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.SCULK_GROWTH))) {
event.setCancelled(true);
return;
}
}
handleGrow(event, event.getBlock().getLocation(), newType);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) {
Location loc = event.getBlock().getLocation();
final Material type = event.getNewState().getType();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
final Material type = event.getBlock().getType();
handleGrow(event, loc, type);
}
private void handleGrow(Cancellable event, Location loc, Material type) {
WorldConfiguration wcfg = getWorldConfig(loc.getWorld());
if (Materials.isCrop(type)) {
if (wcfg.disableCropGrowth) {
event.setCancelled(true);
event.setCancelled(false);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(loc), (RegionAssociable) null, Flags.CROP_GROWTH))) {
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.CROP_GROWTH))) {
event.setCancelled(true);
return;
}
@@ -713,22 +682,12 @@ public class WorldGuardBlockListener extends AbstractListener {
event.setCancelled(true);
return;
}
} else if (Materials.isCoral(event.getBlock().getType())) {
if (wcfg.disableCoralBlockFade) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.CORAL_FADE))) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -741,24 +700,4 @@ public class WorldGuardBlockListener extends AbstractListener {
}
}
/**
* Called when the moisture level of a block changes
*/
@EventHandler(ignoreCancelled = true)
public void onMoistureChange(MoistureChangeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableSoilMoistureChange) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.MOISTURE_CHANGE))) {
event.setCancelled(true);
}
}
}
}
@@ -19,34 +19,23 @@
package com.sk89q.worldguard.bukkit.listener;
import com.destroystokyo.paper.event.entity.EntityZapEvent;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.InteropUtils;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.FailedLoadRegionSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.AbstractWindCharge;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderCrystal;
@@ -54,21 +43,17 @@ import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.WindCharge;
import org.bukkit.entity.Wither;
import org.bukkit.entity.WitherSkull;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -77,6 +62,7 @@ import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityBreakDoorEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCreatePortalEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
@@ -85,24 +71,23 @@ import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.EntityTransformEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.projectiles.ProjectileSource;
import java.util.Set;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener extends AbstractListener {
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
@@ -110,44 +95,39 @@ public class WorldGuardEntityListener extends AbstractListener {
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
/**
* Register events.
*/
public void registerEvents() {
super.registerEvents();
PluginManager pm = getPlugin().getServer().getPluginManager();
if (PaperLib.isPaper()) {
pm.registerEvents(new PaperListener(), getPlugin());
} else {
pm.registerEvents(new SpigotListener(), getPlugin());
plugin.getServer().getPluginManager().registerEvents(this, plugin);
if (!EntityCreatePortalEvent.class.isAnnotationPresent(Deprecated.class)) {
plugin.getServer().getPluginManager().registerEvents(new UselessIn114Listener(), plugin);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
WorldConfiguration wcfg = getWorldConfig(block.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
if (block.getType() == Material.FARMLAND && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
return;
}
if (block.getType() == Material.TURTLE_EGG && wcfg.disableCreatureTurtleEggTrampling) {
event.setCancelled(true);
return;
}
if (block.getType() == Material.SNIFFER_EGG && wcfg.disableCreatureSnifferEggTrampling) {
event.setCancelled(true);
return;
if (block.getType() == Material.FARMLAND) {
if (/* entity instanceof Creature && // catch for any entity (not thrown for players) */
wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
@@ -158,14 +138,16 @@ public class WorldGuardEntityListener extends AbstractListener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player player && !Entities.isNPC(defender)) {
} else if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
@@ -181,9 +163,6 @@ public class WorldGuardEntityListener extends AbstractListener {
if (wcfg.teleportOnVoid && type == DamageCause.VOID) {
localPlayer.findFreePosition();
if (wcfg.safeFallOnVoid) {
localPlayer.resetFallDistance();
}
event.setCancelled(true);
return;
}
@@ -207,7 +186,7 @@ public class WorldGuardEntityListener extends AbstractListener {
// handled anywhere else
if (type == DamageCause.BLOCK_EXPLOSION
&& (wcfg.blockOtherExplosions
|| ((wcfg.explosionFlagCancellation || Entities.isConsideredBuildingIfUsed(defender))
|| (wcfg.explosionFlagCancellation
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(defender.getLocation()), (RegionAssociable) null, Flags.OTHER_EXPLOSION))))) {
event.setCancelled(true);
@@ -227,7 +206,8 @@ public class WorldGuardEntityListener extends AbstractListener {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof ItemFrame) {
if (checkItemFrameProtection(attacker, (ItemFrame) defender)) {
@@ -253,8 +233,9 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
@@ -297,6 +278,13 @@ public class WorldGuardEntityListener extends AbstractListener {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.testState(localPlayer, Flags.CREEPER_EXPLOSION) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
}
}
}
}
@@ -313,9 +301,11 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Player player && !Entities.isNPC(defender)) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
// Check Mob
@@ -330,17 +320,13 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
}
if (event.getDamager() instanceof Fireball fireball) {
if (event.getDamager() instanceof Fireball) {
Fireball fireball = (Fireball) event.getDamager();
if (fireball instanceof WitherSkull) {
if (wcfg.blockWitherSkullExplosions) {
event.setCancelled(true);
return;
}
} else if (fireball instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -349,7 +335,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (!query.testState(localPlayer.getLocation(), localPlayer, Entities.getExplosionFlag(event.getDamager())) && wcfg.explosionFlagCancellation) {
if (!query.testState(localPlayer.getLocation(), localPlayer, Flags.GHAST_FIREBALL) && wcfg.explosionFlagCancellation) {
event.setCancelled(true);
return;
}
@@ -384,14 +370,16 @@ public class WorldGuardEntityListener extends AbstractListener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player player && !Entities.isNPC(defender)) {
} else if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
if (type == DamageCause.WITHER) {
@@ -404,14 +392,14 @@ public class WorldGuardEntityListener extends AbstractListener {
if (wcfg.useRegions) {
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
if (!set.testState(getPlugin().wrapPlayer(player), Flags.MOB_DAMAGE)) {
if (!set.testState(plugin.wrapPlayer(player), Flags.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
if (type == DamageCause.DROWNING && getConfig().hasAmphibiousMode(localPlayer)) {
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(localPlayer)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -463,7 +451,10 @@ public class WorldGuardEntityListener extends AbstractListener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(world));
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -472,7 +463,6 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getLocation().getWorld());
if (ent instanceof Creeper) {
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
@@ -506,11 +496,6 @@ public class WorldGuardEntityListener extends AbstractListener {
event.blockList().clear();
return;
}
} else if (ent instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
} else {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
@@ -521,10 +506,10 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
}
if (wcfg.useRegions && !(ent instanceof WindCharge)) {
// allow wither skull blocking since there is no dedicated flag atm
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Entities.getExplosionFlag(ent))) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.GHAST_FIREBALL)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -542,8 +527,8 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.WITHER_DAMAGE)) {
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(block.getLocation()),
(RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.blockList().clear();
event.setCancelled(true);
return;
@@ -558,8 +543,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
if (wcfg.useRegions) {
for (Block block : event.blockList()) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.testState(BukkitAdapter.adapt(block.getLocation()), null, Flags.OTHER_EXPLOSION)) {
if (!WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation())).testState(null, Flags.OTHER_EXPLOSION)) {
event.blockList().clear();
if (wcfg.explosionFlagCancellation) event.setCancelled(true);
return;
@@ -568,6 +552,7 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(BukkitAdapter.adapt(block.getLocation()))) {
@@ -584,7 +569,8 @@ public class WorldGuardEntityListener extends AbstractListener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -593,7 +579,6 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (event.getEntityType() == EntityType.WITHER) {
if (wcfg.blockWitherExplosions) {
event.setCancelled(true);
@@ -614,33 +599,28 @@ public class WorldGuardEntityListener extends AbstractListener {
event.setCancelled(true);
return;
}
} else if (event.getEntityType() == EntityType.TNT
|| event.getEntityType() == EntityType.TNT_MINECART) {
} else if (event.getEntityType() == EntityType.PRIMED_TNT
|| event.getEntityType() == EntityType.MINECART_TNT) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
} else if (event.getEntity() instanceof AbstractWindCharge) {
if (wcfg.blockWindChargeExplosions) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && Entities.isPluginSpawning(event.getSpawnReason())) {
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
return;
}
@@ -690,66 +670,25 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatePortal(PortalCreateEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
private static class UselessIn114Listener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatePortal(EntityCreatePortalEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (wcfg.useRegions && wcfg.regionNetherPortalProtection
&& event.getReason() == PortalCreateEvent.CreateReason.NETHER_PAIR
&& !event.getBlocks().isEmpty()) {
final com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getWorld());
final Cause cause = Cause.create(event.getEntity());
LocalPlayer localPlayer = null;
if (cause.getRootCause() instanceof Player player) {
if (wcfg.fakePlayerBuildOverride && InteropUtils.isFakePlayer(player)) {
return;
}
localPlayer = getPlugin().wrapPlayer(player);
if (WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, world)) {
return;
}
switch (event.getEntityType()) {
case ENDER_DRAGON:
if (wcfg.blockEnderDragonPortalCreation) event.setCancelled(true);
break;
}
final RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer()
.get(world);
ApplicableRegionSet regions;
if (regionManager == null) {
regions = FailedLoadRegionSet.getInstance();
} else {
BlockVector3 min = null;
BlockVector3 max = null;
for (BlockState block : event.getBlocks()) {
BlockVector3 loc = BlockVector3.at(block.getX(), block.getY(), block.getZ());
min = min == null ? loc : loc.getMinimum(min);
max = max == null ? loc : loc.getMaximum(max);
}
ProtectedCuboidRegion target = new ProtectedCuboidRegion("__portal_check", true, min, max);
regions = regionManager.getApplicableRegions(target);
}
final RegionAssociable associable = createRegionAssociable(cause);
final State buildState = StateFlag.denyToNone(regions.queryState(associable, Flags.BUILD));
if (!StateFlag.test(buildState, regions.queryState(associable, Flags.BLOCK_BREAK))
|| !StateFlag.test(buildState, regions.queryState(associable, Flags.BLOCK_PLACE))) {
if (localPlayer != null && !cause.isIndirect()) {
// NB there is no way to cancel the teleport without PTA (since PlayerPortal doesn't have block info)
// removing PTA was a mistake
String message = regions.queryValue(localPlayer, Flags.DENY_MESSAGE);
RegionProtectionListener.formatAndSendDenyMessage("create portals", localPlayer, message);
}
event.setCancelled(true);
}
}
// NOTE: as of right now, bukkit doesn't fire this event for this (despite deprecating EntityCreatePortalEvent for it)
// maybe one day this code will be useful
if (event.getEntity() instanceof EnderDragon && wcfg.blockEnderDragonPortalCreation) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityTransform(EntityTransformEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
final EntityType type = entity.getType();
if (wcfg.disableVillagerZap && type == EntityType.VILLAGER
@@ -758,8 +697,11 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
private static void handlePigZap(Entity entity, Cancellable event) {
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
if (wcfg.disablePigZap) {
event.setCancelled(true);
@@ -768,8 +710,8 @@ public class WorldGuardEntityListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
@@ -778,44 +720,17 @@ public class WorldGuardEntityListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
RegainReason regainReason = event.getRegainReason();
if (regainReason != RegainReason.REGEN && regainReason != RegainReason.SATIATED) {
return;
}
Entity ent = event.getEntity();
World world = ent.getWorld();
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && ent instanceof Player player && !Entities.isNPC(ent)
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
BukkitAdapter.adapt(ent.getLocation()),
WorldGuardPlugin.inst().wrapPlayer(player),
Flags.HEALTH_REGEN)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onFoodChange(FoodLevelChangeEvent event) {
if (event.getItem() != null) return;
HumanEntity ent = event.getEntity();
if (!(ent instanceof Player bukkitPlayer)) return;
if (Entities.isNPC(bukkitPlayer)) return;
if (event.getFoodLevel() > ent.getFoodLevel()) return;
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer(bukkitPlayer);
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (wcfg.useRegions
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
player.getLocation(), player, Flags.HUNGER_DRAIN)) {
event.setCancelled(true);
}
}
/**
@@ -826,21 +741,12 @@ public class WorldGuardEntityListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (ent instanceof FallingBlock) {
Material id = event.getBlock().getType();
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if ((id == Material.SAND || id == Material.RED_SAND) && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
} else if (ent instanceof Enderman) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(ent.getWorld()));
if (ent instanceof Enderman) {
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
@@ -851,7 +757,6 @@ public class WorldGuardEntityListener extends AbstractListener {
return;
}
if (wcfg.useRegions) {
Location location = event.getBlock().getLocation();
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(location), (RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.setCancelled(true);
return;
@@ -865,15 +770,6 @@ public class WorldGuardEntityListener extends AbstractListener {
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(event.getEntered().getWorld());
if (wcfg.blockEntityVehicleEntry && !(event.getEntered() instanceof Player)) {
event.setCancelled(true);
}
}
/**
* Checks regions and config settings to protect items from being knocked
* out of item frames.
@@ -882,8 +778,9 @@ public class WorldGuardEntityListener extends AbstractListener {
* @return true if the event should be cancelled
*/
private boolean checkItemFrameProtection(Entity attacker, ItemFrame defender) {
World world = defender.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
World world = attacker.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.useRegions) {
// bukkit throws this event when a player attempts to remove an item from a frame
if (!(attacker instanceof Player)) {
@@ -898,20 +795,4 @@ public class WorldGuardEntityListener extends AbstractListener {
return false;
}
private static class PaperListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityZap(EntityZapEvent event) {
if (event.getEntityType() == EntityType.PIG) {
handlePigZap(event.getEntity(), event);
}
}
}
private static class SpigotListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
handlePigZap(event.getEntity(), event);
}
}
}
@@ -22,6 +22,7 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
@@ -37,6 +38,7 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
@@ -44,18 +46,35 @@ import org.bukkit.projectiles.ProjectileSource;
/**
* Listener for painting related events.
*
* @author BangL <henno.rickowski@gmail.com>
*/
public class WorldGuardHangingListener extends AbstractListener {
public class WorldGuardHangingListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardHangingListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
@@ -31,6 +31,8 @@ import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.session.MoveType;
@@ -38,9 +40,10 @@ import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.GameModeFlag;
import com.sk89q.worldguard.util.Entities;
import com.sk89q.worldguard.util.command.CommandFilter;
import com.sk89q.worldguard.util.profile.Profile;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.TravelAgent;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
@@ -48,6 +51,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
@@ -56,35 +60,51 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Handles all events thrown in relation to a player.
*/
public class WorldGuardPlayerListener extends AbstractListener {
public class WorldGuardPlayerListener implements Listener {
private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName());
private static final Pattern opPattern = Pattern.compile("^/(?:minecraft:)?(?:bukkit:)?(?:de)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().getIfPresent(localPlayer);
if (session != null) {
GameModeFlag handler = session.getHandler(GameModeFlag.class);
@@ -102,10 +122,11 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
World world = player.getWorld();
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (cfg.activityHaltToggle) {
player.sendMessage(ChatColor.YELLOW
@@ -122,7 +143,7 @@ public class WorldGuardPlayerListener extends AbstractListener {
if (removed > 10) {
log.info("Halt-Act: " + removed + " entities (>10) auto-removed from "
+ player.getWorld());
+ player.getWorld().toString());
}
}
@@ -132,15 +153,14 @@ public class WorldGuardPlayerListener extends AbstractListener {
}
Events.fire(new ProcessPlayerEvent(player));
WorldGuard.getInstance().getExecutorService().submit(() ->
WorldGuard.getInstance().getProfileCache().put(new Profile(player.getUniqueId(), player.getName())));
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
if (wcfg.useRegions) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet chatFrom = query.getApplicableRegions(localPlayer.getLocation());
@@ -155,13 +175,13 @@ public class WorldGuardPlayerListener extends AbstractListener {
boolean anyRemoved = false;
for (Iterator<Player> i = event.getRecipients().iterator(); i.hasNext();) {
Player rPlayer = i.next();
LocalPlayer rLocal = getPlugin().wrapPlayer(rPlayer);
LocalPlayer rLocal = plugin.wrapPlayer(rPlayer);
if (!query.testState(rLocal.getLocation(), rLocal, Flags.RECEIVE_CHAT)) {
i.remove();
anyRemoved = true;
}
}
if (anyRemoved && event.getRecipients().isEmpty() && wcfg.regionCancelEmptyChatEvents) {
if (anyRemoved && event.getRecipients().size() == 0 && wcfg.regionCancelEmptyChatEvents) {
event.setCancelled(true);
}
}
@@ -170,7 +190,7 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
String hostKey = cfg.hostKeys.get(player.getUniqueId().toString());
if (hostKey == null) {
@@ -185,8 +205,7 @@ public class WorldGuardPlayerListener extends AbstractListener {
}
if (!hostname.equals(hostKey)
&& !(cfg.hostKeysAllowFMLClients &&
(hostname.equals(hostKey + "\u0000FML\u0000") || hostname.equals(hostKey + "\u0000FML2\u0000")))) {
&& !(cfg.hostKeysAllowFMLClients && hostname.equals(hostKey + "\u0000FML\u0000"))) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"You did not join with the valid host key!");
log.warning("WorldGuard host key check: " +
@@ -212,11 +231,11 @@ public class WorldGuardPlayerListener extends AbstractListener {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.removeInfiniteStacks
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int slot = player.getInventory().getHeldItemSlot();
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -242,12 +261,13 @@ public class WorldGuardPlayerListener extends AbstractListener {
Player player = event.getPlayer();
@Nullable ItemStack item = event.getItem();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
// Infinite stack removal
if (Materials.isInventoryBlock(type)
&& wcfg.removeInfiniteStacks
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
for (int slot = 0; slot < 40; slot++) {
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -258,11 +278,13 @@ public class WorldGuardPlayerListener extends AbstractListener {
}
if (wcfg.useRegions) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
//Block placedIn = block.getRelative(event.getBlockFace());
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
//ApplicableRegionSet placedInSet = plugin.getRegionContainer().createQuery().getApplicableRegions(placedIn.getLocation());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (item != null && item.getType().getKey().toString().equals(wcfg.regionWand) && getPlugin().hasPermission(player, "worldguard.region.wand")) {
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.getApplicableRegions(BukkitAdapter.adapt(block.getLocation()), RegionQuery.QueryOption.SORT);
if (item != null && item.getType().getKey().toString().equals(wcfg.regionWand) && plugin.hasPermission(player, "worldguard.region.wand")) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? " + (set.testState(localPlayer, Flags.BUILD) ? "Yes" : "No"));
@@ -294,20 +316,13 @@ public class WorldGuardPlayerListener extends AbstractListener {
Player player = event.getPlayer();
Block block = event.getClickedBlock(); //not actually clicked but whatever
Material type = block.getType();
//int type = block.getTypeId();
World world = player.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (type == Material.FARMLAND && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
if (type == Material.TURTLE_EGG && wcfg.disablePlayerTurtleEggTrampling) {
event.setCancelled(true);
return;
}
if (type == Material.SNIFFER_EGG && wcfg.disablePlayerSnifferEggTrampling) {
if (block.getType() == Material.FARMLAND && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
@@ -316,11 +331,12 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
if (com.sk89q.worldguard.bukkit.util.Entities.isNPC(player)) return;
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
@@ -335,10 +351,12 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
if (wcfg.removeInfiniteStacks
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int newSlot = event.getNewSlot();
ItemStack heldItem = player.getInventory().getItem(newSlot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -350,21 +368,17 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
if (event.getTo() == null) {
// The target location for PlayerTeleportEvents can be null.
// Those events will be ignored by the server, so we can ignore them too.
return;
}
World world = event.getFrom().getWorld();
Player player = event.getPlayer();
if (com.sk89q.worldguard.bukkit.util.Entities.isNPC(player)) return;
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions && cfg.usePlayerTeleports) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet set = query.getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom = query.getApplicableRegions(BukkitAdapter.adapt(event.getFrom()));
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getFrom()));
if (event.getCause() == TeleportCause.ENDER_PEARL) {
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
@@ -372,41 +386,89 @@ public class WorldGuardPlayerListener extends AbstractListener {
String message = null;
if (!setFrom.testState(localPlayer, Flags.ENDERPEARL)) {
cancel = true;
message = setFrom.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
message = set.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
} else if (!set.testState(localPlayer, Flags.ENDERPEARL)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
event.setCancelled(true);
return;
}
}
} else if (event.getCause() == TeleportCause.CHORUS_FRUIT) {
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
boolean cancel = false;
String message = null;
if (!setFrom.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = setFrom.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
} else if (!set.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
player.sendMessage(message);
event.setCancelled(true);
return;
}
}
}
if (null != WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer)
.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), MoveType.TELEPORT)) {
if (event.getCause() == TeleportCause.CHORUS_FRUIT) {
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
boolean cancel = false;
String message = null;
if (!setFrom.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.EXIT_DENY_MESSAGE);
} else if (!set.testState(localPlayer, Flags.CHORUS_TELEPORT)) {
cancel = true;
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
player.sendMessage(message);
event.setCancelled(true);
return;
}
}
}
if (null != WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer).testMoveTo(localPlayer,
BukkitAdapter.adapt(event.getTo()),
MoveType.TELEPORT)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerPortal(PlayerPortalEvent event) {
if (event.getTo() == null) { // apparently this counts as a cancelled event, implementation specific though
return;
}
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
LocalPlayer localPlayer = plugin.wrapPlayer(event.getPlayer());
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getTo().getWorld()));
if (!wcfg.regionNetherPortalProtection) return;
if (event.getCause() != TeleportCause.NETHER_PORTAL) {
return;
}
try {
if (!event.useTravelAgent()) { // either end travel (even though we checked cause) or another plugin is fucking with us, shouldn't create a portal though
return;
}
} catch (NoSuchMethodError ignored) {
return;
}
TravelAgent pta = event.getPortalTravelAgent();
if (pta == null) { // possible, but shouldn't create a portal
return;
}
if (pta.findPortal(event.getTo()) != null) {
return; // portal exists...it shouldn't make a new one
}
// HOPEFULLY covered everything the server can throw at us...proceed protection checking
// a lot of that is implementation specific though
// hackily estimate the area that could be effected by this event, since the server refuses to tell us
int radius = pta.getCreationRadius();
Location min = event.getTo().clone().subtract(radius, radius, radius);
Location max = event.getTo().clone().add(radius, radius, radius);
com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getTo().getWorld());
ProtectedRegion check = new ProtectedCuboidRegion("__portalcheck__", BukkitAdapter.adapt(min.getBlock().getLocation()).toVector().toBlockPoint(),
BukkitAdapter.adapt(max.getBlock().getLocation()).toVector().toBlockPoint());
if (wcfg.useRegions && !WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, world)) {
RegionManager mgr = WorldGuard.getInstance().getPlatform().getRegionContainer().get(world);
if (mgr == null) return;
ApplicableRegionSet set = mgr.getApplicableRegions(check);
if (!set.testState(plugin.wrapPlayer(event.getPlayer()), Flags.BUILD)) {
event.getPlayer().sendMessage(ChatColor.RED + "Destination is in a protected area.");
event.setCancelled(true);
return;
}
@@ -416,9 +478,9 @@ public class WorldGuardPlayerListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
if (wcfg.useRegions && !WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
ApplicableRegionSet set =
@@ -19,28 +19,42 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
public class WorldGuardServerListener extends AbstractListener {
/**
* @author zml2008
*/
public class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardServerListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
getConfig().updateCommandBookGodMode();
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
getConfig().updateCommandBookGodMode();
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
}
}
}
@@ -24,8 +24,7 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.bukkit.util.PaperInterop;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.util.Locations;
@@ -33,16 +32,31 @@ import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.stream.Collectors;
public class WorldGuardVehicleListener extends AbstractListener {
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
@@ -55,32 +69,22 @@ public class WorldGuardVehicleListener extends AbstractListener {
return;
}
World world = vehicle.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
org.bukkit.Location from = event.getFrom();
org.bukkit.Location to = event.getTo();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.useRegions) {
// Did we move a block?
if (Locations.isDifferentBlock(BukkitAdapter.adapt(from), BukkitAdapter.adapt(to))) {
if (Locations.isDifferentBlock(BukkitAdapter.adapt(event.getFrom()), BukkitAdapter.adapt(event.getTo()))) {
for (Player player : playerPassengers) {
if (Entities.isNPC(player)) continue;
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
Location lastValid;
if ((lastValid = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer)
.testMoveTo(localPlayer, BukkitAdapter.adapt(to), MoveType.RIDE)) != null) {
.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), MoveType.RIDE)) != null) {
vehicle.setVelocity(new Vector(0, 0, 0));
if (getPlugin().isFolia()) {
PaperInterop.teleportAsync(vehicle, from);
} else {
vehicle.teleport(from);
}
if (Locations.isDifferentBlock(lastValid, BukkitAdapter.adapt(from))) {
vehicle.teleport(event.getFrom());
if (Locations.isDifferentBlock(lastValid, BukkitAdapter.adapt(event.getFrom()))) {
Vector dir = player.getLocation().getDirection();
org.bukkit.Location playerTeleportLocation = BukkitAdapter.adapt(lastValid).setDirection(dir);
if (getPlugin().isFolia()) {
PaperInterop.teleportAsync(player, playerTeleportLocation);
} else {
player.teleport(playerTeleportLocation);
}
player.teleport(BukkitAdapter.adapt(lastValid).setDirection(dir));
}
return;
}
@@ -22,29 +22,44 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
public class WorldGuardWeatherListener extends AbstractListener {
public class WorldGuardWeatherListener implements Listener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
@@ -59,7 +74,8 @@ public class WorldGuardWeatherListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (event.toThunderState()) {
if (wcfg.disableThunder) {
@@ -74,14 +90,11 @@ public class WorldGuardWeatherListener extends AbstractListener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
if (!wcfg.disallowedLightningBlocks.isEmpty()) {
final Block target = event.getLightning().getLocation().getBlock();
Material targetId = target.getType();
if (targetId == Material.AIR) {
targetId = target.getRelative(BlockFace.DOWN).getType();
}
if (wcfg.disallowedLightningBlocks.size() > 0) {
Material targetId = event.getLightning().getLocation().getBlock().getType();
if (wcfg.disallowedLightningBlocks.contains(BukkitAdapter.asBlockType(targetId).getId())) {
event.setCancelled(true);
}
@@ -34,17 +34,30 @@ import org.bukkit.event.world.WorldLoadEvent;
import java.util.logging.Logger;
public class WorldGuardWorldListener extends AbstractListener {
public class WorldGuardWorldListener implements Listener {
private static final Logger log = Logger.getLogger(WorldGuardWorldListener.class.getCanonicalName());
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
super(plugin);
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = getConfig();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
if (cfg.activityHaltToggle) {
int removed = 0;
@@ -76,7 +89,8 @@ public class WorldGuardWorldListener extends AbstractListener {
* @param world The specified world
*/
public void initWorld(World world) {
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
@@ -19,6 +19,7 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.config.WorldConfiguration;
@@ -41,7 +42,7 @@ public class WorldRulesListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onSpawnEntity(final SpawnEntityEvent event) {
if (event.getEffectiveType() == EntityType.EXPERIENCE_ORB) {
WorldConfiguration config = getWorldConfig(event.getWorld());
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
if (config.disableExpDrops) {
event.setCancelled(true);
@@ -52,7 +53,7 @@ public class WorldRulesListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionEffect(EntityPotionEffectEvent event) {
if (event.getCause() == EntityPotionEffectEvent.Cause.CONDUIT) {
WorldConfiguration config = getWorldConfig(event.getEntity().getWorld());
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getEntity().getWorld()));
if (config.disableConduitEffects) {
event.setCancelled(true);
@@ -20,8 +20,6 @@
package com.sk89q.worldguard.bukkit.listener.debounce.legacy;
import com.sk89q.worldguard.bukkit.listener.debounce.legacy.InventoryMoveItemEventDebounce.Key;
import com.sk89q.worldguard.bukkit.util.PaperInterop;
import io.papermc.lib.PaperLib;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@@ -46,18 +44,18 @@ public class InventoryMoveItemEventDebounce extends AbstractEventDebounce<Key> {
private final Object target;
public Key(InventoryMoveItemEvent event) {
cause = transform(PaperInterop.getHolder(event.getInitiator(), false));
source = transform(PaperInterop.getHolder(event.getSource(), false));
target = transform(PaperInterop.getHolder(event.getDestination(), false));
cause = transform(event.getInitiator().getHolder());
source = transform(event.getSource().getHolder());
target = transform(event.getDestination().getHolder());
}
private Object transform(InventoryHolder holder) {
if (holder instanceof BlockState blockState) {
return new BlockMaterialKey(blockState);
} else if (holder instanceof DoubleChest doubleChest) {
InventoryHolder left = PaperLib.isPaper() ? doubleChest.getLeftSide(false) : doubleChest.getLeftSide();
if (left instanceof Chest chest) {
return new BlockMaterialKey(chest);
if (holder instanceof BlockState) {
return new BlockMaterialKey(((BlockState) holder).getBlock());
} else if (holder instanceof DoubleChest) {
InventoryHolder left = ((DoubleChest) holder).getLeftSide();
if (left instanceof Chest) {
return new BlockMaterialKey(((Chest) left).getBlock());
} else {
return holder;
}
@@ -96,8 +94,8 @@ public class InventoryMoveItemEventDebounce extends AbstractEventDebounce<Key> {
private final Block block;
private final Material material;
private BlockMaterialKey(BlockState block) {
this.block = block.getBlock();
private BlockMaterialKey(Block block) {
this.block = block;
material = block.getType();
}
@@ -24,17 +24,15 @@ import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.session.AbstractSessionManager;
import com.sk89q.worldguard.session.Session;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.function.Consumer;
import java.util.Collection;
/**
* Keeps tracks of sessions and also does session-related handling
@@ -47,75 +45,39 @@ public class BukkitSessionManager extends AbstractSessionManager implements Runn
* information for all players.
*/
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void resetAllStates() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
Runnable task = () -> {
BukkitPlayer bukkitPlayer = new BukkitPlayer(WorldGuardPlugin.inst(), player);
Session session = getIfPresent(bukkitPlayer);
if (session != null) {
session.resetState(bukkitPlayer);
}
};
if (WorldGuardPlugin.inst().isFolia()) {
player.getScheduler().run(WorldGuardPlugin.inst(), new Consumer() {
@Override
public void accept(Object ignored) {
task.run();
}
}, null);
} else {
task.run();
Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers();
for (Player player : players) {
BukkitPlayer bukkitPlayer = new BukkitPlayer(WorldGuardPlugin.inst(), player);
Session session = getIfPresent(bukkitPlayer);
if (session != null) {
session.resetState(bukkitPlayer);
}
}
}
@EventHandler
public void onPlayerProcess(ProcessPlayerEvent event) {
public void onPlayerJoin(PlayerJoinEvent event) {
// Pre-load a session
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer(event.getPlayer());
get(player).initialize(player);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void run() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
Runnable task = () -> {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
get(localPlayer).tick(localPlayer);
};
if (WorldGuardPlugin.inst().isFolia()) {
player.getScheduler().run(WorldGuardPlugin.inst(), new Consumer() {
@Override
public void accept(Object ignored) {
task.run();
}
}, null);
} else {
task.run();
}
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
get(localPlayer).tick(localPlayer);
}
}
@Override
public boolean hasBypass(LocalPlayer player, World world) {
if (player instanceof BukkitPlayer bukkitPlayer) {
if (Entities.isNPC(bukkitPlayer.getPlayer())
&& WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world).fakePlayerBuildOverride) {
if (player instanceof BukkitPlayer) {
if (((BukkitPlayer) player).getPlayer().hasMetadata("NPC")
&& WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world).fakePlayerBuildOverride)
return true;
}
if (!bukkitPlayer.getPlayer().isOnline()) {
return false;
}
}
return super.hasBypass(player, world);
}
public void shutdown() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
get(localPlayer).uninitialize(localPlayer);
}
}
}
@@ -45,13 +45,15 @@ public final class Blocks {
* @return a list of connected blocks, not including the given block
*/
public static List<Block> getConnected(Block block) {
BlockState state = PaperInterop.getBlockState(block, false);
BlockState state = block.getState();
BlockData data = state.getBlockData();
if (data instanceof Bed bed) {
if (data instanceof Bed) {
Bed bed = (Bed) data;
return Collections.singletonList(block.getRelative(bed.getPart() == Bed.Part.FOOT
? bed.getFacing() : bed.getFacing().getOppositeFace()));
} else if (data instanceof Chest chest) {
} else if (data instanceof Chest) {
final Chest chest = (Chest) data;
Chest.Type type = chest.getType();
if (type == Chest.Type.SINGLE) {
return Collections.emptyList();
@@ -1,167 +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.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.PluginClassLoader;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Validates that certain specified classes came from the same source as
* a plugin.
* This is copied from the same class in WorldEdit because unfortunately
* trying to use WorldEdit's means we're susceptible to getting a bad version
* of this class if another plugin shades it....which is exactly what we're
* trying to detect and report.
*/
public class ClassSourceValidator {
private static final String SEPARATOR_LINE = Strings.repeat("*", 46);
private static final Method loadClass;
private static Class<?> pluginClassLoaderClass;
static {
Method tmp;
try {
pluginClassLoaderClass = Class.forName("org.bukkit.plugin.java.PluginClassLoader", false,
Bukkit.class.getClassLoader());
tmp = pluginClassLoaderClass.getDeclaredMethod("loadClass0",
String.class, boolean.class, boolean.class, boolean.class);
tmp.setAccessible(true);
} catch (NoSuchMethodException | ClassNotFoundException e) {
tmp = null;
}
loadClass = tmp;
}
private final Plugin plugin;
@Nullable
private final ClassLoader expectedClassLoader;
/**
* Create a new instance.
*
* @param plugin The plugin
*/
public ClassSourceValidator(Plugin plugin) {
checkNotNull(plugin, "plugin");
this.plugin = plugin;
this.expectedClassLoader = plugin.getClass().getClassLoader();
}
/**
* Return a map of classes that been loaded from a different source.
*
* @param classes A list of classes to check
* @return The results
*/
public Map<Class<?>, Plugin> findMismatches(List<Class<?>> classes) {
checkNotNull(classes, "classes");
if (expectedClassLoader == null || loadClass == null) {
return ImmutableMap.of();
}
Map<Class<?>, Plugin> mismatches = new HashMap<>();
for (Plugin target : Bukkit.getPluginManager().getPlugins()) {
if (target == plugin) {
continue;
}
ClassLoader targetLoader = target.getClass().getClassLoader();
if (!(pluginClassLoaderClass.isAssignableFrom(targetLoader.getClass()))) {
continue;
}
for (Class<?> testClass : classes) {
Class<?> targetClass;
try {
targetClass = (Class<?>) loadClass.invoke(targetLoader, testClass.getName(), false, false, false);
} catch (IllegalAccessException | InvocationTargetException ignored) {
continue;
}
if (targetClass.getClassLoader() != expectedClassLoader) {
mismatches.putIfAbsent(testClass, targetClass.getClassLoader() == targetLoader ? target : null);
}
}
}
return mismatches;
}
/**
* Reports classes that have come from a different source.
*
* <p>The warning is emitted to the log.</p>
*
* @param classes The list of classes to check
*/
public void reportMismatches(List<Class<?>> classes) {
if (Boolean.getBoolean("enginehub.disable.class.source.validation")) {
return;
}
Map<Class<?>, Plugin> mismatches = findMismatches(classes);
if (mismatches.isEmpty()) {
return;
}
StringBuilder builder = new StringBuilder("\n");
builder.append(SEPARATOR_LINE).append("\n");
builder.append("** /!\\ SEVERE WARNING /!\\\n");
builder.append("** \n");
builder.append("** A plugin developer has included a portion of \n");
builder.append("** ").append(plugin.getName()).append(" into their own plugin, so rather than using\n");
builder.append("** the version of ").append(plugin.getName()).append(" that you downloaded, you\n");
builder.append("** will be using a broken mix of old ").append(plugin.getName()).append(" (that came\n");
builder.append("** with the plugin) and your downloaded version. THIS MAY\n");
builder.append("** SEVERELY BREAK ").append(plugin.getName().toUpperCase(Locale.ROOT)).append(" AND ALL OF ITS FEATURES.\n");
builder.append("**\n");
builder.append("** This may have happened because the developer is using\n");
builder.append("** the ").append(plugin.getName()).append(" API and thinks that including\n");
builder.append("** ").append(plugin.getName()).append(" is necessary. However, it is not!\n");
builder.append("**\n");
builder.append("** Here are some files that have been overridden:\n");
builder.append("** \n");
for (Map.Entry<Class<?>, Plugin> entry : mismatches.entrySet()) {
Plugin badPlugin = entry.getValue();
String url = badPlugin == null
? "(unknown)"
: badPlugin.getName() + " (" + badPlugin.getClass().getProtectionDomain().getCodeSource().getLocation() + ")";
builder.append("** '").append(entry.getKey().getSimpleName()).append("' came from '").append(url).append("'\n");
}
builder.append("**\n");
builder.append("** Please report this to the plugins' developers.\n");
builder.append(SEPARATOR_LINE).append("\n");
plugin.getLogger().severe(builder.toString());
}
}
@@ -19,41 +19,33 @@
package com.sk89q.worldguard.bukkit.util;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.bukkit.entity.Allay;
import org.bukkit.entity.Ambient;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.BreezeWindCharge;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enemy;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Flying;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Monster;
import org.bukkit.entity.NPC;
import org.bukkit.entity.Pig;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Shulker;
import org.bukkit.entity.Slime;
import org.bukkit.entity.SpectralArrow;
import org.bukkit.entity.Steerable;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.TippedArrow;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.WindCharge;
import org.bukkit.entity.Wither;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class Entities {
@@ -99,7 +91,7 @@ public final class Entities {
* @return true if the entity can be ridden
*/
public static boolean isRiddenOnUse(Entity entity) {
return entity instanceof Steerable ? ((Steerable) entity).hasSaddle() : entity instanceof Vehicle;
return entity instanceof Pig ? ((Pig) entity).hasSaddle() : entity instanceof Vehicle;
}
/**
@@ -109,23 +101,8 @@ public final class Entities {
* @return true if the type is a vehicle type
*/
public static boolean isVehicle(EntityType type) {
return isBoat(type) || isMinecart(type);
}
/**
* Test whether the given entity type is a Boat type.
*
* @param type the type
* @return true if the type is a Boat type
*/
public static boolean isBoat(EntityType type) {
return switch (type) {
case OAK_BOAT, DARK_OAK_BOAT, SPRUCE_BOAT, ACACIA_BOAT, CHERRY_BOAT, JUNGLE_BOAT, MANGROVE_BOAT,
BIRCH_BOAT, PALE_OAK_BOAT, BAMBOO_RAFT, OAK_CHEST_BOAT, DARK_OAK_CHEST_BOAT, SPRUCE_CHEST_BOAT,
ACACIA_CHEST_BOAT, CHERRY_CHEST_BOAT, JUNGLE_CHEST_BOAT, MANGROVE_CHEST_BOAT, BIRCH_CHEST_BOAT,
PALE_OAK_CHEST_BOAT, BAMBOO_CHEST_RAFT -> true;
default -> false;
};
return type == EntityType.BOAT
|| isMinecart(type);
}
/**
@@ -135,11 +112,13 @@ public final class Entities {
* @return true if the type is a Minecart type
*/
public static boolean isMinecart(EntityType type) {
return switch(type) {
case MINECART, CHEST_MINECART, COMMAND_BLOCK_MINECART, FURNACE_MINECART,
HOPPER_MINECART, SPAWNER_MINECART, TNT_MINECART -> true;
default -> false;
};
return type == EntityType.MINECART
|| type == EntityType.MINECART_CHEST
|| type == EntityType.MINECART_COMMAND
|| type == EntityType.MINECART_FURNACE
|| type == EntityType.MINECART_HOPPER
|| type == EntityType.MINECART_MOB_SPAWNER
|| type == EntityType.MINECART_TNT;
}
/**
@@ -170,7 +149,11 @@ public final class Entities {
* @return true if hostile
*/
public static boolean isHostile(Entity entity) {
return entity instanceof Enemy;
return entity instanceof Monster
|| entity instanceof Slime
|| entity instanceof Flying
|| entity instanceof EnderDragon
|| entity instanceof Shulker;
}
/**
@@ -225,49 +208,14 @@ public final class Entities {
return entity instanceof Hanging
|| entity instanceof ArmorStand
|| entity instanceof EnderCrystal
|| entity instanceof Allay
|| entity instanceof Minecart && entity instanceof InventoryHolder;
}
public static boolean isPotionArrow(Entity entity) {
return entity instanceof Arrow || entity instanceof SpectralArrow;
return entity instanceof TippedArrow || entity instanceof SpectralArrow;
}
public static boolean isAoECloud(EntityType type) {
return type == EntityType.AREA_EFFECT_CLOUD;
}
/**
* Check whether the spawn reason should be considered as a "plugin spawning".
* This is true for custom creations or the summon command.
*
* @param spawnReason the reason
* @return true if considered plugin spawning
*/
public static boolean isPluginSpawning(CreatureSpawnEvent.SpawnReason spawnReason) {
return switch (spawnReason) {
case CUSTOM, COMMAND -> true;
default -> false;
};
}
/**
* Get the explosion flag relevant for an entity type.
* @param entity the entity
* @return the relevant StateFlag or OTHER_EXPLOSION if none is matching
*/
public static @Nonnull StateFlag getExplosionFlag(Entity entity) {
return switch (entity) {
case BreezeWindCharge breezeWindCharge -> Flags.BREEZE_WIND_CHARGE;
case WindCharge windCharge -> Flags.WIND_CHARGE_BURST;
case Firework firework -> Flags.FIREWORK_DAMAGE;
case Fireball fireball -> Flags.GHAST_FIREBALL;
case Wither wither -> Flags.WITHER_DAMAGE;
case Creeper creeper -> Flags.CREEPER_EXPLOSION;
case TNTPrimed tnt -> Flags.TNT;
case ExplosiveMinecart minecart -> Flags.TNT;
case EnderDragon dragon -> Flags.ENDERDRAGON_BLOCK_DAMAGE;
case null, default -> Flags.OTHER_EXPLOSION;
};
}
}
@@ -70,7 +70,7 @@ public final class InteropUtils {
UUID uuid = player.getUniqueId();
String name = player.getName();
if (Entities.isNPC(player)) {
if (player.hasMetadata("NPC")) {
return true;
}
File diff suppressed because it is too large. Load diff
@@ -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.bukkit.util;
import io.papermc.lib.PaperLib;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
/**
* This class is mainly here to replace PaperLib, as it no longer fully functions on MC 26.1+.
*/
public class PaperInterop {
private PaperInterop() {
}
public static @Nullable InventoryHolder getHolder(@Nonnull Inventory inventory, boolean useSnapshot) {
if (PaperLib.isPaper()) {
return inventory.getHolder(useSnapshot);
}
return inventory.getHolder();
}
public static BlockState getBlockState(@Nonnull Block block, boolean useSnapshot) {
if (PaperLib.isPaper()) {
return block.getState(useSnapshot);
}
return block.getState();
}
public static CompletableFuture<Boolean> teleportAsync(@Nonnull Entity entity, @Nonnull Location location) {
if (PaperLib.isPaper()) {
return entity.teleportAsync(location);
}
return CompletableFuture.completedFuture(entity.teleport(location));
}
}
@@ -0,0 +1,127 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.util.logging;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.security.CodeSource;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Validates that certain specified classes came from the same source as
* a plugin.
*/
public class ClassSourceValidator {
private static final Logger log = Logger.getLogger(ClassSourceValidator.class.getCanonicalName());
private static final String separatorLine = Strings.repeat("*", 46);
private final Plugin plugin;
@Nullable
private final CodeSource expectedCodeSource;
/**
* Create a new instance.
*
* @param plugin The plugin
*/
public ClassSourceValidator(Plugin plugin) {
checkNotNull(plugin, "plugin");
this.plugin = plugin;
this.expectedCodeSource = plugin.getClass().getProtectionDomain().getCodeSource();
}
/**
* Return a map of classes that been loaded from a different source.
*
* @param classes A list of classes to check
* @return The results
*/
public Map<Class<?>, CodeSource> findMismatches(List<Class<?>> classes) {
checkNotNull(classes, "classes");
Map<Class<?>, CodeSource> mismatches = Maps.newHashMap();
if (expectedCodeSource != null) {
for (Class<?> testClass : classes) {
CodeSource testSource = testClass.getProtectionDomain().getCodeSource();
if (!expectedCodeSource.equals(testSource)) {
mismatches.put(testClass, testSource);
}
}
}
return mismatches;
}
/**
* Reports classes that have come from a different source.
*
* <p>The warning is emitted to the log.</p>
*
* @param classes The list of classes to check
*/
public void reportMismatches(List<Class<?>> classes) {
if (Boolean.getBoolean("worldguard.disable.class.validation")) {
return;
}
Map<Class<?>, CodeSource> mismatches = findMismatches(classes);
if (!mismatches.isEmpty()) {
StringBuilder builder = new StringBuilder("\n");
builder.append(separatorLine).append("\n");
builder.append("** /!\\ SEVERE WARNING /!\\\n");
builder.append("** \n");
builder.append("** A plugin developer has copied and pasted a portion of \n");
builder.append("** ").append(plugin.getName()).append(" into their own plugin, so rather than using\n");
builder.append("** the version of ").append(plugin.getName()).append(" that you downloaded, you\n");
builder.append("** will be using a broken mix of old ").append(plugin.getName()).append(" (that came\n");
builder.append("** with the plugin) and your downloaded version. THIS MAY\n");
builder.append("** SEVERELY BREAK ").append(plugin.getName().toUpperCase()).append(" AND ALL OF ITS FEATURES.\n");
builder.append("**\n");
builder.append("** This may have happened because the developer is using\n");
builder.append("** the ").append(plugin.getName()).append(" API and thinks that including\n");
builder.append("** ").append(plugin.getName()).append(" is necessary. However, it is not!\n");
builder.append("**\n");
builder.append("** Here are some files that have been overridden:\n");
builder.append("** \n");
for (Map.Entry<Class<?>, CodeSource> entry : mismatches.entrySet()) {
CodeSource codeSource = entry.getValue();
String url = codeSource != null ? codeSource.getLocation().toExternalForm() : "(unknown)";
builder.append("** '").append(entry.getKey().getSimpleName()).append("' came from '").append(url).append("'\n");
}
builder.append("**\n");
builder.append("** Please report this to the plugins' developers.\n");
builder.append(separatorLine).append("\n");
log.log(Level.SEVERE, builder.toString());
}
}
}
@@ -1,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.util.report;
import com.sk89q.worldedit.util.report.DataReport;
import io.papermc.paper.datapack.Datapack;
import org.bukkit.Bukkit;
import java.util.Collection;
/**
* A report for current datapacks with some information. Only available on Paper
*/
public class DatapackReport extends DataReport {
public DatapackReport() {
super("DataPacks");
Collection<Datapack> packs = Bukkit.getDatapackManager().getPacks();
append("Datapack Count", packs.size());
append("Datapack Enabled Count", Bukkit.getDatapackManager().getEnabledPacks().size());
for (Datapack pack : packs) {
DataReport report = new DataReport("DataPack: " + pack.getName());
report.append("Enabled?", pack.isEnabled());
report.append("Name", pack.getName());
report.append("Compatibility", pack.getCompatibility().name());
append(report.getTitle(), report);
}
}
}
@@ -24,7 +24,6 @@ import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sk89q.worldedit.util.report.DataReport;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
@@ -52,9 +51,6 @@ public class SchedulerReport extends DataReport {
public SchedulerReport() {
super("Scheduler");
if (WorldGuardPlugin.inst().isFolia()) {
return; // Todo Add support Schedulers
}
List<BukkitTask> tasks = Bukkit.getServer().getScheduler().getPendingTasks();
@@ -20,7 +20,6 @@
package com.sk89q.worldguard.bukkit.util.report;
import com.sk89q.worldedit.util.report.DataReport;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Server;
@@ -31,20 +30,16 @@ public class ServerReport extends DataReport {
Server server = Bukkit.getServer();
try {
append("Server ID", server.getServerId());
append("Server Name", server.getServerName());
} catch (NoSuchMethodError ignored) {
}
append("Bukkit Version", server.getBukkitVersion());
append("Implementation", server.getName() + " " + server.getVersion());
append("Implementation", server.getVersion());
append("Player Count", "%d/%d", Bukkit.getOnlinePlayers().size(), server.getMaxPlayers());
append("Server Class Source", server.getClass().getProtectionDomain().getCodeSource().getLocation());
DataReport onlineMode = new DataReport("Online Mode");
onlineMode.append("enabled?", server.getOnlineMode());
if (PaperLib.isSpigot()) {
onlineMode.append("BungeeCord support?", Bukkit.spigot().getConfig().getBoolean("settings.bungeecord", false));
}
if (PaperLib.isPaper()) {
onlineMode.append("Velocity support?", Bukkit.spigot().getPaperConfig().getBoolean("proxies.velocity.enabled", false));
}
append(onlineMode.getTitle(), onlineMode);
append("Server Class Source", server.getClass().getProtectionDomain().getCodeSource().getLocation());
DataReport spawning = new DataReport("Spawning");
spawning.append("Ambient Spawn Limit", server.getAmbientSpawnLimit());
@@ -1,63 +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.profile.resolver;
import com.sk89q.worldguard.util.profile.Profile;
import io.papermc.lib.PaperLib;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.UUID;
/**
* @deprecated Use {@link com.sk89q.worldguard.util.profile.resolver.PaperPlayerService} instead
*/
@Deprecated(forRemoval = true)
public final class PaperProfileService extends SingleRequestService {
private static final PaperPlayerService SUPER = PaperPlayerService.getInstance();
private static final PaperProfileService INSTANCE = new PaperProfileService();
private PaperProfileService() {
if (!PaperLib.isPaper()) {
throw new IllegalStateException("Attempt to access PaperProfileService on non-Paper server.");
}
}
@Override
public int getIdealRequestLimit() {
return SUPER.getIdealRequestLimit();
}
@Override
@Nullable
public Profile findByName(String name) throws IOException, InterruptedException {
return SUPER.findByName(name);
}
@Nullable
@Override
public Profile findByUuid(UUID uuid) throws IOException, InterruptedException {
return SUPER.findByUuid(uuid);
}
public static PaperProfileService getInstance() {
return INSTANCE;
}
}
@@ -7,7 +7,7 @@
###############################################################################
#
# Example to block some ore mining and placement:
# [coal_ore,gold_ore,iron_ore]
# [coalore,goldore,ironore]
# on-break=deny,log,kick
# on-place=deny,tell
#
@@ -42,7 +42,7 @@
###############################################################################
#
# For more information, see:
# https://worldguard.enginehub.org/en/latest/blacklist/
# https://worldguard.readthedocs.io/en/latest/blacklist/
#
###############################################################################
#
@@ -51,12 +51,17 @@
#
# Deny lava buckets
#[lava_bucket]
#[lavabucket]
#ignore-perms=my.own.madeup.permission
#ignore-groups=admins,mods
#on-use=deny,tell
# Deny some ore
#[coal_ore,gold_ore,iron_ore]
#[coalore,goldore,ironore]
#ignore-groups=admins,mods
#on-break=notify,deny,log
# Some funky data value tests
#[wood:0;>=2]
#ignore-groups=admins,mods
#on-break=notify,deny,log
@@ -1,6 +1,6 @@
name: WorldGuard
main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${internalVersion}"
version: "${project.internalVersion}"
depend: [WorldEdit]
api-version: "26.2"
folia-supported: true
softdepend: [CommandBook]
api-version: 1.13
+30
View File
@@ -0,0 +1,30 @@
apply plugin: 'eclipse'
apply plugin: 'idea'
dependencies {
api 'com.sk89q.worldedit:worldedit-core:7.0.1-SNAPSHOT'
implementation 'com.sk89q:squirrelid:0.2.0'
implementation 'org.flywaydb:flyway-core:3.0'
implementation 'org.khelekore:prtree:1.5.0'
api 'com.google.code.findbugs:jsr305:1.3.9'
testImplementation 'junit:junit:4.11'
testImplementation 'org.hamcrest:hamcrest-library:1.2.1'
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
resources {
srcDir 'src/main/resources'
}
}
}
shadowJar {
relocate('com.sk89q.squirrelid', 'com.sk89q.worldguard.util.profile')
}
build.dependsOn(shadowJar { classifier = null })
-42
View File
@@ -1,42 +0,0 @@
plugins {
id("buildlogic.core-and-platform")
}
dependencies {
constraints {
"implementation"(libs.snakeyaml) {
because("Bukkit provides SnakeYaml")
}
}
"api"(project(":worldguard-libs:core"))
"api"(libs.worldedit.core)
"implementation"(libs.flyway.core)
"implementation"(libs.snakeyaml)
"implementation"(libs.guava)
"compileOnlyApi"(libs.jsr305)
"implementation"(libs.gson)
"compileOnly"(libs.worldedit.libs.ap)
"annotationProcessor"(libs.worldedit.libs.ap)
// ensure this is on the classpath for the AP
"annotationProcessor"(libs.guava)
"compileOnly"(libs.autoService) {
because("Needed to resolve annotations in Piston")
}
"testImplementation"(libs.hamcrest.library)
}
tasks.compileJava {
dependsOn(":worldguard-libs:build")
options.compilerArgs.add("-Aarg.name.key.prefix=")
}
configure<PublishingExtension> {
publications.named<MavenPublication>("maven") {
artifactId = the<BasePluginExtension>().archivesName.get()
from(components["java"])
}
}
@@ -207,17 +207,4 @@ public interface LocalPlayer extends Player, RegionAssociable {
*/
@Beta
void sendTitle(String title, String subtitle);
/**
* Clears fall distance.
*/
void resetFallDistance();
/**
* Teleport the player, potentially async, displaying the message on a success.
* @param location location to teleport to
* @param successMessage message to display on success
* @param failMessage message to display on failure
*/
void teleport(Location location, String successMessage, String failMessage);
}
@@ -24,12 +24,14 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.domains.registry.DomainRegistry;
import com.sk89q.worldguard.domains.registry.SimpleDomainRegistry;
import com.sk89q.worldguard.util.profile.cache.HashMapCache;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
import com.sk89q.worldguard.util.profile.cache.SQLiteCache;
import com.sk89q.worldguard.util.profile.resolver.ProfileService;
import com.sk89q.squirrelid.cache.HashMapCache;
import com.sk89q.squirrelid.cache.ProfileCache;
import com.sk89q.squirrelid.cache.SQLiteCache;
import com.sk89q.squirrelid.resolver.BukkitPlayerService;
import com.sk89q.squirrelid.resolver.CacheForwardingService;
import com.sk89q.squirrelid.resolver.CombinedProfileService;
import com.sk89q.squirrelid.resolver.HttpRepositoryService;
import com.sk89q.squirrelid.resolver.ProfileService;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.task.SimpleSupervisor;
import com.sk89q.worldedit.util.task.Supervisor;
@@ -57,7 +59,6 @@ public final class WorldGuard {
private WorldGuardPlatform platform;
private final SimpleFlagRegistry flagRegistry = new SimpleFlagRegistry();
private final SimpleDomainRegistry domainRegistry = new SimpleDomainRegistry();
private final Supervisor supervisor = new SimpleSupervisor();
private ProfileCache profileCache;
private ProfileService profileService;
@@ -76,32 +77,34 @@ public final class WorldGuard {
}
public void setup() {
executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20,
"WorldGuard Task Executor - %s"));
executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20));
File cacheDir = new File(getPlatform().getConfigDir().toFile(), "cache");
cacheDir.mkdirs();
try {
profileCache = new SQLiteCache(new File(cacheDir, "profiles.sqlite"));
} catch (IOException | UnsatisfiedLinkError ignored) {
logger.log(Level.WARNING, "Failed to initialize SQLite profile cache. Cache is memory-only.");
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to initialize SQLite profile cache");
profileCache = new HashMapCache();
}
profileService = getPlatform().createProfileService(profileCache);
profileService = new CacheForwardingService(
new CombinedProfileService(
BukkitPlayerService.getInstance(),
HttpRepositoryService.forMinecraft()),
profileCache);
getPlatform().load();
}
/**
* The WorldGuard Platform.
* The Platform is only available after WorldGuard is enabled.
*
* @return The platform
*/
public WorldGuardPlatform getPlatform() {
checkNotNull(platform, "WorldGuard is not enabled, unable to access the platform.");
checkNotNull(platform);
return platform;
}
@@ -119,16 +122,6 @@ public final class WorldGuard {
return this.flagRegistry;
}
/**
* Get the domain registry.
*
* @return the domain registry
*/
public DomainRegistry getDomainRegistry() {
return this.domainRegistry;
}
/**
* Get the supervisor.
*
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.blacklist.action;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
@@ -43,12 +42,10 @@ public class BanAction implements Action {
if (event.getPlayer() != null) {
String message = entry.getMessage();
String friendlyName = PlainComponentSerializer.INSTANCE.serialize(event.getTarget().getFriendlyNameComponent());
if (message != null) {
event.getPlayer().ban("Banned: " + String.format(message, friendlyName));
event.getPlayer().ban("Banned: " + String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().ban("Banned: You can't " + event.getDescription() + " " + friendlyName);
event.getPlayer().ban("Banned: You can't " + event.getDescription() + " " + event.getTarget().getFriendlyName());
}
}
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.blacklist.action;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
@@ -43,12 +42,10 @@ public class KickAction implements Action {
if (event.getPlayer() != null) {
String message = entry.getMessage();
String friendlyName = PlainComponentSerializer.INSTANCE.serialize(event.getTarget().getFriendlyNameComponent());
if (message != null) {
event.getPlayer().kick(String.format(message, friendlyName));
event.getPlayer().kick(String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().kick("You can't " + event.getDescription() + " " + friendlyName);
event.getPlayer().kick("You can't " + event.getDescription() + " " + event.getTarget().getFriendlyName());
}
}
@@ -19,8 +19,6 @@
package com.sk89q.worldguard.blacklist.action;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.blacklist.BlacklistEntry;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
@@ -46,10 +44,9 @@ public class TellAction extends RepeatGuardedAction {
if (event.getPlayer() != null) {
if (message != null) {
message = message.replaceAll("(?!<\\\\)\\\\n", "\n").replaceAll("\\\\\\\\n", "\\n");
// TODO Find a better way to do this String.format call that doesn't require a string.
event.getPlayer().print(TextComponent.of(String.format(message, PlainComponentSerializer.INSTANCE.serialize(event.getTarget().getFriendlyNameComponent()))));
event.getPlayer().print(String.format(message, event.getTarget().getFriendlyName()));
} else {
event.getPlayer().printError(TextComponent.of("You're not allowed to " + event.getDescription() + " ").append(event.getTarget().getFriendlyNameComponent()).append(TextComponent.of(".")));
event.getPlayer().printError("You're not allowed to " + event.getDescription() + " " + event.getTarget().getFriendlyName() + ".");
}
}
@@ -20,7 +20,6 @@
package com.sk89q.worldguard.blacklist.event;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
@@ -41,7 +40,7 @@ abstract class BlockBlacklistEvent extends AbstractBlacklistEvent {
@Override
public String getLoggerMessage() {
return getPlayerName() + " tried to " + getDescription() + " " + PlainComponentSerializer.INSTANCE.serialize(getTarget().getFriendlyNameComponent());
return getPlayerName() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
@@ -20,7 +20,6 @@
package com.sk89q.worldguard.blacklist.event;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
@@ -46,7 +45,7 @@ public final class BlockDispenseBlacklistEvent extends BlockBlacklistEvent {
@Override
public String getLoggerMessage() {
return getPosition() + " tried to " + getDescription() + " " + PlainComponentSerializer.INSTANCE.serialize(getTarget().getFriendlyNameComponent());
return getPosition() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
@@ -20,7 +20,6 @@
package com.sk89q.worldguard.blacklist.event;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.target.Target;
@@ -41,7 +40,7 @@ abstract class ItemBlacklistEvent extends AbstractBlacklistEvent {
@Override
public String getLoggerMessage() {
return getPlayerName() + " tried to " + getDescription() + " " + PlainComponentSerializer.INSTANCE.serialize(getTarget().getFriendlyNameComponent());
return getPlayerName() + " tried to " + getDescription() + " " + getTarget().getFriendlyName();
}
@Override
@@ -95,9 +95,9 @@ public class DatabaseHandler implements LoggerHandler {
stmt.setString(1, eventType.name());
stmt.setString(2, worldName);
stmt.setString(3, player != null ? player.getName() : "");
stmt.setInt(4, pos.x());
stmt.setInt(5, pos.y());
stmt.setInt(6, pos.z());
stmt.setInt(4, pos.getBlockX());
stmt.setInt(5, pos.getBlockY());
stmt.setInt(6, pos.getBlockZ());
stmt.setString(7, item);
stmt.setInt(8, (int)(System.currentTimeMillis() / 1000));
stmt.setString(9, comment);
@@ -20,12 +20,10 @@
package com.sk89q.worldguard.blacklist.logger;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.formatting.text.serializer.plain.PlainComponentSerializer;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.event.BlacklistEvent;
import com.sk89q.worldguard.blacklist.target.Target;
import javax.annotation.Nullable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -89,13 +87,13 @@ public class FileHandler implements LoggerHandler {
* Build the path.
*
* @param playerName The name of the player
* @return The path for the logfile, null when no applicable path could be found
* @return The path for the logfile
*/
private @Nullable String buildPath(@Nullable String playerName) {
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
Matcher m = pattern.matcher(pathPattern);
StringBuilder buffer = new StringBuilder();
StringBuffer buffer = new StringBuffer();
// Pattern replacements
while (m.find()) {
@@ -105,13 +103,12 @@ public class FileHandler implements LoggerHandler {
if (group.matches("%%")) {
rep = "%";
} else if (group.matches("%u")) {
if (playerName == null) return null; // Unable to create a path for non player logging events
rep = playerName.toLowerCase().replaceAll("[^A-Za-z0-9_]", "_");
if (rep.length() > 32) { // Actual max length is 16
rep = rep.substring(0, 32);
}
} else if (group.matches("%w")) {
}else if (group.matches("%w")) {
rep = worldName.toLowerCase().replaceAll("[^A-Za-z0-9_]", "_");
if (rep.length() > 32) { // Actual max length is 16
rep = rep.substring(0, 32);
@@ -151,12 +148,11 @@ public class FileHandler implements LoggerHandler {
* @param message The message to log
* @param comment The comment associated with the logged event
*/
private void log(@Nullable LocalPlayer player, String message, String comment) {
String path = buildPath(player != null ? player.getName() : null);
if (path == null) return;
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
try {
String date = dateFormat.format(new Date());
String line = "[" + date + "] " + (player != null ? player.getName() : "Unknown Source") + ": " + message
String line = "[" + date + "] " + player.getName() + ": " + message
+ (comment != null ? " (" + comment + ")" : "") + "\r\n";
LogFileWriter writer = writers.get(path);
@@ -194,7 +190,7 @@ public class FileHandler implements LoggerHandler {
writers.entrySet().iterator();
// Remove some entries
while (it.hasNext()) {
for (; it.hasNext(); ) {
Map.Entry<String,LogFileWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
@@ -222,11 +218,11 @@ public class FileHandler implements LoggerHandler {
* @return The position's coordinates in human-readable form
*/
private String getCoordinates(BlockVector3 pos) {
return "@" + pos.x() + "," + pos.y() + "," + pos.z();
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
}
private void logEvent(BlacklistEvent event, String text, Target target, BlockVector3 pos, String comment) {
log(event.getPlayer(), "Tried to " + text + " " + PlainComponentSerializer.INSTANCE.serialize(target.getFriendlyNameComponent()) + " " + getCoordinates(pos), comment);
log(event.getPlayer(), "Tried to " + text + " " + target.getFriendlyName() + " " + getCoordinates(pos), comment);
}
@Override
@@ -19,12 +19,11 @@
package com.sk89q.worldguard.blacklist.target;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.world.block.BlockType;
public class BlockTarget implements Target {
private final BlockType type;
private BlockType type;
public BlockTarget(BlockType type) {
this.type = type;
@@ -32,16 +31,11 @@ public class BlockTarget implements Target {
@Override
public String getTypeId() {
return type.id();
return type.getId();
}
@Override
public String getFriendlyName() {
return type.getName();
}
@Override
public Component getFriendlyNameComponent() {
return type.getRichName();
}
}
@@ -19,12 +19,11 @@
package com.sk89q.worldguard.blacklist.target;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.world.item.ItemType;
public class ItemTarget implements Target {
private final ItemType type;
private ItemType type;
public ItemTarget(ItemType type) {
this.type = type;
@@ -32,7 +31,7 @@ public class ItemTarget implements Target {
@Override
public String getTypeId() {
return type.id();
return type.getId();
}
@Override
@@ -40,8 +39,4 @@ public class ItemTarget implements Target {
return type.getName();
}
@Override
public Component getFriendlyNameComponent() {
return type.getRichName();
}
}
@@ -19,9 +19,6 @@
package com.sk89q.worldguard.blacklist.target;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
/**
* A target is something that can have events attached to it.
*/
@@ -38,18 +35,7 @@ public interface Target {
* Get a friendly name to be printed.
*
* @return a friendly name
* @deprecated Use {@link #getFriendlyNameComponent()} instead, which supports more complex formatting.
*/
@Deprecated
String getFriendlyName();
/**
* Get a friendly name to be printed.
*
* @return a friendly name
*/
default Component getFriendlyNameComponent() {
return TextComponent.of(getFriendlyName());
}
}
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff. Show more