Compare commits

..
Author SHA1 Message Date
sk89q 2c7767f89f Added RegionQueryCache, which will be used to for cached regions-contain-point lookups. 2012-11-09 12:18:54 -08:00
sk89q 5e75bf36c3 Added proposed protection models. 2012-11-06 22:04:25 -08:00
sk89q a5814c4b32 Made the resolution of criteria parameters as all logical ANDs. 2012-11-06 10:29:41 -08:00
sk89q 70ae1c46a2 Fixed incorrect warning about unrecognized "entity" parameter in TellActionLoader. 2012-11-06 00:52:44 -08:00
sk89q fc5c59ec85 Added support for the item attribute of the Context and routed PlayerInteract into item-use,. 2012-11-06 00:51:40 -08:00
sk89q 2d9a28b0e6 Support accessing the item attribute of the context with match-item and update-item. 2012-11-04 16:07:42 -08:00
sk89q cbcc524798 Standardize the default resolver of entities/blocks to 'target'. 2012-11-04 13:00:52 -08:00
sk89q 69940f2fac Standardized default resolver values. 2012-11-04 12:33:35 -08:00
sk89q 35628d09be Route BlockDispenseEvent to RuleLists item-drop. 2012-11-04 12:17:05 -08:00
sk89q ef43ba2700 player-spawn -> player-join 2012-11-04 11:05:21 -08:00
sk89q 2c2484b026 player-death is very redundant. Changing to entity-death. 2012-11-04 11:03:40 -08:00
sk89q b181bfc914 Added dynamics.disable-mycelium-spread to match master branch. 2012-11-04 01:03:08 -08:00
sk89q 7fcf686d8d Added physics.vine-like-rope-ladders to make ladders work like vines. 2012-11-03 23:28:35 -07:00
sk89q 4f5a751519 Added RuleLists, which are a more flexible version of blacklists, with a cleanup of code.
RuleLists abstract events, and provide a way to unify WorldGuard's various code paths eventually.

There's also a general cleanup of everything and added support for changing the per-world configurations and blacklists (fixes WORLDGUARD-2232). WORLDGUARD-2203 is implicitly fixed by this, although not entirely fully as this does not yet replace blacklists.

Most configuration settings have been rewritten as RuleList rules and can be found in src/main/resources/builtin_rules.yml. Some configuration changes were made: anti-wolf-dumbness was deprecated in favor of wolves-practically-invincible, and ocelots-practically-invincible was added.

Sponges can now re-place water when they are removed, fixing WORLDGUARD-2202.
2012-11-03 23:21:32 -07:00
104 changed files with 8017 additions and 3214 deletions

No files matched your search

-84
View File
@@ -1,87 +1,3 @@
5.7.1:
- Added a vine growth config option and flag.
- Added support for many commands to be used from console.
Usage is with -w flag and a world name e.g.
/rg addmem <id> <player> -w <worldname>
/rg flag <id> <flag> -w <worldname> <flagvalue>
- Fixed bug that blocks placing plants in flower pots.
- Fixed permissions check for /rg tp
- Fixed enderchests not being accessible (they are now part of the USE flag)
- Fixed an issue with slabs being placable in protected regions. This was
also fixed in CraftBukkit but has been left in for users running other versions.
- Fixed wither skulls being handled with other fireballs, despite having their own settings.
- Fixed item frames being placable on region borders.
- Fixed a bug that made explosions more ineffective than they should have been.
- Fixed bonemeal usage in protected regions.
- Fixed special minecarts being placable in protected regions.
- Fixed bugs being placable on region borders.
- Fixed wolves bypassing pvp flags.
5.7:
- Fixed thread sync issue with FlagStateManager.
- Fixed dragon egg region protection not working in certain cases.
- Added beacon and anvil usage protection in regions.
- Add mobs.block-enderdragon-portal-creation to stop enderdragons
from making portals on death.
- Fix TNT being lethal in some case when damage was disabled.
- Fix snowballs and enderpearls being able to knock players back in
pvp deny regions.
- Add subcommand support for allowed and blocked command flags.
- Add max-players-allowed and max-players-reject-message flags to
limit the numbers of players in a region.
- Fix players being able to plant cocoa beans in protected areas.
- Add an enderpearl flag to prevent players from teleporting to and
from regions.
- Added mobs.block-other-explosions config setting and other-explosion
flag to block explosions caused by uncovered things, such as other
plugins. (It doesn't actually have to be a mob)
- Fix mob damage setting and flag not blocking the DoT wither effect.
- Ghast fireball flag will not block blaze fireballs from lighting things
on fire.
- Fixed players without region permissions being able to trigger tripwires,
use enderchests, use wooden buttons, and put plants in flower pots.
- Added mobs.block-zombie-door-destruction setting to stop zombies from
breaking down doors while difficulty is set to hard.
Thank you to thvortex, Dilandau, tophathacker, and Dark_arc for their contributions this release.
5.6.5:
- Fixed a regression that caused paintings and item frames to no longer be properly
protected.
5.6.4:
- Added mobs.block-above-ground-slimes to block slimes spawning naturally above ground.
- Added security.deop-everyone-on-join to de-op all players when they join.
- Added security.block-in-game-op-command to prevent usage of /op from in-game.
- Fixed a NullPointerException in PlayerInteract involving water potions and
potion blocking.
- Fixed an issue with snowballs being blocked in regions.
- Changed dragon eggs to be checked like it is a broken block in regions.
- Moved developer's WGBukkit class to package com.sk89q.worldguard.bukkit.
5.6.3:
- Added helper WGBukkit class to get references to WorldGuard from other plugins.
- Added physics.vine-like-rope-ladders to make ladders work like vines. As long as the
top ladder block is present, ladder blocks will hold even if they have no block
behind them, like a rope ladder.
- Fixed NullPointerException in PlayerInteractEvent caused by potion blocking.
- Fixed mobs.block-{item-frame,painting}-destroy not working.
Thank you to def for testing the above fixes and features.
5.6.2:
- Fixed potion blocking not working well for splash potions.
5.6.1:
- Added a mycelium-spread region flag.
- Added a dynamics.disable-mycelium-spread configuration setting.
- Added new gameplay.block-potions option. For example:
gameplay:
block-potions: [invisibility, speed]
- Fixed a bug in the entity explosion event handler that caused a NullPointerException.
Thank you for gabizou for his contribution in this release.
5.6:
- Added official support for Minecraft 1.4. Support for 1.3.2 (and below) is still
provided in this release.
-3
View File
@@ -26,12 +26,9 @@ must be licensed under the GNU General Public License v3.
Please read CONTRIBUTING.md for important guidelines to follow.
We recommend following our [mailing list](https://groups.google.com/d/forum/sk-dev-discuss), especially if you have some big ideas that you want to implement.
Links
-----
* [Mailing list](https://groups.google.com/d/forum/sk-dev-discuss)
* [IRC channel](http://skq.me/irc/irc.esper.net/sk89q/) (#sk89q on irc.esper.net)
* [Issue tracker](http://youtrack.sk89q.com/issues/WORLDGUARD)
* [Continuous integration](http://build.sk89q.com) [![Build Status](https://secure.travis-ci.org/sk89q/worldguard.png)](http://travis-ci.org/sk89q/worldguard)
+247 -240
View File
@@ -1,240 +1,247 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.7.1</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
<license>
<name>GNU General Public License 2.0</name>
<url>LICENSE.txt</url>
<distribution>repo</distribution>
<comments>License on all contributions</comments>
</license>
</licenses>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
</distributionManagement>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>config.yml</include>
<include>config_world.yml</include>
<include>blacklist.txt</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.7-SNAPSHOT</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers.</description>
<licenses>
<license>
<name>GNU General Public License 2.0</name>
<url>LICENSE.txt</url>
<distribution>repo</distribution>
<comments>License on all contributions</comments>
</license>
</licenses>
<scm>
<connection>scm:git:git://github.com/sk89q/worldguard.git</connection>
<url>https://github.com/sk89q/worldguard</url>
<tag>master</tag>
<developerConnection>scm:git:git@github.com:sk89q/worldguard.git</developerConnection>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>zml-repo</id>
<url>http://files.zachsthings.com/repo</url>
</repository>
<repository>
<id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.4.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>rebar</artifactId>
<version>4.1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.2-R0.2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>com.zachsthings.libcomponents</groupId>
<artifactId>libcomponents-bukkit</artifactId>
</exclusion>
<exclusion>
<groupId>org.spout</groupId>
<artifactId>spoutapi</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.nijikokun</groupId>
<artifactId>iconomy</artifactId>
<version>5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.khelekore</groupId>
<artifactId>prtree</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<site>
<id>sk89q-docs-upload</id>
<url>ftp://sk89q-maven-deploy/worldguard/</url>
</site>
</distributionManagement>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
</includes>
</resource>
<resource>
<targetPath>defaults/</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>blacklist.txt</include>
<include>builtin_rules.yml</include>
<include>rulelist.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>true</addMavenDescriptor>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Class-Path>WorldGuard/WorldEdit.jar lib/WorldEdit.jar ../lib/WorldEdit.jar ../WorldEdit.jar</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>net.sf.opencsv:opencsv</include>
<include>org.khelekore:prtree</include>
<include>com.sk89q:rebar</include>
</includes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
<executions>
<execution>
<id>release</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<preparationGoals>assembly:assembly</preparationGoals>
<goals>assembly:assembly</goals>
<tagNameFormat>@{project.version}</tagNameFormat>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.5</version>
<reportSets>
<reportSet>
<reports>
<report>license</report>
<report>index</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</project>
+1
View File
@@ -3,6 +3,7 @@
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>default</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* An action that will be performed if the conditions are matched of the rule.
*
* @param <T> implementation-specific context object
*/
public interface Action<T extends Context> {
/**
* Apply the action.
*
* @param context implementation-specific context object
*/
void apply(T context);
}
@@ -0,0 +1,40 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* An object that can learn rules and possibly implement them. Attachments can be
* analogous to events that occur in the game. An attachment, for example, would be
* a block break event.
*/
public interface Attachment {
/**
* Learn a rule.
*
* @param rule rule
*/
public void learn(Rule<?> rule);
/**
* Forget all previously learned rules.
*/
public void forgetRules();
}
@@ -0,0 +1,62 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.HashMap;
import java.util.Map;
/**
* Manages known attachment points.
*
* @see Attachment
*/
public class AttachmentManager {
private final Map<String, Attachment> attachments = new HashMap<String, Attachment>();
/**
* Register an {@link Attachment}.
*
* @param name name of the attachment (used in a rule's 'when' clause) (case insensitive)
* @param attachment attachment
*/
public void register(String name, Attachment attachment) {
attachments.put(name.toLowerCase(), attachment);
}
/**
* Get an attachment.
*
* @param name name of the attachment (case insensitive)
* @return attachment
*/
public Attachment get(String name) {
return attachments.get(name.toLowerCase());
}
/**
* Forget all the rules in the registered attachments.
*/
public void forgetRules() {
for (Attachment attachment : attachments.values()) {
attachment.forgetRules();
}
}
}
@@ -0,0 +1,88 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* A context has some shared variables that may be used by a number of different
* events. Because the context contains common information, criteria and
* actions do not have to be custom tailored to specific implementation-specific
* events, and can refer to the the properties set on the context. The place
* where the information is known as to what is considered the proper valid
* value of a common property is during the initial handling of
* the event in the implementation.
* </p>
* Implementations need to have custom contexts that can carry more
* information than offered in this abstract implementation. Criteria and
* actions can be implement-specific by tailoring themselves to one of these
* implementation-specific contexts.
*
* @author sk89q
*/
public abstract class Context {
private boolean matches = false;
private boolean cancelled = false;
/**
* Gets whether the event associated with this context has been set to
* be cancelled.
*
* @return true if the event is set to be cancelled
*/
public boolean isCancelled() {
return cancelled;
}
/**
* Set the event associated with this context to be cancelled, if possible.
*/
public void cancel() {
setCancelled(true);
}
/**
* Set the event associated with this context to be cancelled, if possible.
*
* @param cancelled true to cancel
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Set as to whether all the conditions associated with this context have
* evaluated to being true.
*
* @param matches match state
*/
void setMatches(boolean matches) {
this.matches = matches;
}
/**
* Returns whether all the conditions associated with this context
* have been evaluated to true.
*
* @return true if all the conditions have been true
*/
public boolean matches() {
return matches;
}
}
@@ -0,0 +1,37 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* A criteria that is evaluated to decide whether the rule should undergo
* further processing.
*
* @param <T> an implementation-specific context
*/
public interface Criteria<T extends Context> {
/**
* Returns whether the current event / context matches this criteria.
*
* @param context context to verify
* @return true if it matches
*/
boolean matches(T context);
}
@@ -0,0 +1,99 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@link Rule} implementation with a list of {@link Criteria} and
* {@link Action}s.
*
* @param <T> underlying implementation-specific context
*/
public class DefinedRule<T extends Context> implements Rule<T> {
private static Logger logger = Logger.getLogger(Rule.class.getCanonicalName());
private final List<Criteria<T>> criterion = new LinkedList<Criteria<T>>();
private final List<Action<T>> actions = new LinkedList<Action<T>>();
/**
* Add a criteria to this rule.
*
* @param criteria the criteria
*/
public void add(Criteria<T> criteria) {
criterion.add(criteria);
}
/**
* Add an action to this rule.
*
* @param action the action
*/
public void add(Action<T> action) {
actions.add(action);
}
/**
* Returns whether criteria are defined.
*
* @return true if there are criteria
*/
public boolean hasCriterion() {
return criterion.size() > 0;
}
/**
* Returns whether actions are defined.
*
* @return true if there are actions
*/
public boolean hasActions() {
return actions.size() > 0;
}
@Override
public boolean matches(T context) {
for (Criteria<T> criteria : criterion) {
if (!criteria.matches(context)) {
context.setMatches(false);
return false;
}
}
context.setMatches(true);
return true;
}
@Override
public void apply(T context) {
for (Action<T> action : actions) {
try {
action.apply(context);
} catch (Throwable t) {
logger.log(Level.WARNING, "Failed to apply action of rule", t);
}
}
}
}
@@ -0,0 +1,42 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import com.sk89q.rebar.config.LoaderBuilderException;
public class DefinitionException extends LoaderBuilderException {
private static final long serialVersionUID = -5429457695711163632L;
public DefinitionException() {
}
public DefinitionException(String message) {
super(message);
}
public DefinitionException(Throwable cause) {
super(cause);
}
public DefinitionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,47 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class DefinitionInitializeEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final RuleListsManager ruleListsManager;
public DefinitionInitializeEvent(RuleListsManager ruleListsManager) {
this.ruleListsManager = ruleListsManager;
}
public RuleListsManager getManager() {
return ruleListsManager;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -0,0 +1,76 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.HashMap;
import java.util.Map;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.ConfigurationValue;
import com.sk89q.rebar.config.Loader;
/**
* Manages loaders for definitions of the given generic type.
*
* @author sk89q
* @param <V> type to create
*/
public class DefinitionManager<V> {
/**
* Map of factories.
*/
private Map<String, Loader<? extends V>> factories = new HashMap<String, Loader<? extends V>>();
/**
* Register a loader.
*
* @param id ID, case does not matter
* @param factory factory
*/
public void register(String id, Loader<? extends V> factory) {
factories.put(id.toLowerCase(), factory);
}
/**
* Create a new instance.
*
* @param id type
* @param node configuration node
* @param value short-hand value, possibly null
* @return an object
* @throws DefinitionException thrown on error when parsing or instantiating
*/
V newInstance(String id, ConfigurationNode node, ConfigurationValue value) throws DefinitionException {
Loader<? extends V> factory;
if (value != null) {
node = node.clone();
node.set("_", value.get());
}
if ((factory = factories.get(id)) != null) {
return factory.read(node);
}
throw new DefinitionException("Don't know what '" + id
+ "' is (typo? criteria/action doesn't exist?)");
}
}
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExpressionParser {
private static final char COLOR_CHAR = '\u00A7';
private static final Pattern classicColors = Pattern.compile("&[A-Fa-z0-9klmnor]");
public String format(Context context, String string) {
Matcher m = classicColors.matcher(string);
string = m.replaceAll(COLOR_CHAR + "$1");
return string;
}
}
@@ -0,0 +1,40 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* A criteria wrapper that inverts the condition.
*
* @author sk89q
* @param <T> underlying criteria
*/
public class InvertedCriteria<T extends Context> implements Criteria<T> {
private final Criteria<T> criteria;
public InvertedCriteria(Criteria<T> criteria) {
this.criteria = criteria;
}
@Override
public boolean matches(T context) {
return !criteria.matches(context);
}
}
@@ -0,0 +1,89 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* Contains names of standard attachments.
*/
public enum KnownAttachment {
BLOCK_BREAK("block-break"),
BLOCK_PLACE("block-place"),
BLOCK_SPREAD("block-spread"),
BLOCK_PHYSICS("block-physics"),
BLOCK_INTERACT("block-interact"),
BLOCK_FADE("block-fade"),
BLOCK_FORM("block-form"),
PLAYER_JOIN("player-join"),
PLAYER_RESPAWN("player-respawn"),
PLAYER_QUIT("player-quit"),
ENTITY_EXPLODE("entity-explode"),
ENTITY_DAMAGE("entity-damage"),
ENTITY_DEATH("entity-death"),
ENTITY_IGNITE("entity-ignite"),
ENTITY_SPAWN("entity-spawn"),
ENTITY_STRIKE("entity-strike"),
ENTITY_INTERACT("entity-interact"),
ITEM_DROP("item-drop"),
ITEM_PICKUP("item-pickup"),
ITEM_USE("item-use"),
WEATHER_PHENOMENON("weather-phenomenon"),
WEATHER_TRANSITION("weather-transition"),
WORLD_LOAD("world-load"),
WORLD_UNLOAD("world-unload"),
WORLD_SAVE("world-save");
private final static Map<String, KnownAttachment> ids = new HashMap<String, KnownAttachment>();
static {
for (KnownAttachment attachment : EnumSet.allOf(KnownAttachment.class)) {
ids.put(attachment.getId().toLowerCase(), attachment);
}
}
private final String id;
KnownAttachment(String id) {
this.id = id;
}
/**
* Get the attachment's string ID.
*
* @return string ID
*/
public String getId() {
return id;
}
/**
* Get an attachment from a given string ID. Not case sensitive.
*
* @param id string ID
* @return attachment name
*/
public static KnownAttachment fromId(String id) {
return ids.get(id.toLowerCase());
}
}
@@ -0,0 +1,52 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.EnumMap;
import java.util.Map;
/**
* Holds known attachment rule sets for every {@link KnownAttachment}.
*/
public class KnownAttachmentRules {
private Map<KnownAttachment, RuleSet> ruleSets =
new EnumMap<KnownAttachment, RuleSet>(KnownAttachment.class);
/**
* Build a new instance, with every attachment having an empty {@link RuleSet}
* defined for it.
*/
public KnownAttachmentRules() {
for (KnownAttachment attachment : KnownAttachment.values()) {
ruleSets.put(attachment, new RuleSet());
}
}
/**
* Get a rule set for a given attachment.
*
* @param attachment the attachment
* @return the rule set
*/
public RuleSet get(KnownAttachment attachment) {
return ruleSets.get(attachment);
}
}
@@ -0,0 +1,30 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* Attempts to resolve the requested object from other objects. For
* example, a block place event can have multiple 'relevant' blocks, such as
* the target block or the source block. A resolver is used to figure out
* which block is requested, and then the resolver would return the object
* requested by accessing it through a given context.
*/
public interface Resolver {
}
@@ -0,0 +1,63 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.HashMap;
import java.util.Map;
public class ResolverManager {
private final Map<Class<? extends Resolver>, Map<String, Resolver>> resolvers
= new HashMap<Class<? extends Resolver>, Map<String, Resolver>>();
private final Map<Resolver, String> reverse = new HashMap<Resolver, String>();
public <T extends Resolver> void register(Class<T> clazz, String id, T resolver) {
Map<String, Resolver> map = resolvers.get(clazz);
if (map == null) {
map = new HashMap<String, Resolver>();
resolvers.put(clazz, map);
}
reverse.put(resolver, id);
map.put(id.toLowerCase(), resolver);
}
public String getId(Object object) {
return reverse.get(object);
}
@SuppressWarnings("unchecked")
public <T extends Resolver> T get(Class<T> clazz, String id) throws DefinitionException {
Map<String, Resolver> map = resolvers.get(clazz);
if (map == null) {
throw new DefinitionException("Don't know how to resolve "
+ clazz.getCanonicalName());
}
Resolver resolver = map.get(id);
if (resolver == null) {
throw new DefinitionException("Don't know how to resolve "
+ clazz.getCanonicalName());
}
return (T) resolver;
}
}
@@ -0,0 +1,35 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* A rule that may match a number of events and can be applied in
* a situation. See {@link DefinedRule} for a rule implementation that
* consists of constituent {@link Criteria}s and {@link Action}s.
*
* @author sk89q
* @param <T> implementation-specific context
*/
public interface Rule<T extends Context> {
boolean matches(T context);
void apply(T context);
}
@@ -0,0 +1,60 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.List;
/**
* A pair of attachment/event names a rule.
*/
public class RuleEntry {
private final List<String> attachmentNames;
private final Rule<?> rule;
/**
* Construct the rule entry with the list of attachment names and rules.
*
* @param attachmentNames attachment names
* @param rule rules
*/
public RuleEntry(List<String> attachmentNames, Rule<?> rule) {
this.attachmentNames = attachmentNames;
this.rule = rule;
}
/**
* Get the list of attachment names.
*
* @return attachment names
*/
public List<String> getAttachmentNames() {
return attachmentNames;
}
/**
* Get the rule.
*
* @return rule
*/
public Rule<?> getRule() {
return rule;
}
}
@@ -0,0 +1,172 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.ConfigurationValue;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.util.LoggerUtils;
/**
* A loader that will load rule definitions for the RuleLists.
*/
public class RuleEntryLoader extends AbstractNodeLoader<RuleEntry> {
public static final String INLINE = "_";
private static Logger logger = LoggerUtils.getLogger(RuleEntryLoader.class, "[WorldGuard] RuleList: ");
private final DefinitionLoader<Criteria<?>> criteriaLoader;
private final DefinitionLoader<Action<?>> actionLoader;
/**
* Construct the loader.
*
* @param ruleListsManager the action lists manager
*/
public RuleEntryLoader(RuleListsManager ruleListsManager) {
criteriaLoader = new DefinitionLoader<Criteria<?>>(ruleListsManager.getCriterion(), true);
actionLoader = new DefinitionLoader<Action<?>>(ruleListsManager.getActions(), false);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public RuleEntry read(ConfigurationNode node) {
if (node.size() == 0) {
return null;
}
List<String> when = node.getStringList("when", new ArrayList<String>());
// Check to see if the rule has any events defined
if (when.size() == 0) {
logger.warning("A rule has missing 'when' clause:\n" + node.toString());
return null;
}
try {
DefinedRule rule = new DefinedRule();
// Get criterion from the 'if' subnode
for (Criteria criteria : node.listOf("if", criteriaLoader)) {
rule.add(criteria);
}
// Get actions from the 'then' subnode
for (Action action : node.listOf("then", actionLoader)) {
rule.add(action);
}
// A rule needs actions!
if (rule.hasActions()) {
return new RuleEntry(when, rule);
} else {
logger.warning("The following rule has no actions in:\n" + node.toString());
return null;
}
} catch (LoaderBuilderException e) {
logger.warning("A rule had the error '" + e.getMessage() + ", and the rule is:\n" + node.toString());
return null;
}
}
/**
* Inverts an criteria, wrapping it in a {@link InvertedCriteria}.
*
* @param criteria to invert
* @param inverted true to invert (false to not)
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <V> V invertCriteria(V object, boolean inverted) {
if (object instanceof Criteria && inverted) {
return (V) new InvertedCriteria((Criteria<?>) object);
}
return object;
}
/**
* Loads specific definitions (criterion or actions) defined.
*
* @param <T> type of definition ({@link Action} or {@link Criteria})
*/
private class DefinitionLoader<T> extends AbstractNodeLoader<T> {
private final DefinitionManager<T> manager;
private final boolean strict;
/**
* Construct the object.
*
* @param manager the definition manager
* @param strict true to throw exceptions on error
*/
public DefinitionLoader(DefinitionManager<T> manager, boolean strict) {
this.manager = manager;
this.strict = strict;
}
@Override
public T read(ConfigurationNode node) {
String id = node.getString("?");
boolean inverted = node.getBoolean("negate", false);
try {
// Check for long hand notation (?: class)
if (id != null) {
return invertCriteria(manager.newInstance(id, node, null), inverted);
}
// Check for short-hand notation (?class: value)
for (String key : node.getKeys(ConfigurationNode.ROOT)) {
if (key.startsWith("?")) {
id = key;
Object value = node.get(key);
return invertCriteria(
manager.newInstance(key.substring(1), node, new ConfigurationValue(value)), inverted);
}
}
// No class defined!
logger.warning("EventListeners: Missing '?' parameter in definition " +
"(to define what kind of criteria/action it is)");
return null;
} catch (DefinitionException e) {
logger.warning("EventListeners: Invalid definition " +
"identified by type '" + id + "': " + e.getMessage());
// Throw an exception in strict mode
if (strict) {
throw new LoaderBuilderException();
}
return null;
}
}
}
}
@@ -0,0 +1,65 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.List;
import java.util.logging.Logger;
import com.sk89q.rebar.config.ConfigurationNode;
/**
* RuleList-related utility methods.
*/
public class RuleListUtils {
private RuleListUtils() {
}
/**
* Warn of unknown directives in a rule list block.
*
* @param node node
* @param logger the logger to send to
* @param expected expected keys
*/
public static void warnUnknown(ConfigurationNode node, Logger logger, String ... expected) {
List<String> keys = node.getKeys(ConfigurationNode.ROOT);
for (String key : keys) {
boolean found = false;
if (key.equals("?")) continue;
if (key.equals("negate")) continue;
if (key.equals("_")) continue;
if (key.length() > 0 && key.charAt(0) == '?') continue;
for (String expect : expected) {
if (expect.equals(key)) {
found = true;
break;
}
}
if (!found) {
logger.warning("[WorldGuard] RuleList: Unexpected parameter of '" + key + "' in " + node);
}
}
}
}
@@ -0,0 +1,77 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
/**
* Manages action lists and details relevant to them.
*/
public class RuleListsManager {
private final AttachmentManager attachments = new AttachmentManager();
private final DefinitionManager<Criteria<?>> criterion = new DefinitionManager<Criteria<?>>();
private final DefinitionManager<Action<?>> actions = new DefinitionManager<Action<?>>();
private final ResolverManager subjectResolvers = new ResolverManager();
private final ExpressionParser exprParser = new ExpressionParser();
/**
* Get the attachment manager.
*
* @return the attachment manager
*/
public AttachmentManager getAttachments() {
return attachments;
}
/**
* Get the criterion manager.
*
* @return criteron manager
*/
public DefinitionManager<Criteria<?>> getCriterion() {
return criterion;
}
/**
* Get the actions manager.
*
* @return actions manager
*/
public DefinitionManager<Action<?>> getActions() {
return actions;
}
/**
* Get the subject resolvers manager.
*
* @return the subject resolvers manager
*/
public ResolverManager getResolvers() {
return subjectResolvers;
}
/**
* Get the expression parser.
*
* @return the expression parser
*/
public ExpressionParser getParser() {
return exprParser;
}
}
@@ -0,0 +1,61 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.LinkedList;
import java.util.List;
public class RuleSet implements Attachment {
private List<Rule<?>> rules = new LinkedList<Rule<?>>();
@Override
public void learn(Rule<?> rule) {
rules.add(rule);
}
@Override
public void forgetRules() {
rules.clear();
}
public boolean hasRules() {
return rules.size() > 0;
}
public List<Rule<?>> getRules() {
return rules;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean process(Context context) {
if (context.isCancelled()) {
return true; // Ignore cancelled events for now
}
for (Rule rule : rules) {
if (rule.matches(context)) {
rule.apply(context);
}
}
return context.isCancelled();
}
}
@@ -0,0 +1,131 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.rulelists;
import java.util.ArrayList;
import java.util.List;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.StringLoaderBuilder;
/**
* A loader that will load the built-in rules used. It handles a slightly different
* format that also stores parameter information and other goodies.
*/
public class RuleTemplateEntryLoader extends AbstractNodeLoader<List<RuleEntry>> {
private static final StringLoaderBuilder stringLoader = new StringLoaderBuilder();
private final ConfigurationNode config;
private final RuleEntryLoader entryLoader;
/**
* Construct the loader with the given rule lists manager.
*
* @param manager the manager
* @param config the configuration node to read settings from
*/
public RuleTemplateEntryLoader(RuleListsManager manager, ConfigurationNode config) {
entryLoader = new RuleEntryLoader(manager);
this.config = config;
}
@Override
public List<RuleEntry> read(ConfigurationNode node) throws LoaderBuilderException {
List<RuleEntry> rules = new ArrayList<RuleEntry>();
List<String> settings = node.listOf("setting", stringLoader);
if (settings.size() == 0) {
throw new LoaderBuilderException("No 'setting' value in:\n" + node.toString());
}
String selectedSetting = settings.get(0);
String type = node.getString("type", "boolean");
if (settings.size() > 1) {
boolean migrate = false;
boolean found = false;
Object value = null;
for (String setting : settings) {
if (config.contains(setting)) {
value = config.get(setting);
found = true;
break;
} else {
migrate = true;
}
}
if (found && migrate) {
config.set(settings.get(0), value);
int i = 0;
for (String setting : settings) {
if (i++ != 0) {
config.remove(setting);
}
}
}
}
boolean active = false;
// See if the setting is active
if (type.equals("boolean")) {
boolean negate = node.getBoolean("negate", false);
boolean enabled = config.getBoolean(selectedSetting, negate);
if (negate) {
enabled = !enabled;
}
if (enabled) {
active = true;
}
} else if (type.equals("list")) {
Object val = config.get(selectedSetting);
if (val == null) {
config.set(selectedSetting, new ArrayList<Object>());
} else if (val instanceof List<?> && ((List<?>) val).size() > 0) {
active = true;
}
}
// Load the setting
if (active) {
List<String> paramPaths = node.getStringList("parameters.target", new ArrayList<String>());
if (paramPaths.size() > 0) {
Object val = config.get(selectedSetting);
for (String path : paramPaths) {
node.set(path, val);
}
}
for (RuleEntry rule : node.listOf("rules", entryLoader)) {
rules.add(rule);
}
}
return rules;
}
}
@@ -0,0 +1,103 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.inventory.ItemStack;
import com.sk89q.rulelists.Context;
public class BukkitContext extends Context {
private final Event event;
private String message;
private Entity sourceEntity;
private Entity targetEntity;
private ItemStack item;
private BlockState sourceBlock;
private BlockState targetBlock;
private BlockState replacedTargetBlock;
public BukkitContext(Event event) {
this.event = event;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Entity getSourceEntity() {
return sourceEntity;
}
public void setSourceEntity(Entity sourceEntity) {
this.sourceEntity = sourceEntity;
}
public Entity getTargetEntity() {
return targetEntity;
}
public void setTargetEntity(Entity targetEntity) {
this.targetEntity = targetEntity;
}
public ItemStack getItem() {
return item;
}
public void setItem(ItemStack item) {
this.item = item;
}
public BlockState getSourceBlock() {
return sourceBlock;
}
public void setSourceBlock(BlockState block) {
this.sourceBlock = block;
}
public BlockState getTargetBlock() {
return targetBlock;
}
public void setTargetBlock(BlockState targetBlock) {
this.targetBlock = targetBlock;
}
public BlockState getPlacedBlock() {
return replacedTargetBlock;
}
public void setPlacedBlock(BlockState replacedTargetBlock) {
this.replacedTargetBlock = replacedTargetBlock;
}
public Event getEvent() {
return event;
}
}
@@ -0,0 +1,99 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.RegionQueryCache;
/**
* An implementation of {@link RegionQueryCache} for Bukkit. This implementation is
* thread-safe.
*/
public class BukkitRegionQueryCache extends RegionQueryCache {
private final WorldGuardPlugin plugin;
/**
* Construct the cache with the given plugin instance.
*
* @param plugin plugin instance
*/
public BukkitRegionQueryCache(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Get an {@link ApplicableRegionSet} for a given location. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given location.
*
* @param event the event to cache against
* @param location the location to check
* @return the set, or null if region protection is disabled for the given location
*/
public ApplicableRegionSet lookup(Event event, Location location) {
World world = location.getWorld();
Vector vector = BukkitUtil.toVector(location);
ConfigurationManager config = plugin.getGlobalStateManager();
WorldConfiguration worldConfig = config.get(world);
GlobalRegionManager regionManager = plugin.getGlobalRegionManager();
if (!worldConfig.useRegions) {
return null;
}
return get(event).lookup(regionManager.get(world), vector);
}
/**
* Get an {@link ApplicableRegionSet} for a given block. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given block.
*
* @param event the event to cache against
* @param block the block to check
* @return the set, or null if region protection is disabled for the given block
*/
public ApplicableRegionSet lookup(Event event, Block block) {
return lookup(event, block.getLocation());
}
/**
* Get an {@link ApplicableRegionSet} for a given entity. The result may have been
* temporarily cached for the given event, or null if region protection has
* been disabled for the the world of the given entity.
*
* @param event the event to cache against
* @param entity the entity to check
* @return the set, or null if region protection is disabled for the given entity
*/
public ApplicableRegionSet lookup(Event event, Entity entity) {
return lookup(event, entity.getLocation());
}
}
@@ -31,6 +31,7 @@ import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class BukkitUtil {
@@ -142,27 +143,6 @@ public class BukkitUtil {
return id == 8 || id == 9;
}
/**
* Checks if the given potion is a vial of water.
*
* @param item the item to check
* @return true if it's a water vial
*/
public static boolean isWaterPotion(ItemStack item) {
return (item.getDurability() & 0x3F) == 0;
}
/**
* Get just the potion effect bits. This is to work around bugs with potion
* parsing.
*
* @param item item
* @return new bits
*/
public static int getPotionEffectBits(ItemStack item) {
return item.getDurability() & 0x3F;
}
/**
* Find a position for the player to stand that is not inside a block.
* Blocks above the player will be iteratively tested until there is
@@ -245,22 +225,6 @@ public class BukkitUtil {
return str;
}
/**
* Returns whether an entity should be removed for the halt activity mode.
*
* @param entity
* @return true if it's to be removed
*/
public static boolean isIntensiveEntity(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingSand
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
/**
* Returns whether our running CraftBukkit already supports
* the HangingEvent instead of the PaintingEvent
@@ -18,15 +18,6 @@
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
@@ -35,86 +26,70 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.PairedKeyValueLoaderBuilder;
import com.sk89q.rebar.config.YamlConfigurationFile;
import com.sk89q.rebar.config.YamlStyle;
import com.sk89q.rebar.config.types.LowercaseStringLoaderBuilder;
import com.sk89q.rebar.config.types.StringLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.RuleEntryLoader;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.Blacklist;
/**
* Represents the global configuration and also delegates configuration
* for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class ConfigurationManager {
private static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's main configuration file\r\n" +
"#\r\n" +
"# This is the global configuration file. Anything placed into here will\r\n" +
"# be applied to all worlds. However, each world has its own configuration\r\n" +
"# file to allow you to replace most settings in here for that world only.\r\n" +
"#\r\n" +
"# About editing this file:\r\n" +
"# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
"# you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
"# must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
"# be changed in Settings > Preferences > Language Menu.\r\n" +
"# - Don't get rid of the indents. They are indented so some entries are\r\n" +
"# in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
"# category.\r\n" +
"# - If you want to check the format of this file before putting it\r\n" +
"# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/\r\n" +
"# and see if it gives \"ERROR:\".\r\n" +
"# - Lines starting with # are comments and so they are ignored.\r\n" +
"#\r\n";
private static Logger logger = LoggerUtils.getLogger(RuleEntryLoader.class, "[WorldGuard] ");
private static final String DEFAULT_RULELIST_PATH = "rulelist.yml";
private static final String DEFAULT_BLACKLIST_PATH = "worlds/%world%/blacklist.txt";
private static final String DEFAULT_WORLD_CONFIG_PATH = "worlds/%world%/config.yml";
static final YamlStyle YAML_STYLE = new YamlStyle(FlowStyle.BLOCK);
/**
* Reference to the plugin.
*/
private WorldGuardPlugin plugin;
/**
* Holds configurations for different worlds.
*/
private ConcurrentMap<String, WorldConfiguration> worlds;
private YamlConfigurationFile config;
/**
* The global configuration for use when loading worlds
*/
private YAMLProcessor config;
private Map<String, String> ruleLists = new HashMap<String, String>();
private Map<String, String> blacklists = new HashMap<String, String>();
private Map<String, String> worldConfigs = new HashMap<String, String>();
/**
* List of people with god mode.
*/
@Deprecated
private Set<String> hasGodMode = new HashSet<String>();
/**
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
/* Configuration data start */
public boolean useRegionsScheduler;
public boolean useRegionsCreatureSpawnEvent;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
public boolean deopOnJoin;
public boolean blockInGameOp;
public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
public boolean useSqlDatabase = false;
public String sqlDsn;
public String sqlUsername;
public String sqlPassword;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin The plugin instance
* @param plugin the plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -124,59 +99,66 @@ public class ConfigurationManager {
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
plugin.createDefaultConfiguration(
new File(plugin.getDataFolder(), "config.yml"), "config.yml");
loadConfig();
config = new YAMLProcessor(new File(plugin.getDataFolder(), "config.yml"), true, YAMLFormat.EXTENDED);
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for global config: ");
e.printStackTrace();
}
config.removeProperty("suppress-tick-sync-warnings");
// Regions settings
useRegionsScheduler = config.getBoolean("regions.use-scheduler", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
autoGodMode = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean("use-player-move-event", true);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
hostKeys = new HashMap<String, String>();
Object hostKeysRaw = config.getProperty("host-keys");
if (hostKeysRaw == null || !(hostKeysRaw instanceof Map)) {
config.setProperty("host-keys", new HashMap<String, String>());
} else {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) hostKeysRaw).entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
hostKeys.put(key.toLowerCase(), value);
}
}
useSqlDatabase = config.getBoolean(
"regions.sql.use", false);
// Regions SQL settings
useSqlDatabase = config.getBoolean("regions.sql.use", false);
sqlDsn = config.getString("regions.sql.dsn", "jdbc:mysql://localhost/worldguard");
sqlUsername = config.getString("regions.sql.username", "worldguard");
sqlPassword = config.getString("regions.sql.password", "worldguard");
// Other settings
usePlayerMove = config.getBoolean("use-player-move-event", true);
// Load host keys
hostKeys = config.mapOf("host-keys",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
// Load rule list filenames
if (config.contains("rulelists")) {
ruleLists = config.mapOf("rulelists",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("rulelists").set("__default__", DEFAULT_RULELIST_PATH);
ruleLists = new HashMap<String, String>();
ruleLists.put("__default__", DEFAULT_RULELIST_PATH);
}
// Load blacklist filenames
if (config.contains("blacklists")) {
blacklists = config.mapOf("blacklists",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("blacklists").set("__default__", DEFAULT_BLACKLIST_PATH);
blacklists = new HashMap<String, String>();
blacklists.put("__default__", DEFAULT_BLACKLIST_PATH);
}
// Load world config filenames
if (config.contains("world-configs")) {
worldConfigs = config.mapOf("world-configs",
PairedKeyValueLoaderBuilder.build(
new LowercaseStringLoaderBuilder(), new StringLoaderBuilder()));
} else {
config.setNode("world-configs").set("__default__", DEFAULT_WORLD_CONFIG_PATH);
worldConfigs = new HashMap<String, String>();
worldConfigs.put("__default__", DEFAULT_WORLD_CONFIG_PATH);
}
// Load configurations for each world
for (World world : plugin.getServer().getWorlds()) {
get(world);
}
config.setHeader(CONFIG_HEADER);
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
}
saveConfig();
}
/**
@@ -186,6 +168,41 @@ public class ConfigurationManager {
worlds.clear();
}
/**
* Load the configuration from file.
*/
private void loadConfig() {
config = new YamlConfigurationFile(new File(plugin.getDataFolder(), "config.yml"), YAML_STYLE);
try {
config.load();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading config.yml for global config", e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Error reading config.yml for global config", e);
}
}
/**
* Save the configuration to file.
*/
private void saveConfig() {
config.setHeader(
"# GLOBAL CONFIGURATION FILE\r\n" +
"#\r\n" +
"# Everything in here applies to all worlds. For world-specific settings, edit \r\n" +
"# the files in plugins/WorldGuard/worlds/WORLD_NAME_HERE/config.yml\r\n" +
"#\r\n" +
"# The official format of this file is called YAML. If you've never had to\r\n" +
"# edit one before, you should REALLY read http://wiki.sk89q.com/wiki/Editing_YAML\r\n");
try {
config.save();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to save configuration", e);
}
}
/**
* Get the configuration for a world.
*
@@ -199,7 +216,7 @@ public class ConfigurationManager {
while (config == null) {
if (newConfig == null) {
newConfig = new WorldConfiguration(plugin, worldName, this.config);
newConfig = new WorldConfiguration(plugin, worldName, this, this.config);
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
@@ -208,12 +225,91 @@ public class ConfigurationManager {
return config;
}
/**
* Get the RuleList file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getRuleListFile(String worldName) {
String path = ruleLists.get(worldName.toLowerCase());
if (path == null) {
path = ruleLists.get("__default__");
}
if (path == null) {
path = DEFAULT_RULELIST_PATH;
}
path = path.replace("%world%", worldName);
File file = new File(plugin.getDataFolder(), path);
if (!file.exists()) {
plugin.createDefaultConfiguration(file, "rulelist.yml");
}
return file;
}
/**
* Get the blacklist file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getBlacklistFile(String worldName) {
String path = blacklists.get(worldName.toLowerCase());
File file;
if (path == null) {
path = blacklists.get("__default__");
}
if (path == null) {
path = DEFAULT_BLACKLIST_PATH;
}
path = path.replace("%world%", worldName);
file = new File(plugin.getDataFolder(), path);
if (!file.exists()) {
plugin.createDefaultConfiguration(file, "blacklist.txt");
}
return file;
}
/**
* Get the world configuration file for the given world.
*
* @param worldName world
* @return file (which may or may not exist)
*/
File getWorldConfigFile(String worldName) {
String path = worldConfigs.get(worldName.toLowerCase());
File file;
if (path == null) {
path = worldConfigs.get("__default__");
}
if (path == null) {
path = DEFAULT_WORLD_CONFIG_PATH;
}
path = path.replace("%world%", worldName);
file = new File(plugin.getDataFolder(), path);
return file;
}
/**
* Forget a player.
*
* @param player The player to forget about
*/
public void forgetPlayer(LocalPlayer player) {
void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
: worlds.entrySet()) {
@@ -235,7 +331,6 @@ public class ConfigurationManager {
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
@@ -293,7 +388,10 @@ public class ConfigurationManager {
return hasAmphibious.contains(player.getName());
}
public void updateCommandBookGodMode() {
/**
* Check and store whether CommandBook is installed.
*/
void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
Class.forName("com.sk89q.commandbook.GodComponent");
@@ -304,7 +402,12 @@ public class ConfigurationManager {
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
/**
* Return whether CommandBook is available for God mode usage.
*
* @return true if it available
*/
boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
}
@@ -19,18 +19,19 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.HashMap;
import java.util.Map;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* This processes per-player state information and is also meant to be used
@@ -59,6 +60,7 @@ public class FlagStateManager implements Runnable {
/**
* Run the task.
*/
@Override
public void run() {
Player[] players = plugin.getServer().getOnlinePlayers();
ConfigurationManager config = plugin.getGlobalStateManager();
@@ -82,8 +84,10 @@ public class FlagStateManager implements Runnable {
}
Vector playerLocation = toVector(player.getLocation());
RegionManager regionManager = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet applicable = regionManager.getApplicableRegions(playerLocation);
RegionManager regionManager = plugin.getGlobalRegionManager()
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
@@ -121,10 +125,6 @@ public class FlagStateManager implements Runnable {
if (minHealth == null) minHealth = 0;
if (maxHealth == null) maxHealth = 20;
// Apply a cap to prevent possible exceptions
minHealth = Math.min(player.getMaxHealth(), minHealth);
maxHealth = Math.min(player.getMaxHealth(), maxHealth);
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
@@ -162,10 +162,6 @@ public class FlagStateManager implements Runnable {
if (minHunger == null) minHunger = 0;
if (maxHunger == null) maxHunger = 20;
// Apply a cap to prevent possible exceptions
minHunger = Math.min(20, minHunger);
maxHunger = Math.min(20, maxHunger);
if (player.getFoodLevel() >= maxHunger && feedAmount > 0) {
return;
}
@@ -0,0 +1,305 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.PluginManager;
import com.sk89q.rebar.util.LoggerUtils;
/**
* Handles the "stop lag" mode.
*/
public class LagStopMode implements Listener {
private static final Logger logger = LoggerUtils.getLogger(LagStopMode.class,
"[WorldGuard] Lag Stop Mode: ");
private final WorldGuardPlugin plugin;
private boolean enabled = false;
private boolean removeAnimals = true;
LagStopMode(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register this class's events.
*/
void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
/**
* Get whether the lag stop mode is enabled.
*
* @return true if it's enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enable the lag stop mode. This will start the process and emit messages.
*
* @param unloadChunks true to unload chunks
*/
public void enable(boolean unloadChunks) {
if (!enabled) {
Server server = plugin.getServer();
server.broadcastMessage(ChatColor.GRAY
+ "(WorldGuard's 'lag stop' mode has been enabled. Some parts of the game may be 'frozen'. Keep calm and carry on.)");
// Remove entities
server.broadcastMessage(ChatColor.GRAY + "(Please wait... removing entities...)");
for (World world : server.getWorlds()) {
freeUp(world);
}
// Unloading chunks
if (unloadChunks) {
server.broadcastMessage(ChatColor.GRAY + "(Please wait... garbage collecting chunks...)");
for (World world : server.getWorlds()) {
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
chunk.unload(true, true);
}
}
}
server.broadcastMessage(ChatColor.GRAY + "(Completed. Lag stop mode is still enabled.)");
}
this.enabled = true;
}
/**
* Disable the lag stop mode.
*/
public void disable() {
if (enabled) {
Server server = plugin.getServer();
server.broadcastMessage(ChatColor.GRAY
+ "(WorldGuard's 'lag stop' mode is now off. Everything should proceed to start working again.)");
}
this.enabled = false;
}
/**
* Returns whether animals are being removed.
*
* @return true if animals are being removed
*/
public boolean isRemovingAnimals() {
return removeAnimals;
}
/**
* Set whether animals should be removed.
*
* @param removeAnimals true to remove animals
*/
public void setRemoveAnimals(boolean removeAnimals) {
this.removeAnimals = removeAnimals;
}
/**
* Remove items and other things within the chunk.
*
* @param plugin the plugin
* @param chunk the chunk to halt
*/
private void freeUp(Chunk chunk) {
int removed = 0;
for (Entity entity : chunk.getEntities()) {
if (shouldRemove(entity)) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info(removed + " entities (>50) auto-removed from " + chunk.toString());
}
}
/**
* Remove items and other things within the world.
*
* @param plugin the plugin
* @param world the world to halt
*/
private void freeUp(World world) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (shouldRemove(entity)) {
entity.remove();
removed++;
}
}
if (removed > 50) {
logger.info(removed + " entities (>50) auto-removed from " + world.toString());
}
}
/**
* Returns whether an entity should be removed.
*
* @param entity the entity to check
* @return true if it should be removed
*/
private boolean shouldRemove(Entity entity) {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingBlock
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player)
&& (removeAnimals || !(entity instanceof Animals)));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
if (enabled) {
player.sendMessage(ChatColor.GRAY
+ "WorldGuard's 'lag stop' mode has been enabled. Some parts of the game may be 'frozen'.");
freeUp(world);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockFromTo(BlockFromToEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockIgnite(BlockIgniteEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBurn(BlockBurnEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockForm(BlockFormEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onLeavesDecay(LeavesDecayEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockSpread(BlockSpreadEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityExplode(EntityExplodeEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (enabled) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
if (enabled) {
freeUp(event.getChunk());
}
}
}
@@ -20,6 +20,7 @@
package com.sk89q.worldguard.bukkit;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
@@ -27,8 +28,6 @@ import org.bukkit.command.CommandSender;
/**
* Sends all logger messages to a player.
*
* @author sk89q
*/
public class LoggerToChatHandler extends Handler {
/**
@@ -64,7 +63,12 @@ public class LoggerToChatHandler extends Handler {
*/
@Override
public void publish(LogRecord record) {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.WHITE + record.getMessage());
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
player.sendMessage(ChatColor.RED + record.getLevel().getName() + ": "
+ ChatColor.YELLOW + record.getMessage());
} else {
player.sendMessage(ChatColor.GRAY + record.getLevel().getName() + ": "
+ ChatColor.WHITE + record.getMessage());
}
}
}
@@ -0,0 +1,196 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.sk89q.worldedit.blocks.BlockID;
/**
* An applicator of the sponge feature.
*/
class SpongeApplicator {
private final int spongeRadius;
private final boolean useRedstone;
private final boolean refillArea;
/**
* Construct a new applicator.
*
* @param spongeRadius the radius of the sponge's effect
* @param useRedstone use Redstone
* @param refillArea refill the area if a sponge is removed
*/
public SpongeApplicator(int spongeRadius, boolean useRedstone, boolean refillArea) {
this.spongeRadius = spongeRadius;
this.useRedstone = useRedstone;
this.refillArea = refillArea;
}
/**
* Returns whether the block at the given position is water.
*
* @param world world
* @param x x
* @param y y
* @param z z
* @return true if it's water
*/
private static boolean isWater(World world, int x, int y, int z) {
int type = world.getBlockTypeIdAt(x, y, z);
return type == BlockID.WATER || type == BlockID.STATIONARY_WATER;
}
/**
* Returns whether the given sponge is an active sponge.
*
* @param block block to check
* @return true if it's active
*/
public boolean isActiveSponge(Block block) {
return block.getType() == Material.SPONGE
&& (!useRedstone || !block.isBlockIndirectlyPowered());
}
/**
* Return true if a given block near an active sponge.
*
* @param blockTo location of the block
* @return true if it's near a sponge (and water should be cancelled)
*/
public boolean isNearSponge(Block blockTo) {
World world = blockTo.getWorld();
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (isActiveSponge(sponge)) {
return true;
}
}
}
}
return false;
}
/**
* Remove water due to a sponge from the given position.
*
* @param block the block
*/
public void clearWater(Block block) {
World world = block.getWorld();
int ox = block.getX();
int oy = block.getY();
int oz = block.getZ();
for (int cx = -spongeRadius; cx <= spongeRadius; cx++) {
for (int cy = -spongeRadius; cy <= spongeRadius; cy++) {
for (int cz = -spongeRadius; cz <= spongeRadius; cz++) {
if (isWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water due to a sponge from the given position.
*
* @param block the block
*/
public void placeWater(Block block) {
if (!refillArea) return;
World world = block.getWorld();
int ox = block.getX();
int oy = block.getY();
int oz = block.getZ();
// The negative x edge
int cx = ox - spongeRadius - 1;
for (int cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx + 1, cy, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The positive x edge
cx = ox + spongeRadius + 1;
for (int cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx - 1, cy, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The negative y edge
int cy = oy - spongeRadius - 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy + 1, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The positive y edge
cy = oy + spongeRadius + 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (int cz = oz - spongeRadius - 1; cz <= oz + spongeRadius + 1; cz++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy - 1, cz).setType(Material.STATIONARY_WATER);
}
}
}
// The negative z edge
int cz = oz - spongeRadius - 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy, cz + 1).setType(Material.STATIONARY_WATER);
}
}
}
// The positive z edge
cz = oz + spongeRadius + 1;
for (cx = ox - spongeRadius - 1; cx <= ox + spongeRadius + 1; cx++) {
for (cy = oy - spongeRadius - 1; cy <= oy + spongeRadius + 1; cy++) {
if (isWater(world, cx, cy, cz)) {
world.getBlockAt(cx, cy, cz - 1).setType(Material.STATIONARY_WATER);
}
}
}
}
}
@@ -1,126 +0,0 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.isBlockWater;
import static com.sk89q.worldguard.bukkit.BukkitUtil.setBlockToWater;
import org.bukkit.World;
public class SpongeUtil {
/**
* Remove water around a sponge.
*
* @param plugin The plugin instace
* @param world The world the sponge isin
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void clearSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water around a sponge.
*
* @param plugin The plugin instance
* @param world The world the sponge is located in
* @param ox The x coordinate of the 'sponge' block
* @param oy The y coordinate of the 'sponge' block
* @param oz The z coordinate of the 'sponge' block
*/
public static void addSpongeWater(WorldGuardPlugin plugin, World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// The negative x edge
int cx = ox - wcfg.spongeRadius - 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx + 1, cy, cz);
}
}
}
// The positive x edge
cx = ox + wcfg.spongeRadius + 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx - 1, cy, cz);
}
}
}
// The negative y edge
int cy = oy - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy + 1, cz);
}
}
}
// The positive y edge
cy = oy + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy - 1, cz);
}
}
}
// The negative z edge
int cz = oz - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz + 1);
}
}
}
// The positive z edge
cz = oz + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz - 1);
}
}
}
}
}
@@ -1,73 +0,0 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Helper class to get a reference to WorldGuard and its components.
*/
public class WGBukkit {
private static WorldGuardPlugin cachedPlugin = null;
private WGBukkit() {
}
/**
* Get the WorldGuard plugin. If WorldGuard isn't loaded yet, then this will
* return null.
* <p>
* If you are depending on WorldGuard in your plugin, you should place
* <code>softdepend: [WorldGuard]</code> or <code>depend: [WorldGuard]</code>
* in your plugin.yml so that this won't return null for you.
*
* @return the WorldGuard plugin or null
*/
public static WorldGuardPlugin getPlugin() {
if (cachedPlugin == null) {
cachedPlugin = (WorldGuardPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
}
return cachedPlugin;
}
/**
* Set cache to null for reload WorldGuardPlugin
*/
public static void cleanCache() {
cachedPlugin = null;
}
/**
* Returns the region manager for a given world. May return null if WorldGuard
* is not loaded or region protection is not enabled for the given world.
*
* @param world world
* @return a region manager or null
*/
public static RegionManager getRegionManager(World world) {
if (getPlugin() == null) {
return null;
}
return cachedPlugin.getRegionManager(world);
}
}
@@ -22,21 +22,24 @@ package com.sk89q.worldguard.bukkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.YamlConfigurationFile;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.KnownAttachmentRules;
import com.sk89q.rulelists.RuleEntry;
import com.sk89q.rulelists.RuleEntryLoader;
import com.sk89q.rulelists.RuleTemplateEntryLoader;
import com.sk89q.worldguard.blacklist.Blacklist;
import com.sk89q.worldguard.blacklist.BlacklistLogger;
import com.sk89q.worldguard.blacklist.loggers.ConsoleLoggerHandler;
@@ -47,372 +50,101 @@ import com.sk89q.worldguard.chest.SignChestProtection;
/**
* Holds the configuration for individual worlds.
*
* @author sk89q
* @author Michael
*/
public class WorldConfiguration {
public static final String CONFIG_HEADER = "#\r\n" +
"# WorldGuard's world configuration file\r\n" +
"#\r\n" +
"# This is a world configuration file. Anything placed into here will only\r\n" +
"# affect this world. If you don't put anything in this file, then the\r\n" +
"# settings will be inherited from the main configuration file.\r\n" +
"#\r\n" +
"# If you see {} below, that means that there are NO entries in this file.\r\n" +
"# Remove the {} and add your own entries.\r\n" +
"#\r\n";
private static Logger logger = LoggerUtils.getLogger(WorldConfiguration.class, "[WorldGuard] ");
private WorldGuardPlugin plugin;
private String worldName;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File blacklistFile;
private final WorldGuardPlugin plugin;
private final ConfigurationManager configMan;
private final YamlConfigurationFile config;
private final String worldName;
private Blacklist blacklist;
private KnownAttachmentRules ruleList = new KnownAttachmentRules();
private ChestProtection chestProtection = new SignChestProtection();
private SpongeApplicator spongeApplicator = null;
/* Configuration data start */
public boolean summaryOnStart;
public boolean opPermissions;
public boolean fireSpreadDisableToggle;
public boolean itemDurability;
public boolean simulateSponge;
public int spongeRadius;
public boolean disableExpDrops;
public Set<PotionEffectType> blockPotions;
public boolean blockPotionsAlways;
public boolean pumpkinScuba;
public boolean redstoneSponges;
public boolean noPhysicsGravel;
public boolean noPhysicsSand;
public boolean ropeLadders;
public boolean allowPortalAnywhere;
public Set<Integer> preventWaterDamage;
public boolean blockLighter;
public boolean disableFireSpread;
public Set<Integer> disableFireSpreadBlocks;
public boolean preventLavaFire;
public Set<Integer> allowedLavaSpreadOver;
public boolean blockTNTExplosions;
public boolean blockTNTBlockDamage;
public boolean blockCreeperExplosions;
public boolean blockCreeperBlockDamage;
public boolean blockWitherExplosions;
public boolean blockWitherBlockDamage;
public boolean blockWitherSkullExplosions;
public boolean blockWitherSkullBlockDamage;
public boolean blockEnderDragonBlockDamage;
public boolean blockEnderDragonPortalCreation;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockOtherExplosions;
public boolean blockEntityPaintingDestroy;
public boolean blockEntityItemFrameDestroy;
public boolean blockPluginSpawning;
public boolean blockGroundSlimes;
public boolean blockZombieDoorDestruction;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
public boolean disableFireDamage;
public boolean disableLightningDamage;
public boolean disableDrowningDamage;
public boolean disableSuffocationDamage;
public boolean teleportOnSuffocation;
public boolean disableVoidDamage;
public boolean teleportOnVoid;
public boolean disableExplosionDamage;
public boolean disableMobDamage;
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand;
public Set<EntityType> blockCreatureSpawn;
public boolean regionInvinciblityRemovesMobs;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
public int maxClaimVolume;
public boolean claimOnlyInsideExistingRegions;
public int maxRegionCountPerPlayer;
public boolean antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
public boolean preventLightningFire;
public Set<Integer> disallowedLightningBlocks;
public boolean disableThunder;
public boolean disableWeather;
public boolean alwaysRaining;
public boolean alwaysThundering;
public boolean disablePigZap;
public boolean disableCreeperPower;
public boolean disableHealthRegain;
public boolean disableMushroomSpread;
public boolean disableIceMelting;
public boolean disableSnowMelting;
public boolean disableSnowFormation;
public boolean disableIceFormation;
public boolean disableLeafDecay;
public boolean disableGrassGrowth;
public boolean disableMyceliumSpread;
public boolean disableVineGrowth;
public boolean disableEndermanGriefing;
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
public boolean fireSpreadDisableToggle;
/* Configuration data end */
/**
* Construct the object.
*
* @param plugin The WorldGuardPlugin instance
* @param worldName The world name that this WorldConfiguration is for.
* @param parentConfig The parent configuration to read defaults from
* @param plugin the plugin instance
* @param worldName name of the world that this object is for
* @param configMan configuration manager
* @param parentConfig parent configuration
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
File configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
public WorldConfiguration(WorldGuardPlugin plugin, String worldName,
ConfigurationManager configMan, ConfigurationNode parentConfig) {
this.plugin = plugin;
this.worldName = worldName;
this.parentConfig = parentConfig;
this.configMan = configMan;
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
File file = configMan.getWorldConfigFile(worldName);
config = new YamlConfigurationFile(file, ConfigurationManager.YAML_STYLE);
config.setParent(parentConfig);
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
if (summaryOnStart) {
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
}
}
private boolean getBoolean(String node, boolean def) {
boolean val = parentConfig.getBoolean(node, def);
if (config.getProperty(node) != null) {
return config.getBoolean(node, def);
} else {
return val;
}
}
private String getString(String node, String def) {
String val = parentConfig.getString(node, def);
if (config.getProperty(node) != null) {
return config.getString(node, def);
} else {
return val;
}
}
private int getInt(String node, int def) {
int val = parentConfig.getInt(node, def);
if (config.getProperty(node) != null) {
return config.getInt(node, def);
} else {
return val;
}
}
@SuppressWarnings("unused")
private double getDouble(String node, double def) {
double val = parentConfig.getDouble(node, def);
if (config.getProperty(node) != null) {
return config.getDouble(node, def);
} else {
return val;
}
}
private List<Integer> getIntList(String node, List<Integer> def) {
List<Integer> res = parentConfig.getIntList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<Integer>());
}
if (config.getProperty(node) != null) {
res = config.getIntList(node, def);
}
return res;
}
private List<String> getStringList(String node, List<String> def) {
List<String> res = parentConfig.getStringList(node, def);
if (res == null || res.size() == 0) {
parentConfig.setProperty(node, new ArrayList<String>());
}
if (config.getProperty(node) != null) {
res = config.getStringList(node, def);
}
return res;
}
private List<String> getKeys(String node) {
List<String> res = parentConfig.getKeys(node);
if (res == null || res.size() == 0) {
res = config.getKeys(node);
}
if (res == null) {
res = new ArrayList<String>();
}
return res;
}
private Object getProperty(String node) {
Object res = parentConfig.getProperty(node);
if (config.getProperty(node) != null) {
res = config.getProperty(node);
}
return res;
load();
}
/**
* Load the configuration.
*/
private void loadConfiguration() {
try {
config.load();
} catch (IOException e) {
plugin.getLogger().severe("Error reading configuration for world " + worldName + ": ");
e.printStackTrace();
private void load() {
logger.info("Loading configuration for '" + worldName + "'...");
loadConfig();
// Load rule lists
loadBuiltInRules();
loadUserRules();
loadBlacklist();
// Load other rules
opPermissions = config.getBoolean("op-permissions", true);
boolean simulateSponge = config.getBoolean("simulation.sponge.enable", true);
int spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1;
boolean redstoneSponges = config.getBoolean("simulation.sponge.redstone", false);
boolean refillArea = config.getBoolean("simulation.sponge.refill-area", false);
if (simulateSponge) {
spongeApplicator = new SpongeApplicator(spongeRadius, redstoneSponges, refillArea);
}
summaryOnStart = getBoolean("summary-on-start", true);
opPermissions = getBoolean("op-permissions", true);
signChestProtection = config.getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = config.getBoolean("chest-protection.disable-off-check", false);
itemDurability = getBoolean("protection.item-durability", true);
removeInfiniteStacks = getBoolean("protection.remove-infinite-stacks", false);
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
useRegions = config.getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = config.getBoolean("regions.invincibility-removes-mobs", false);
highFreqFlags = config.getBoolean("regions.high-frequency-flags", false);
regionWand = config.getInt("regions.wand", 287);
maxClaimVolume = config.getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = config.getBoolean("regions.claim-only-inside-existing-regions", false);
blockPotions = new HashSet<PotionEffectType>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
PotionEffectType effect = PotionEffectType.getByName(potionName);
if (effect == null) {
plugin.getLogger().warning("Unknown potion effect type '" + potionName + "'");
} else {
blockPotions.add(effect);
}
}
blockPotionsAlways = getBoolean("gameplay.block-potions-overly-reliably", false);
simulateSponge = getBoolean("simulation.sponge.enable", true);
spongeRadius = Math.max(1, getInt("simulation.sponge.radius", 3)) - 1;
redstoneSponges = getBoolean("simulation.sponge.redstone", false);
pumpkinScuba = getBoolean("default.pumpkin-scuba", false);
disableHealthRegain = getBoolean("default.disable-health-regain", false);
noPhysicsGravel = getBoolean("physics.no-physics-gravel", false);
noPhysicsSand = getBoolean("physics.no-physics-sand", false);
ropeLadders = getBoolean("physics.vine-like-rope-ladders", false);
allowPortalAnywhere = getBoolean("physics.allow-portal-anywhere", false);
preventWaterDamage = new HashSet<Integer>(getIntList("physics.disable-water-damage-blocks", null));
blockTNTExplosions = getBoolean("ignition.block-tnt", false);
blockTNTBlockDamage = getBoolean("ignition.block-tnt-block-damage", false);
blockLighter = getBoolean("ignition.block-lighter", false);
preventLavaFire = getBoolean("fire.disable-lava-fire-spread", true);
disableFireSpread = getBoolean("fire.disable-all-fire-spread", false);
disableFireSpreadBlocks = new HashSet<Integer>(getIntList("fire.disable-fire-spread-blocks", null));
allowedLavaSpreadOver = new HashSet<Integer>(getIntList("fire.lava-spread-blocks", null));
blockCreeperExplosions = getBoolean("mobs.block-creeper-explosions", false);
blockCreeperBlockDamage = getBoolean("mobs.block-creeper-block-damage", false);
blockWitherExplosions = getBoolean("mobs.block-wither-explosions", false);
blockWitherBlockDamage = getBoolean("mobs.block-wither-block-damage", false);
blockWitherSkullExplosions = getBoolean("mobs.block-wither-skull-explosions", false);
blockWitherSkullBlockDamage = getBoolean("mobs.block-wither-skull-block-damage", false);
blockEnderDragonBlockDamage = getBoolean("mobs.block-enderdragon-block-damage", false);
blockEnderDragonPortalCreation = getBoolean("mobs.block-enderdragon-portal-creation", false);
blockFireballExplosions = getBoolean("mobs.block-fireball-explosions", false);
blockFireballBlockDamage = getBoolean("mobs.block-fireball-block-damage", false);
antiWolfDumbness = getBoolean("mobs.anti-wolf-dumbness", false);
disableEndermanGriefing = getBoolean("mobs.disable-enderman-griefing", false);
blockEntityPaintingDestroy = getBoolean("mobs.block-painting-destroy", false);
blockEntityItemFrameDestroy = getBoolean("mobs.block-item-frame-destroy", false);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
blockGroundSlimes = getBoolean("mobs.block-above-ground-slimes", false);
blockOtherExplosions = getBoolean("mobs.block-other-explosions", false);
blockZombieDoorDestruction = getBoolean("mobs.block-zombie-door-destruction", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
disableFireDamage = getBoolean("player-damage.disable-fire-damage", false);
disableLightningDamage = getBoolean("player-damage.disable-lightning-damage", false);
disableDrowningDamage = getBoolean("player-damage.disable-drowning-damage", false);
disableSuffocationDamage = getBoolean("player-damage.disable-suffocation-damage", false);
disableContactDamage = getBoolean("player-damage.disable-contact-damage", false);
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);
disableExplosionDamage = getBoolean("player-damage.disable-explosion-damage", false);
disableMobDamage = getBoolean("player-damage.disable-mob-damage", false);
disableDeathMessages = getBoolean("player-damage.disable-death-messages", false);
signChestProtection = getBoolean("chest-protection.enable", false);
disableSignChestProtectionCheck = getBoolean("chest-protection.disable-off-check", false);
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<Integer>(getIntList("weather.prevent-lightning-strike-blocks", null));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
disableWeather = getBoolean("weather.disable-weather", false);
disablePigZap = getBoolean("weather.disable-pig-zombification", false);
disableCreeperPower = getBoolean("weather.disable-powered-creepers", false);
alwaysRaining = getBoolean("weather.always-raining", false);
alwaysThundering = getBoolean("weather.always-thundering", false);
disableMushroomSpread = getBoolean("dynamics.disable-mushroom-spread", false);
disableIceMelting = getBoolean("dynamics.disable-ice-melting", false);
disableSnowMelting = getBoolean("dynamics.disable-snow-melting", false);
disableSnowFormation = getBoolean("dynamics.disable-snow-formation", false);
disableIceFormation = getBoolean("dynamics.disable-ice-formation", false);
disableLeafDecay = getBoolean("dynamics.disable-leaf-decay", false);
disableGrassGrowth = getBoolean("dynamics.disable-grass-growth", false);
disableMyceliumSpread = getBoolean("dynamics.disable-mycelium-spread", false);
disableVineGrowth = getBoolean("dynamics.disable-vine-growth", false);
useRegions = getBoolean("regions.enable", true);
regionInvinciblityRemovesMobs = getBoolean("regions.invincibility-removes-mobs", false);
highFreqFlags = getBoolean("regions.high-frequency-flags", false);
regionWand = getInt("regions.wand", 334);
maxClaimVolume = getInt("regions.max-claim-volume", 30000);
claimOnlyInsideExistingRegions = getBoolean("regions.claim-only-inside-existing-regions", false);
maxRegionCountPerPlayer = getInt("regions.max-region-count-per-player.default", 7);
maxRegionCountPerPlayer = config.getInt("regions.max-region-count-per-player.default", 7);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
for (String key : config.getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
Object val = config.get("regions.max-region-count-per-player." + key);
if (val != null && val instanceof Number) {
maxRegionCounts.put(key, ((Number) val).intValue());
}
@@ -423,113 +155,149 @@ public class WorldConfiguration {
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<EntityType>();
for (String creatureName : getStringList("mobs.block-creature-spawn", null)) {
EntityType creature = EntityType.fromName(creatureName);
saveConfig();
}
if (creature == null) {
plugin.getLogger().warning("Unknown mob type '" + creatureName + "'");
} else if (!creature.isAlive()) {
plugin.getLogger().warning("Entity type '" + creatureName + "' is not a creature");
} else {
blockCreatureSpawn.add(creature);
}
}
boolean useBlacklistAsWhitelist = getBoolean("blacklist.use-as-whitelist", false);
// Console log configuration
boolean logConsole = getBoolean("blacklist.logging.console.enable", true);
// Database log configuration
boolean logDatabase = getBoolean("blacklist.logging.database.enable", false);
String dsn = getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = getString("blacklist.logging.database.user", "root");
String pass = getString("blacklist.logging.database.pass", "");
String table = getString("blacklist.logging.database.table", "blacklist_events");
// File log configuration
boolean logFile = getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, getInt("blacklist.logging.file.open-files", 10));
// Load the blacklist
/**
* Load the configuration from file.
*/
private void loadConfig() {
try {
config.load();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error reading configuration for world " + worldName, e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Error reading configuration for world " + worldName, e);
}
}
/**
* Save the configuration to file.
*/
private void saveConfig() {
config.setHeader(
"# CONFIGURATION FILE FOR ONLY THIS WORLD\r\n" +
"#\r\n" +
"# Everything in here applies to ONLY this world. For global settings, edit \r\n" +
"# the file in plugins/WorldGuard/config.yml\r\n" +
"#\r\n" +
"# How do you use this file? Copy potions of the global configuration file into this file.\r\n" +
"#\r\n" +
"# EXAMPLE (remove the # in front):\r\n" +
"#physics:\r\n" +
"# block-tnt-damage: false");
try {
config.save();
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to save configuration", e);
}
}
/**
* Load the built-in rules.
*/
private void loadBuiltInRules() {
try {
RuleTemplateEntryLoader loader = new RuleTemplateEntryLoader(
plugin.getRulesListManager(), config);
for (List<RuleEntry> entries : plugin.getBuiltInRules().listOf("", loader)) {
for (RuleEntry entry : entries) {
learnRule(entry);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load the built-in rules", e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to load the built-in rules", e);
}
}
/**
* Load the user rules.
*/
private void loadUserRules() {
File rulesFile = configMan.getRuleListFile(worldName);
RuleEntryLoader entryLoader = new RuleEntryLoader(plugin.getRulesListManager());
YamlConfigurationFile rulesConfig = new YamlConfigurationFile(rulesFile,
ConfigurationManager.YAML_STYLE, false);
try {
rulesConfig.load();
for (RuleEntry entry : rulesConfig.listOf(ConfigurationNode.ROOT, entryLoader)) {
learnRule(entry);
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load " + rulesFile.getAbsolutePath(), e);
} catch (ConfigurationException e) {
logger.log(Level.SEVERE, "Failed to load " + rulesFile.getAbsolutePath(), e);
}
}
/**
* Load the blacklist.
*/
private void loadBlacklist() {
try {
// If there was an existing blacklist, close loggers
if (blacklist != null) {
blacklist.getLogger().close();
}
// First load the blacklist data from worldguard-blacklist.txt
Blacklist blist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
blist.load(blacklistFile);
File blacklistFile = configMan.getBlacklistFile(worldName);
// If the blacklist is empty, then set the field to null
// and save some resources
if (blist.isEmpty()) {
// Load blacklist settings
boolean useBlacklistAsWhitelist = config.getBoolean("blacklist.use-as-whitelist", false);
boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true);
boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false);
String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft");
String user = config.getString("blacklist.logging.database.user", "root");
String pass = config.getString("blacklist.logging.database.pass", "");
String table = config.getString("blacklist.logging.database.table", "blacklist_events");
boolean logFile = config.getBoolean("blacklist.logging.file.enable", false);
String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log");
int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10));
Blacklist newBlacklist = new BukkitBlacklist(useBlacklistAsWhitelist, plugin);
newBlacklist.load(blacklistFile);
// If the blacklist is empty, then set the field to null and save some resources
if (newBlacklist.isEmpty()) {
this.blacklist = null;
} else {
this.blacklist = blist;
if (summaryOnStart) {
plugin.getLogger().log(Level.INFO, "Blacklist loaded.");
}
this.blacklist = newBlacklist;
logger.log(Level.INFO, "Blacklist loaded.");
BlacklistLogger blacklistLogger = blist.getLogger();
BlacklistLogger blacklistLogger = newBlacklist.getLogger();
if (logDatabase) {
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table, worldName, plugin.getLogger()));
}
if (logDatabase)
blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user,
pass, table, worldName, logger));
if (logConsole) {
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName, plugin.getLogger()));
}
if (logConsole)
blacklistLogger.addHandler(new ConsoleLoggerHandler(worldName,
logger));
if (logFile) {
FileLoggerHandler handler =
new FileLoggerHandler(logFilePattern, logFileCacheSize, worldName, plugin.getLogger());
FileLoggerHandler handler = new FileLoggerHandler(logFilePattern,
logFileCacheSize, worldName, logger);
blacklistLogger.addHandler(handler);
}
}
} catch (FileNotFoundException e) {
plugin.getLogger().log(Level.WARNING, "WorldGuard blacklist does not exist.");
logger.log(Level.WARNING, "WorldGuard blacklist does not exist", e);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not load WorldGuard blacklist: "
+ e.getMessage());
logger.log(Level.WARNING, "Could not load blacklist", e);
}
// Print an overview of settings
if (summaryOnStart) {
plugin.getLogger().log(Level.INFO, blockTNTExplosions
? "(" + worldName + ") TNT ignition is blocked."
: "(" + worldName + ") TNT ignition is PERMITTED.");
plugin.getLogger().log(Level.INFO, blockLighter
? "(" + worldName + ") Lighters are blocked."
: "(" + worldName + ") Lighters are PERMITTED.");
plugin.getLogger().log(Level.INFO, preventLavaFire
? "(" + worldName + ") Lava fire is blocked."
: "(" + worldName + ") Lava fire is PERMITTED.");
if (disableFireSpread) {
plugin.getLogger().log(Level.INFO, "(" + worldName + ") All fire spread is disabled.");
} else {
if (disableFireSpreadBlocks.size() > 0) {
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is limited to "
+ disableFireSpreadBlocks.size() + " block types.");
} else {
plugin.getLogger().log(Level.INFO, "(" + worldName
+ ") Fire spread is UNRESTRICTED.");
}
}
}
config.setHeader(CONFIG_HEADER);
config.save();
}
public Blacklist getBlacklist() {
return this.blacklist;
return blacklist;
}
SpongeApplicator getSpongeApplicator() {
return spongeApplicator;
}
public String getWorldName() {
@@ -591,4 +359,24 @@ public class WorldConfiguration {
}
return max;
}
public KnownAttachmentRules getRuleList() {
return ruleList;
}
/**
* Register a rule with this rule list.
*
* @param entry entry
*/
public void learnRule(RuleEntry entry) {
for (String name : entry.getAttachmentNames()) {
KnownAttachment attachment = KnownAttachment.fromId(name);
if (attachment != null) {
ruleList.get(attachment).learn(entry.getRule());
} else {
logger.warning("Don't know what the RuleList event '" + name + "' is");
}
}
}
}
@@ -16,6 +16,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
@@ -25,6 +26,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -42,18 +44,14 @@ import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
@@ -64,86 +62,58 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected WorldConfiguration getWorldConfig(World world) {
return plugin.getGlobalStateManager().get(world);
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
}
/*
* Called when a block is damaged.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Cake are damaged and not broken when they are eaten, so we must
// handle them a bit separately
if (blockDamaged.getTypeId() == BlockID.CAKE_BLOCK) {
// Regions
if (!plugin.getGlobalRegionManager().canBuild(player, blockDamaged)) {
player.sendMessage(ChatColor.DARK_RED + "You're not invited to this tea party!");
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(player);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
Block block = event.getBlock();
if (!wcfg.itemDurability) {
ItemStack held = player.getItemInHand();
if (held.getTypeId() > 0
&& !(ItemType.usesDamageValue(held.getTypeId())
|| BlockType.usesData(held.getTypeId()))) {
held.setDurability((short) -1);
player.setItemInHand(held);
}
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Regions
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())
|| !plugin.getGlobalRegionManager().canConstruct(player, event.getBlock())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
@@ -151,6 +121,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
// Blacklist
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
@@ -169,85 +140,46 @@ public class WorldGuardBlockListener implements Listener {
}
}
// Chest protection
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_BREAK);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(player);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
/* --- No short-circuit returns below this line --- */
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
}
}
}
/*
* Called when fluids flow.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9;
boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11;
boolean isAir = blockFrom.getTypeId() == 0;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& (!wcfg.redstoneSponges || !sponge.isBlockIndirectlyPowered())) {
event.setCancelled(true);
return;
}
}
}
}
}
/*if (plugin.classicWater && isWater) {
int blockBelow = blockFrom.getRelative(0, -1, 0).getTypeId();
if (blockBelow != 0 && blockBelow != 8 && blockBelow != 9) {
blockFrom.setTypeId(9);
if (blockTo.getTypeId() == 0) {
blockTo.setTypeId(9);
}
return;
}
}*/
// Check the fluid block (from) whether it is air.
// If so and the target block is protected, cancel the event
if (wcfg.preventWaterDamage.size() > 0) {
int targetId = blockTo.getTypeId();
if ((isAir || isWater) &&
wcfg.preventWaterDamage.contains(targetId)) {
event.setCancelled(true);
return;
}
}
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
}
}
// Regions
if (wcfg.highFreqFlags && isWater
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.WATER_FLOW,
blockFrom.getLocation())) {
@@ -262,73 +194,43 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (wcfg.disableObsidianGenerators && (isAir || isLava)
&& blockTo.getTypeId() == 55) {
blockTo.setTypeId(0);
return;
}
}
/*
* Called when a block gets ignited.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.preventLavaFire && cause == IgniteCause.LAVA) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0 && isFireSpread) {
int x = block.getX();
int y = block.getY();
int z = block.getZ();
if (wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y - 1, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x + 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x - 1, y, z))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z - 1))
|| wcfg.disableFireSpreadBlocks.contains(world.getBlockTypeIdAt(x, y, z + 1))) {
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && isWater) {
if (spongeAppl.isNearSponge(blockTo)) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_SPREAD);
BukkitContext context = new BukkitContext(event);
context.setSourceBlock(event.getBlock().getState());
context.setTargetBlock(event.getToBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
boolean isFireSpread = cause == IgniteCause.SPREAD;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle && isFireSpread) {
event.setCancelled(true);
return;
}
// Regions
if (wcfg.useRegions) {
Vector pt = toVector(block);
Player player = event.getPlayer();
@@ -363,39 +265,84 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (cause == IgniteCause.FIREBALL && event.getPlayer() == null) {
// wtf bukkit, FIREBALL is supposed to be reserved to players
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules;
BukkitContext context;
BlockState placedState;
switch (event.getCause()) {
case FLINT_AND_STEEL:
// Consider flint and steel as an item use
rules = wcfg.getRuleList().get(KnownAttachment.ITEM_USE);
context = new BukkitContext(event);
context.setSourceEntity(event.getPlayer());
context.setTargetBlock(event.getBlock().getState());
context.setItem(event.getPlayer().getItemInHand()); // Should be flint and steel
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
case LAVA:
case SPREAD:
// Consider everything else as a block spread
rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_SPREAD);
context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
// Make a virtual source state
BlockState sourceState = event.getBlock().getState();
sourceState.setType(event.getCause() == IgniteCause.LAVA ? Material.LAVA : Material.FIRE);
context.setSourceBlock(sourceState);
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
case FIREBALL:
case LIGHTNING:
// Consider everything else as a block spread
rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_PLACE);
context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
// Make a virtual new state
placedState = event.getBlock().getState();
placedState.setType(Material.FIRE);
context.setPlacedBlock(placedState);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
break;
}
}
/*
* Called when a block is destroyed from burning.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
}
// Fire stop toggle
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
@@ -403,21 +350,13 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (wcfg.disableFireSpreadBlocks.size() > 0) {
Block block = event.getBlock();
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
// Chest protection
if (wcfg.isChestProtected(event.getBlock())) {
event.setCancelled(true);
return;
}
// Regions
if (wcfg.useRegions) {
Block block = event.getBlock();
int x = block.getX();
@@ -432,7 +371,18 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_BREAK);
BukkitContext context = new BukkitContext(event);
BlockState virtualFireState = event.getBlock().getState();
virtualFireState.setType(Material.FIRE);
context.setSourceBlock(virtualFireState);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@@ -451,47 +401,35 @@ public class WorldGuardBlockListener implements Listener {
}
}
/*
* Called when block physics occurs.
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_PHYSICS);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
int id = event.getChangedTypeId();
/* --- No short-circuit returns below this line --- */
if (id == 13 && wcfg.noPhysicsGravel) {
event.setCancelled(true);
return;
}
if (id == 12 && wcfg.noPhysicsSand) {
event.setCancelled(true);
return;
}
if (id == 90 && wcfg.allowPortalAnywhere) {
event.setCancelled(true);
return;
}
if (wcfg.ropeLadders && event.getBlock().getType() == Material.LADDER) {
if (event.getBlock().getRelative(0, 1, 0).getType() == Material.LADDER) {
event.setCancelled(true);
return;
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && block.getType() == Material.SPONGE) {
if (spongeAppl.isActiveSponge(block)) {
spongeAppl.placeWater(block);
} else {
spongeAppl.clearWater(block);
}
}
}
/*
* Called when a player places a block.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlock();
@@ -501,6 +439,7 @@ public class WorldGuardBlockListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Regions
if (wcfg.useRegions) {
final Location location = blockPlaced.getLocation();
if (!plugin.getGlobalRegionManager().canBuild(player, location)
@@ -511,6 +450,7 @@ public class WorldGuardBlockListener implements Listener {
}
}
// Blacklist
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockPlaceBlacklistEvent(plugin.wrapPlayer(player), toVector(blockPlaced),
@@ -520,6 +460,7 @@ public class WorldGuardBlockListener implements Listener {
}
}
// Chest protection
if (wcfg.signChestProtection && wcfg.getChestProtection().isChest(blockPlaced.getTypeId())) {
if (wcfg.isAdjacentChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "This spot is for a chest that you don't have permission for.");
@@ -528,62 +469,31 @@ public class WorldGuardBlockListener implements Listener {
}
}
if (wcfg.simulateSponge && blockPlaced.getTypeId() == 19) {
if (wcfg.redstoneSponges && blockPlaced.isBlockIndirectlyPowered()) {
return;
}
int ox = blockPlaced.getX();
int oy = blockPlaced.getY();
int oz = blockPlaced.getZ();
SpongeUtil.clearSpongeWater(plugin, world, ox, oy, oz);
// Sponges
SpongeApplicator spongeAppl = wcfg.getSpongeApplicator();
if (spongeAppl != null && spongeAppl.isActiveSponge(blockPlaced)) {
spongeAppl.clearWater(blockPlaced);
}
}
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.simulateSponge && wcfg.redstoneSponges) {
int ox = blockTo.getX();
int oy = blockTo.getY();
int oz = blockTo.getZ();
for (int cx = -1; cx <= 1; cx++) {
for (int cy = -1; cy <= 1; cy++) {
for (int cz = -1; cz <= 1; cz++) {
Block sponge = world.getBlockAt(ox + cx, oy + cy, oz + cz);
if (sponge.getTypeId() == 19
&& sponge.isBlockIndirectlyPowered()) {
SpongeUtil.clearSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
} else if (sponge.getTypeId() == 19
&& !sponge.isBlockIndirectlyPowered()) {
SpongeUtil.addSpongeWater(plugin, world, ox + cx, oy + cy, oz + cz);
}
}
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_PLACE);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getBlockReplacedState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
/*
* Called when a sign is changed.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
// Chest protection
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
@@ -643,6 +553,15 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_INTERACT);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -650,44 +569,34 @@ public class WorldGuardBlockListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
}
// Regions
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY,
event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_FADE);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
int type = event.getNewState().getTypeId();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Regions
if (type == BlockID.ICE) {
if (wcfg.disableIceFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_FORM, event.getBlock().getLocation())) {
event.setCancelled(true);
@@ -696,38 +605,33 @@ public class WorldGuardBlockListener implements Listener {
}
if (type == BlockID.SNOW) {
if (wcfg.disableSnowFormation) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_FALL, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
}
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (cfg.activityHaltToggle) {
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_FORM);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
int fromType = event.getSource().getTypeId();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Regions
if (fromType == BlockID.RED_MUSHROOM || fromType == BlockID.BROWN_MUSHROOM) {
if (wcfg.disableMushroomSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.MUSHROOMS, event.getBlock().getLocation())) {
event.setCancelled(true);
@@ -736,10 +640,6 @@ public class WorldGuardBlockListener implements Listener {
}
if (fromType == BlockID.GRASS) {
if (wcfg.disableGrassGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.GRASS_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
@@ -747,51 +647,27 @@ public class WorldGuardBlockListener implements Listener {
}
}
if (fromType == BlockID.MYCELIUM) {
if (wcfg.disableMyceliumSpread) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.MYCELIUM_SPREAD, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
if (fromType == BlockID.VINE) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.VINE_GROWTH, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_SPREAD);
BukkitContext context = new BukkitContext(event);
context.setSourceBlock(event.getSource().getState());
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
int type = event.getBlock().getTypeId();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
int type = event.getBlock().getTypeId();
// regions
if (type == BlockID.ICE) {
if (wcfg.disableIceMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ICE_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
@@ -800,31 +676,36 @@ public class WorldGuardBlockListener implements Listener {
}
if (type == BlockID.SNOW) {
if (wcfg.disableSnowMelting) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.SNOW_MELT, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.BLOCK_FADE);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(event.getBlock().getState());
context.setPlacedBlock(event.getNewState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
/*
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Regions
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation())) {
event.setCancelled(true);
return;
}
for (Block block : event.getBlocks()) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, block.getLocation())) {
event.setCancelled(true);
@@ -834,14 +715,12 @@ public class WorldGuardBlockListener implements Listener {
}
}
/*
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
// Regions
if (wcfg.useRegions && event.isSticky()) {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
@@ -851,25 +730,19 @@ public class WorldGuardBlockListener implements Listener {
}
}
/*
* Called when a block is damaged.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
if (wcfg.blockPotions.size() > 0) {
ItemStack item = event.getItem();
if (item.getType() == Material.POTION && !BukkitUtil.isWaterPotion(item)) {
Potion potion = Potion.fromDamage(BukkitUtil.getPotionEffectBits(item));
for (PotionEffect effect : potion.getEffects()) {
if (potion.isSplash() && wcfg.blockPotions.contains(effect.getType())) {
event.setCancelled(true);
return;
}
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ITEM_DROP);
BukkitContext context = new BukkitContext(event);
context.setSourceBlock(event.getBlock().getState());
context.setItem(event.getItem());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -30,16 +30,16 @@ import org.bukkit.entity.Hanging;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Painting;
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;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
@@ -71,80 +71,72 @@ public class WorldGuardHangingListener implements Listener {
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingingBreak(HangingBreakEvent event) {
public void onHangingingBreak(HangingBreakEvent breakEvent) {
if (!(breakEvent instanceof HangingBreakByEntityEvent)) {
return;
}
HangingBreakByEntityEvent event = (HangingBreakByEntityEvent) breakEvent;
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
Entity removerEntity = entityEvent.getRemover();
if (removerEntity instanceof Projectile) {
Projectile projectile = (Projectile) removerEntity;
removerEntity = projectile.getShooter() != null ? projectile.getShooter() : removerEntity;
if (event.getRemover() instanceof Player) {
Player player = (Player) event.getRemover();
if (wcfg.getBlacklist() != null) {
if (hanging instanceof Painting
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (hanging instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), false, false)) {
event.setCancelled(true);
return;
}
}
if (removerEntity instanceof Player) {
Player player = (Player) removerEntity;
if (wcfg.getBlacklist() != null) {
if (hanging instanceof Painting
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
} else if (hanging instanceof ItemFrame
&& !wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.ITEM_FRAME), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, hanging.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (removerEntity instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, hanging.getLocation())) {
event.setCancelled(true);
return;
}
}
if (hanging instanceof Painting
&& (wcfg.blockEntityPaintingDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame
&& (wcfg.blockEntityItemFrameDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, hanging.getLocation())))) {
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, hanging.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
// Explosions from mobs are not covered by HangingBreakByEntity
if (hanging instanceof Painting && wcfg.blockEntityPaintingDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
if (event.getRemover() instanceof Creeper) {
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, hanging.getLocation())) {
event.setCancelled(true);
return;
}
}
if (hanging instanceof Painting
&& ((wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, hanging.getLocation())))) {
event.setCancelled(true);
} else if (hanging instanceof ItemFrame && wcfg.blockEntityItemFrameDestroy
&& event.getCause() == RemoveCause.EXPLOSION) {
} else if (hanging instanceof ItemFrame
&& ((wcfg.useRegions && !plugin.getGlobalRegionManager()
.allows(DefaultFlag.ENTITY_ITEM_FRAME_DESTROY,
hanging.getLocation())))) {
event.setCancelled(true);
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(event.getRemover());
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -174,12 +166,22 @@ public class WorldGuardHangingListener implements Listener {
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getRelative(event.getBlockFace()))) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_SPAWN);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(event.getPlayer());
context.setTargetEntity(event.getEntity());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -197,15 +199,27 @@ public class WorldGuardHangingListener implements Listener {
return;
}
// if (entity instanceof ItemFrame
// && ((!plugin.getGlobalRegionManager().allows(
// DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, entity.getLocation())))) {
// event.setCancelled(true);
// } else if (entity instanceof Painting
// && ((!plugin.getGlobalRegionManager().allows(
// DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
// event.setCancelled(true);
// }
if (entity instanceof ItemFrame
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_ITEM_FRAME_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
return;
} else if (entity instanceof Painting
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_INTERACT);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(player);
context.setTargetEntity(entity);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -37,6 +37,8 @@ import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
@@ -103,22 +105,24 @@ public class WorldGuardPaintingListener implements Listener {
}
} else {
if (event.getRemover() instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.blockEntityPaintingDestroy
|| (wcfg.useRegions
&& !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation()))) {
if ((wcfg.useRegions && !plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation()))) {
event.setCancelled(true);
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_DAMAGE);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(event.getRemover());
context.setTargetEntity(event.getPainting());
rules.process(context);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -147,6 +151,16 @@ public class WorldGuardPaintingListener implements Listener {
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_SPAWN);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(event.getPlayer());
context.setTargetEntity(event.getPainting());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
@@ -163,12 +177,23 @@ public class WorldGuardPaintingListener implements Listener {
event.setCancelled(true);
return;
}
if (entity instanceof Painting
&& ((!plugin.getGlobalRegionManager().allows(
DefaultFlag.ENTITY_PAINTING_DESTROY, entity.getLocation())))) {
event.setCancelled(true);
return;
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.ENTITY_INTERACT);
BukkitContext context = new BukkitContext(event);
context.setSourceEntity(player);
context.setTargetEntity(entity);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -22,7 +22,6 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.hasHangingEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -31,8 +30,7 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@@ -43,6 +41,7 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
@@ -55,52 +54,73 @@ import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.SimpleInjector;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.rebar.bukkit.VirtualRebarPlugin;
import com.sk89q.rebar.config.ConfigurationException;
import com.sk89q.rebar.config.YamlConfiguration;
import com.sk89q.rebar.config.YamlConfigurationResource;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.Criteria;
import com.sk89q.rulelists.DefinitionManager;
import com.sk89q.rulelists.ResolverManager;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.wepif.PermissionsResolverManager;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.commands.GeneralCommands;
import com.sk89q.worldguard.bukkit.commands.ProtectionCommands;
import com.sk89q.worldguard.bukkit.commands.ToggleCommands;
import com.sk89q.worldguard.bukkit.definitions.BlockCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.CancelActionLoader;
import com.sk89q.worldguard.bukkit.definitions.DamageCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.EntityCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.ItemCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.PermissionCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.PhenomenonCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.SetBlockActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SetDropActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SpawnCriteriaLoader;
import com.sk89q.worldguard.bukkit.definitions.TellActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateEntityActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateItemActionLoader;
import com.sk89q.worldguard.bukkit.definitions.SetMessageActionLoader;
import com.sk89q.worldguard.bukkit.definitions.UpdateWorldActionLoader;
import com.sk89q.worldguard.bukkit.definitions.WeatherCriteriaLoader;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlacedBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlayerItemStackSlotResolver;
import com.sk89q.worldguard.bukkit.resolvers.PlayerItemStackSlotResolver.Slot;
import com.sk89q.worldguard.bukkit.resolvers.SourceBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.SourceEntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.TargetBlockResolver;
import com.sk89q.worldguard.bukkit.resolvers.TargetEntityResolver;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.util.FatalConfigurationLoadingException;
/**
* The main class for WorldGuard as a Bukkit plugin.
*
* @author sk89q
*/
public class WorldGuardPlugin extends JavaPlugin {
/**
* Manager for commands. This automatically handles nested commands,
* permissions checking, and a number of other fancy command things.
* We just set it up and register commands against it.
*/
private final CommandsManager<CommandSender> commands;
/**
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Used for scheduling flags.
*/
private FlagStateManager flagStateManager;
private RuleListsManager ruleListsManager;
private final LagStopMode lagStopper;
private WorldGuardWorldListener worldListener;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
* Do initial loading of WorldGuard. Only called once. {@link #onEnable()} will be
* called when WorldGuard is enabled.
*/
public WorldGuardPlugin() {
configuration = new ConfigurationManager(this);
globalRegionManager = new GlobalRegionManager(this);
lagStopper = new LagStopMode(this);
final WorldGuardPlugin plugin = this;
commands = new CommandsManager<CommandSender>() {
@@ -111,12 +131,15 @@ public class WorldGuardPlugin extends JavaPlugin {
};
}
/**
* Called on plugin enable.
*/
@Override
@SuppressWarnings("deprecation")
@Override
public void onEnable() {
// We don't require Rebar yet
VirtualRebarPlugin.setup(this);
// Set up RuleLists
ruleListsManager = new RuleListsManager();
registerRuleList();
// Set the proper command injector
commands.setInjector(new SimpleInjector(this));
@@ -144,12 +167,12 @@ public class WorldGuardPlugin extends JavaPlugin {
LegacyWorldGuardMigration.migrateBlacklist(this);
try {
// Load the configuration
configuration.load();
globalRegionManager.preload();
// Load the configuration
configuration.load();
globalRegionManager.preload();
} catch (FatalConfigurationLoadingException e) {
e.printStackTrace();
getServer().shutdown();
getLogger().log(Level.SEVERE, "Fatal error encountered", e);
getServer().shutdown();
}
// Migrate regions after the regions were loaded because
@@ -159,8 +182,7 @@ public class WorldGuardPlugin extends JavaPlugin {
flagStateManager = new FlagStateManager(this);
if (configuration.useRegionsScheduler) {
getServer().getScheduler().scheduleSyncRepeatingTask(this, flagStateManager,
FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
getServer().getScheduler().scheduleAsyncRepeatingTask(this, flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
// Register events
@@ -170,6 +192,12 @@ public class WorldGuardPlugin extends JavaPlugin {
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
(worldListener = new WorldGuardWorldListener(this)).registerEvents();
lagStopper.registerEvents();
// Initialization
simulateWorldLoad();
if (hasHangingEvent()) {
(new WorldGuardHangingListener(this)).registerEvents();
} else {
@@ -180,28 +208,8 @@ public class WorldGuardPlugin extends JavaPlugin {
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
getServer().getPluginManager().registerEvents(new WorldGuardCommandBookListener(this), this);
}
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
for (World world : getServer().getWorlds()) {
worldListener.initWorld(world);
}
worldListener.registerEvents();
if (!configuration.hasCommandBookGodMode()) {
// Check god mode for existing players, if any
for (Player player : getServer().getOnlinePlayers()) {
if (inGroup(player, "wg-invincible") ||
(configuration.autoGodMode && hasPermission(player, "worldguard.auto-invincible"))) {
configuration.enableGodMode(player);
}
}
}
}
/**
* Called on plugin disable.
*/
@Override
public void onDisable() {
globalRegionManager.unload();
@@ -209,9 +217,6 @@ public class WorldGuardPlugin extends JavaPlugin {
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
@@ -238,6 +243,16 @@ public class WorldGuardPlugin extends JavaPlugin {
return true;
}
/**
* Dispatch {@link WorldLoadEvent}s to the world listener.
*/
public void simulateWorldLoad() {
for (World world : getServer().getWorlds()) {
WorldLoadEvent event = new WorldLoadEvent(world);
worldListener.onWorldLoad(event);
}
}
/**
* Get the GlobalRegionManager.
*
@@ -276,6 +291,74 @@ public class WorldGuardPlugin extends JavaPlugin {
return configuration;
}
/**
* Get the rules list manager.
*
* @return rule lists manager
*/
public RuleListsManager getRulesListManager() {
return ruleListsManager;
}
/**
* Get the built-in rules.
*
* @return built-in rules
* @throws ConfigurationException
* on config error
* @throws IOException
* on I/O exception
*/
public YamlConfiguration getBuiltInRules() throws IOException, ConfigurationException {
YamlConfiguration rules = new YamlConfigurationResource(getClass(),
"/defaults/builtin_rules.yml");
rules.load();
return rules;
}
/**
* Register RuleList resolvers, criterion, and actions.
*/
private void registerRuleList() {
// Subject resolvers
ResolverManager resolvers = ruleListsManager.getResolvers();
resolvers.register(BlockResolver.class, "source", new SourceBlockResolver());
resolvers.register(BlockResolver.class, "target", new TargetBlockResolver());
resolvers.register(BlockResolver.class, "placed", new PlacedBlockResolver());
resolvers.register(EntityResolver.class, "source", new SourceEntityResolver());
resolvers.register(EntityResolver.class, "target", new TargetEntityResolver());
resolvers.register(ItemStackSlotResolver.class, "held", new PlayerItemStackSlotResolver(Slot.HELD));
resolvers.register(ItemStackSlotResolver.class, "helmet", new PlayerItemStackSlotResolver(Slot.HELMET));
resolvers.register(ItemStackSlotResolver.class, "chestplate", new PlayerItemStackSlotResolver(Slot.CHESTPLATE));
resolvers.register(ItemStackSlotResolver.class, "leggings", new PlayerItemStackSlotResolver(Slot.LEGGINGS));
resolvers.register(ItemStackSlotResolver.class, "boots", new PlayerItemStackSlotResolver(Slot.BOOTS));
// Criterion
DefinitionManager<Criteria<?>> criterion = ruleListsManager.getCriterion();
criterion.register("match-block", new BlockCriteriaLoader(ruleListsManager));
criterion.register("match-item", new ItemCriteriaLoader(ruleListsManager));
criterion.register("match-entity", new EntityCriteriaLoader(ruleListsManager));
criterion.register("match-damage", new DamageCriteriaLoader());
criterion.register("match-spawn", new SpawnCriteriaLoader());
criterion.register("match-phenomenon", new PhenomenonCriteriaLoader());
criterion.register("match-weather", new WeatherCriteriaLoader());
criterion.register("has-permission", new PermissionCriteriaLoader(this, ruleListsManager));
// Actions
DefinitionManager<Action<?>> actions = ruleListsManager.getActions();
actions.register("cancel", new CancelActionLoader());
actions.register("tell", new TellActionLoader(ruleListsManager));
actions.register("update-item", new UpdateItemActionLoader(ruleListsManager));
actions.register("update-world", new UpdateWorldActionLoader());
actions.register("update-entity", new UpdateEntityActionLoader(this, ruleListsManager));
actions.register("set-message", new SetMessageActionLoader(ruleListsManager));
actions.register("set-drop", new SetDropActionLoader());
actions.register("set-block", new SetBlockActionLoader(ruleListsManager));
}
/**
* Check whether a player is in a group.
* This calls the corresponding method in PermissionsResolverManager
@@ -707,9 +790,7 @@ public class WorldGuardPlugin extends JavaPlugin {
* @param actual The destination file
* @param defaultName The name of the file inside the jar's defaults folder
*/
public void createDefaultConfiguration(File actual,
String defaultName) {
public void createDefaultConfiguration(File actual, String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
@@ -720,16 +801,10 @@ public class WorldGuardPlugin extends JavaPlugin {
return;
}
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);
}
InputStream input = WorldGuardPlugin.class.getResourceAsStream("/defaults/" + defaultName);
if (input == null) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
@@ -832,6 +907,15 @@ public class WorldGuardPlugin extends JavaPlugin {
return getGlobalRegionManager().get(world);
}
/**
* Get the "lag stop mode" controller.
*
* @return the lag stop mode
*/
public LagStopMode getLagStopMode() {
return lagStopper;
}
/**
* Replace macros in the text.
*
@@ -7,7 +7,7 @@ import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* @author zml2008
* Listener for server events.
*/
public class WorldGuardServerListener implements Listener {
@@ -24,6 +24,7 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
// Legacy god mode
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
@@ -31,6 +32,7 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
// Legacy god mode
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
@@ -16,6 +16,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.FlagStateManager.PlayerFlagState;
@@ -24,22 +25,17 @@ import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* Listener for vehicle events.
*/
public class WorldGuardVehicleListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@@ -50,12 +46,14 @@ public class WorldGuardVehicleListener implements Listener {
Entity destroyer = event.getAttacker();
if (!(destroyer instanceof Player)) return; // don't care
Player player = (Player) destroyer;
World world = vehicle.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Regions
if (wcfg.useRegions) {
Vector pt = toVector(vehicle.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -82,6 +80,7 @@ public class WorldGuardVehicleListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
// Regions
// unfortunate code duplication
if (wcfg.useRegions) {
// Did we move a block?
@@ -27,23 +27,21 @@ import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.RuleSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Listener for weather events.
*/
public class WorldGuardWeatherListener implements Listener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@@ -57,14 +55,12 @@ public class WorldGuardWeatherListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysRaining) {
event.setCancelled(true);
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WEATHER_TRANSITION);
BukkitContext context = new BukkitContext(event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@@ -73,30 +69,23 @@ public class WorldGuardWeatherListener implements Listener {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (event.toThunderState()) {
if (wcfg.disableThunder) {
event.setCancelled(true);
}
} else {
if (!wcfg.disableWeather && wcfg.alwaysThundering) {
event.setCancelled(true);
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WEATHER_TRANSITION);
BukkitContext context = new BukkitContext(event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
Location loc = event.getLightning().getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (wcfg.disallowedLightningBlocks.size() > 0) {
int targetId = event.getLightning().getLocation().getBlock().getTypeId();
if (wcfg.disallowedLightningBlocks.contains(targetId)) {
event.setCancelled(true);
}
}
Location loc = event.getLightning().getLocation();
// Regions
if (wcfg.useRegions) {
Vector pt = toVector(loc);
RegionManager mgr = plugin.getGlobalRegionManager().get(loc.getWorld());
@@ -106,5 +95,14 @@ public class WorldGuardWeatherListener implements Listener {
event.setCancelled(true);
}
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WEATHER_PHENOMENON);
BukkitContext context = new BukkitContext(event);
context.setTargetBlock(loc.getBlock().getState());
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
}
@@ -5,79 +5,63 @@
*/
package com.sk89q.worldguard.bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import com.sk89q.rulelists.KnownAttachment;
import com.sk89q.rulelists.RuleSet;
/**
* Listener for world events.
*/
public class WorldGuardWorldListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
public void onWorldLoad(WorldLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (cfg.activityHaltToggle) {
int removed = 0;
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WORLD_LOAD);
BukkitContext context = new BukkitContext(event);
rules.process(context);
}
for (Entity entity : event.getChunk().getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
@EventHandler
public void onWorldLoad(WorldUnloadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
if (removed > 50) {
plugin.getLogger().info("Halt-Act: " + removed + " entities (>50) auto-removed from "
+ event.getChunk().toString());
}
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WORLD_UNLOAD);
BukkitContext context = new BukkitContext(event);
if (rules.process(context)) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void onWorldLoad(WorldLoadEvent event) {
initWorld(event.getWorld());
}
/**
* Initialize the settings for the specified world
* @see WorldConfiguration#alwaysRaining
* @see WorldConfiguration#disableWeather
* @see WorldConfiguration#alwaysThundering
* @see WorldConfiguration#disableThunder
* @param world The specified world
*/
public void initWorld(World world) {
public void onWorldSave(WorldSaveEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
world.setStorm(false);
}
if (wcfg.alwaysThundering && !wcfg.disableThunder) {
world.setThundering(true);
} else if (wcfg.disableThunder && !wcfg.alwaysThundering) {
world.setStorm(false);
}
WorldConfiguration wcfg = cfg.get(event.getWorld());
// RuleLists
RuleSet rules = wcfg.getRuleList().get(KnownAttachment.WORLD_SAVE);
BukkitContext context = new BukkitContext(event);
rules.process(context);
}
}
@@ -19,23 +19,7 @@
package com.sk89q.worldguard.bukkit.commands;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
@@ -54,57 +38,60 @@ import com.sk89q.worldguard.protection.databases.RegionDBUtil;
import com.sk89q.worldguard.protection.databases.migrators.AbstractDatabaseMigrator;
import com.sk89q.worldguard.protection.databases.migrators.MigrationException;
import com.sk89q.worldguard.protection.databases.migrators.MigratorKey;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class RegionCommands {
private final WorldGuardPlugin plugin;
private MigratorKey migrateDBRequest;
private Date migrateDBRequestDate;
public RegionCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"define", "def", "d"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Defines a region", min = 1)
@CommandPermissions({"worldguard.region.define"})
public void define(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (mgr.hasRegion(id)) {
throw new CommandException("That region is already defined. Use redefine instead.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
@@ -126,9 +113,9 @@ public class RegionCommands {
if (args.argsLength() > 1) {
region.setOwners(RegionDBUtil.parseDomainString(args.getSlice(1), 1));
}
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
@@ -137,17 +124,17 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"redefine", "update", "move"}, usage = "<id>",
desc = "Re-defines the shape of a region", min = 1, max = 1)
public void redefine(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
WorldEditPlugin worldEdit = plugin.getWorldEdit();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
@@ -166,16 +153,16 @@ public class RegionCommands {
} else {
plugin.checkPermission(sender, "worldguard.region.redefine");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
if (sel instanceof Polygonal2DSelection) {
Polygonal2DSelection polySel = (Polygonal2DSelection) sel;
@@ -199,11 +186,11 @@ public class RegionCommands {
region.setParent(existing.getParent());
} catch (CircularInheritanceException ignore) {
}
mgr.addRegion(region);
sender.sendMessage(ChatColor.YELLOW + "Region updated with new area.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -211,38 +198,38 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"claim"}, usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
desc = "Claim a region", min = 1)
@CommandPermissions({"worldguard.region.claim"})
public void claim(CommandContext args, CommandSender sender) throws CommandException {
Player player = plugin.checkPlayer(sender);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldEditPlugin worldEdit = plugin.getWorldEdit();
String id = args.getString(0);
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("A region cannot be named __global__");
}
// Attempt to get the player's selection from WorldEdit
Selection sel = worldEdit.getSelection(player);
if (sel == null) {
throw new CommandException("Select a region with WorldEdit first.");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(sel.getWorld());
if (mgr.hasRegion(id)) {
throw new CommandException("That region already exists. Please choose a different name.");
}
ProtectedRegion region;
// Detect the type of region from WorldEdit
@@ -266,7 +253,7 @@ public class RegionCommands {
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
if (!plugin.hasPermission(sender, "worldguard.region.unlimited")) {
// Check whether the player has created too many regions
int maxRegionCount = wcfg.getMaxRegionCount(player);
@@ -284,9 +271,9 @@ public class RegionCommands {
throw new CommandException("This region already exists and you don't own it.");
}
}
ApplicableRegionSet regions = mgr.getApplicableRegions(region);
// Check if this region overlaps any other region
if (regions.size() > 0) {
if (!regions.isOwnerOfAll(localPlayer)) {
@@ -333,7 +320,7 @@ public class RegionCommands {
region.getOwners().addPlayer(player.getName());
mgr.addRegion(region);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW + "Region saved as " + id + ".");
@@ -402,7 +389,7 @@ public class RegionCommands {
world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(),
poly2d.getMaximumPoint().getBlockY()
);
);
worldEdit.setSelection(player, selection);
player.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
@@ -537,7 +524,7 @@ public class RegionCommands {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds:"
+ " (" + min.getBlockX() + "," + min.getBlockY() + "," + min.getBlockZ() + ")"
+ " (" + max.getBlockX() + "," + max.getBlockY() + "," + max.getBlockZ() + ")"
);
);
}
public class RegionEntry implements Comparable<RegionEntry>{
@@ -662,21 +649,14 @@ public class RegionCommands {
}
}
@Command(aliases = {"flag", "f"}, usage = "<id> <flag> [-g group] [value]", flags = "g:w:",
@Command(aliases = {"flag", "f"}, usage = "<id> <flag> [-g group] [value]", flags = "g:",
desc = "Set flags", min = 2)
public void flag(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
String flagName = args.getString(1);
String value = null;
@@ -700,24 +680,20 @@ public class RegionCommands {
// @TODO deprecate "flag.[own./member./blank]"
boolean hasPerm = false;
if (localPlayer == null) {
hasPerm = true;
if (region.isOwner(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.own." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.own." + id.toLowerCase())) hasPerm = true;
} else if (region.isMember(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.member." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.member." + id.toLowerCase())) hasPerm = true;
} else {
if (region.isOwner(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.own." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.own." + id.toLowerCase())) hasPerm = true;
} else if (region.isMember(localPlayer)) {
if (plugin.hasPermission(sender, "worldguard.region.flag.member." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions.member." + id.toLowerCase())) hasPerm = true;
} else {
if (plugin.hasPermission(sender, "worldguard.region.flag." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions." + id.toLowerCase())) hasPerm = true;
}
if (plugin.hasPermission(sender, "worldguard.region.flag." + id.toLowerCase())) hasPerm = true;
else if (plugin.hasPermission(sender, "worldguard.region.flag.regions." + id.toLowerCase())) hasPerm = true;
}
if (!hasPerm) throw new CommandPermissionsException();
Flag<?> foundFlag = null;
// Now time to find the flag!
for (Flag<?> flag : DefaultFlag.getFlags()) {
// Try to detect the flag
@@ -726,57 +702,53 @@ public class RegionCommands {
break;
}
}
if (foundFlag == null) {
StringBuilder list = new StringBuilder();
// Need to build a list
for (Flag<?> flag : DefaultFlag.getFlags()) {
// @TODO deprecate inconsistant "owner" permission
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".owner." + id.toLowerCase())
&& !plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".own." + id.toLowerCase())) {
continue;
}
} else if (region.isMember(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".member." + id.toLowerCase())) {
continue;
}
} else {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + "." + id.toLowerCase())) {
continue;
}
}
}
if (list.length() > 0) {
list.append(", ");
}
// @TODO deprecate inconsistant "owner" permission
if (region.isOwner(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".owner." + id.toLowerCase())
&& !plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".own." + id.toLowerCase())) {
continue;
}
} else if (region.isMember(localPlayer)) {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + ".member." + id.toLowerCase())) {
continue;
}
} else {
if (!plugin.hasPermission(sender, "worldguard.region.flag.flags."
+ flag.getName() + "." + id.toLowerCase())) {
continue;
}
}
list.append(flag.getName());
}
sender.sendMessage(ChatColor.RED + "Unknown flag specified: " + flagName);
sender.sendMessage(ChatColor.RED + "Available flags: " + list);
player.sendMessage(ChatColor.RED + "Unknown flag specified: " + flagName);
player.sendMessage(ChatColor.RED + "Available flags: " + list);
return;
}
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".owner." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + "." + id.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".owner." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + ".member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + "." + id.toLowerCase());
}
if (args.hasFlag('g')) {
@@ -845,37 +817,27 @@ public class RegionCommands {
+ e.getMessage());
}
}
public <V> void setFlag(ProtectedRegion region,
Flag<V> flag, CommandSender sender, String value)
throws InvalidFlagFormat {
throws InvalidFlagFormat {
region.setFlag(flag, flag.parseInput(plugin, sender, value));
}
@Command(aliases = {"setpriority", "priority", "pri"},
usage = "<id> <priority>",
flags = "w:",
desc = "Set the priority of a region",
min = 2, max = 2)
@Command(aliases = {"setpriority", "priority", "pri"}, usage = "<id> <priority>",
desc = "Set the priority of a region", min = 2, max = 2)
public void setPriority(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
int priority = args.getInteger(1);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
@@ -884,22 +846,20 @@ public class RegionCommands {
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setpriority." + id.toLowerCase());
}
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setpriority." + id.toLowerCase());
}
region.setPriority(priority);
sender.sendMessage(ChatColor.YELLOW
+ "Priority of '" + region.getId() + "' set to "
+ priority + ".");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -907,30 +867,20 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"setparent", "parent", "par"},
usage = "<id> [parent-id]",
flags = "w:",
desc = "Set the parent of a region",
min = 1, max = 2)
@Command(aliases = {"setparent", "parent", "par"}, usage = "<id> [parent-id]",
desc = "Set the parent of a region", min = 1, max = 2)
public void setParent(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
if (id.equalsIgnoreCase("__global__")) {
throw new CommandException("The region cannot be named __global__");
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
@@ -944,45 +894,44 @@ public class RegionCommands {
region.setParent(null);
} catch (CircularInheritanceException ignore) {
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' cleared.");
} else {
String parentId = args.getString(1);
ProtectedRegion parent = mgr.getRegion(parentId);
if (parent == null) {
throw new CommandException("Could not find the parent region by that ID.");
}
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
}
if (parent.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + parentId.toLowerCase());
} else if (parent.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + parentId.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + parentId.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
}
if (parent.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + parentId.toLowerCase());
} else if (parent.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + parentId.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + parentId.toLowerCase());
}
try {
region.setParent(parent);
} catch (CircularInheritanceException e) {
throw new CommandException("Circular inheritance detected!");
}
sender.sendMessage(ChatColor.YELLOW
+ "Parent of '" + region.getId() + "' set to '"
+ parent.getId() + "'.");
}
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -990,24 +939,15 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"remove", "delete", "del", "rem"},
usage = "<id>",
flags = "w:",
desc = "Remove a region",
min = 1, max = 1)
@Command(aliases = {"remove", "delete", "del", "rem"}, usage = "<id>",
desc = "Remove a region", min = 1, max = 1)
public void remove(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -1016,22 +956,20 @@ public class RegionCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.remove." + id.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.remove.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.remove." + id.toLowerCase());
}
mgr.removeRegion(id);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' removed.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -1039,21 +977,21 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"load", "reload"}, usage = "[world]",
desc = "Reload regions from file", max = 1)
@CommandPermissions({"worldguard.region.load"})
public void load(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.load();
sender.sendMessage(ChatColor.YELLOW
@@ -1065,7 +1003,7 @@ public class RegionCommands {
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.load();
} catch (ProtectionDatabaseException e) {
@@ -1073,26 +1011,26 @@ public class RegionCommands {
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases loaded.");
}
}
@Command(aliases = {"save", "write"}, usage = "[world]",
desc = "Re-save regions to file", max = 1)
@CommandPermissions({"worldguard.region.save"})
public void save(CommandContext args, CommandSender sender) throws CommandException {
World world = null;
if (args.argsLength() > 0) {
world = plugin.matchWorld(sender, args.getString(0));
}
if (world != null) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
try {
mgr.save();
sender.sendMessage(ChatColor.YELLOW
@@ -1104,7 +1042,7 @@ public class RegionCommands {
} else {
for (World w : plugin.getServer().getWorlds()) {
RegionManager mgr = plugin.getGlobalRegionManager().get(w);
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -1112,7 +1050,7 @@ public class RegionCommands {
+ e.getMessage());
}
}
sender.sendMessage(ChatColor.YELLOW
+ "Region databases saved.");
}
@@ -1170,6 +1108,7 @@ public class RegionCommands {
@Command(aliases = {"teleport", "tp"}, usage = "<id>", flags = "s",
desc = "Teleports you to the location associated with the region.", min = 1, max = 1)
@CommandPermissions({"worldguard.region.teleport"})
public void teleport(CommandContext args, CommandSender sender) throws CommandException {
final Player player = plugin.checkPlayer(sender);
@@ -30,11 +30,11 @@ import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
// @TODO: A lot of code duplication here! Need to fix.
@@ -44,24 +44,15 @@ public class RegionMemberCommands {
public RegionMemberCommands(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@Command(aliases = {"addmember", "addmember"},
usage = "<id> <members...>",
flags = "w:",
desc = "Add a member to a region",
min = 2)
@Command(aliases = {"addmember", "addmember"}, usage = "<id> <members...>",
desc = "Add a member to a region", min = 2)
public void addMember(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -73,21 +64,19 @@ public class RegionMemberCommands {
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
}
RegionDBUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -95,24 +84,15 @@ public class RegionMemberCommands {
+ e.getMessage());
}
}
@Command(aliases = {"addowner", "addowner"},
usage = "<id> <owners...>",
flags = "w:",
desc = "Add an owner to a region",
min = 2)
@Command(aliases = {"addowner", "addowner"}, usage = "<id> <owners...>",
desc = "Add an owner to a region", min = 2)
public void addOwner(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player = null;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -126,24 +106,22 @@ public class RegionMemberCommands {
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (localPlayer != null) {
if (flag != null && flag && owners != null && owners.size() == 0) {
if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
if (maxRegionCount >= 0 && mgr.getRegionCountOfPlayer(localPlayer)
>= maxRegionCount) {
throw new CommandException("You already own the maximum allowed amount of regions.");
}
if (flag != null && flag && owners != null && owners.size() == 0) {
if (!plugin.hasPermission(player, "worldguard.region.unlimited")) {
int maxRegionCount = plugin.getGlobalStateManager().get(world).getMaxRegionCount(player);
if (maxRegionCount >= 0 && mgr.getRegionCountOfPlayer(localPlayer)
>= maxRegionCount) {
throw new CommandException("You already own the maximum allowed amount of regions.");
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
}
plugin.checkPermission(sender, "worldguard.region.addowner.unclaimed." + id.toLowerCase());
} else {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
plugin.checkPermission(sender, "worldguard.region.addowner." + id.toLowerCase());
}
}
@@ -151,7 +129,7 @@ public class RegionMemberCommands {
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -159,24 +137,15 @@ public class RegionMemberCommands {
+ e.getMessage());
}
}
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"},
usage = "<id> <owners...>",
flags = "w:",
desc = "Remove an owner to a region",
min = 2)
@Command(aliases = {"removemember", "remmember", "removemem", "remmem"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeMember(CommandContext args, CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -188,21 +157,19 @@ public class RegionMemberCommands {
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
}
RegionDBUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -210,25 +177,16 @@ public class RegionMemberCommands {
+ e.getMessage());
}
}
@Command(aliases = {"removeowner", "remowner"},
usage = "<id> <owners...>",
flags = "w:",
desc = "Remove an owner to a region",
min = 2)
@Command(aliases = {"removeowner", "remowner"}, usage = "<id> <owners...>",
desc = "Remove an owner to a region", min = 2)
public void removeOwner(CommandContext args,
CommandSender sender) throws CommandException {
final World world;
Player player;
LocalPlayer localPlayer = null;
if (args.hasFlag('w')) {
world = plugin.matchWorld(sender, args.getFlag('w'));
} else {
player = plugin.checkPlayer(sender);
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
}
Player player = plugin.checkPlayer(sender);
World world = player.getWorld();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
@@ -240,21 +198,19 @@ public class RegionMemberCommands {
id = region.getId();
if (localPlayer != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
}
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
}
RegionDBUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
try {
mgr.save();
} catch (ProtectionDatabaseException e) {
@@ -22,15 +22,11 @@ package com.sk89q.worldguard.bukkit.commands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.LagStopMode;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
@@ -45,15 +41,15 @@ public class ToggleCommands {
desc = "Disables all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void stopFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (!wcfg.fireSpreadDisableToggle) {
@@ -74,15 +70,14 @@ public class ToggleCommands {
desc = "Allows all fire spread temporarily", max = 1)
@CommandPermissions({"worldguard.fire-toggle.stop"})
public void allowFire(CommandContext args, CommandSender sender) throws CommandException {
World world;
if (args.argsLength() == 0) {
world = plugin.checkPlayer(sender).getWorld();
} else {
world = plugin.matchWorld(sender, args.getString(0));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(world);
if (wcfg.fireSpreadDisableToggle) {
@@ -98,48 +93,20 @@ public class ToggleCommands {
}
@Command(aliases = {"halt-activity", "stoplag", "haltactivity"},
desc = "Attempts to cease as much activity in order to stop lag", flags = "c", max = 0)
desc = "Attempts to cease as much activity in order to stop lag", flags = "cag", max = 0)
@CommandPermissions({"worldguard.halt-activity"})
public void stopLag(CommandContext args, CommandSender sender) throws CommandException {
LagStopMode lagStopper = plugin.getLagStopMode();
ConfigurationManager configManager = plugin.getGlobalStateManager();
configManager.activityHaltToggle = !args.hasFlag('c');
if (configManager.activityHaltToggle) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity halted by "
+ plugin.toName(sender) + ".");
for (World world : plugin.getServer().getWorlds()) {
int removed = 0;
for (Entity entity : world.getEntities()) {
if (BukkitUtil.isIntensiveEntity(entity)) {
entity.remove();
removed++;
}
}
if (removed > 10) {
sender.sendMessage("" + removed + " entities (>10) auto-removed from "
+ world.toString());
}
}
lagStopper.setRemoveAnimals(!args.hasFlag('c'));
if (!args.hasFlag('c')) {
sender.sendMessage(ChatColor.YELLOW + "Enabling lag stop mode...");
lagStopper.enable(!args.hasFlag('g'));
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.YELLOW
+ "ALL intensive server activity no longer halted.");
}
plugin.getServer().broadcastMessage(ChatColor.YELLOW
+ "ALL intensive server activity is now allowed.");
sender.sendMessage(ChatColor.YELLOW + "Disabling lag stop mode...");
lagStopper.disable();
}
}
}
@@ -32,9 +32,9 @@ import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.rebar.util.MaterialDatabase;
import com.sk89q.worldguard.bukkit.LoggerToChatHandler;
import com.sk89q.worldguard.bukkit.ReportWriter;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.util.PastebinPoster;
import com.sk89q.worldguard.util.PastebinPoster.PasteCallback;
@@ -57,23 +57,23 @@ public class WorldGuardCommands {
@Command(aliases = {"reload"}, desc = "Reload WorldGuard configuration", max = 0)
@CommandPermissions({"worldguard.reload"})
public void reload(CommandContext args, CommandSender sender) throws CommandException {
LoggerToChatHandler handler = null;
Logger minecraftLogger = null;
if (sender instanceof Player) {
handler = new LoggerToChatHandler(sender);
handler.setLevel(Level.ALL);
minecraftLogger = Logger.getLogger("Minecraft");
minecraftLogger = Logger.getLogger("");
minecraftLogger.addHandler(handler);
}
try {
MaterialDatabase.reload();
plugin.getGlobalStateManager().unload();
plugin.getGlobalRegionManager().unload();
plugin.getGlobalStateManager().load();
plugin.getGlobalRegionManager().preload();
WGBukkit.cleanCache();
sender.sendMessage("WorldGuard configuration reloaded.");
} catch (Throwable t) {
sender.sendMessage("Error while reloading: "
@@ -83,15 +83,17 @@ public class WorldGuardCommands {
minecraftLogger.removeHandler(handler);
}
}
plugin.simulateWorldLoad();
}
@Command(aliases = {"report"}, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({"worldguard.report"})
public void report(CommandContext args, final CommandSender sender) throws CommandException {
File dest = new File(plugin.getDataFolder(), "report.txt");
ReportWriter report = new ReportWriter(plugin);
try {
report.write(dest);
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report written to "
@@ -99,18 +101,20 @@ public class WorldGuardCommands {
} catch (IOException e) {
throw new CommandException("Failed to write report: " + e.getMessage());
}
if (args.hasFlag('p')) {
plugin.checkPermission(sender, "worldguard.report.pastebin");
sender.sendMessage(ChatColor.YELLOW + "Now uploading to Pastebin...");
PastebinPoster.paste(report.toString(), new PasteCallback() {
@Override
public void handleSuccess(String url) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report (1 hour): " + url);
}
@Override
public void handleError(String err) {
// Hope we don't have a thread safety issue here
sender.sendMessage(ChatColor.YELLOW + "WorldGuard report pastebin error: " + err);
@@ -0,0 +1,117 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class BlockCriteria implements Criteria<BukkitContext> {
public enum Direction {
AT,
ABOVE,
BELOW,
AROUND
}
private final BlockResolver resolver;
private Direction direction;
private MaterialPattern[] patterns = new MaterialPattern[0];
public BlockCriteria(BlockResolver resolver) {
this.resolver = resolver;
}
public MaterialPattern[] getPatterns() {
return patterns;
}
public void setPatterns(MaterialPattern[] patterns) {
this.patterns = patterns;
}
public void setPatterns(List<MaterialPattern> patterns) {
MaterialPattern[] arr = new MaterialPattern[patterns.size()];
patterns.toArray(arr);
this.patterns = arr;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
private boolean matches(BlockState block) {
for (MaterialPattern pattern : patterns) {
if (pattern.matches(block.getTypeId(), block.getRawData())) {
return true;
}
}
return false;
}
private boolean matches(Block block) {
for (MaterialPattern pattern : patterns) {
if (pattern.matches(block.getTypeId(), block.getData())) {
return true;
}
}
return false;
}
@Override
public boolean matches(BukkitContext context) {
BlockState block = resolver.resolve(context);
if (block == null) {
return false;
}
switch (getDirection()) {
case AT:
return matches(block);
case ABOVE:
return matches(block.getBlock().getRelative(0, 1, 0));
case BELOW:
return matches(block.getBlock().getRelative(0, -1, 0));
case AROUND:
return matches(block.getBlock().getRelative(0, -1, 0)) ||
matches(block.getBlock().getRelative(0, 1, 0)) ||
matches(block.getBlock().getRelative(-1, 0, 0)) ||
matches(block.getBlock().getRelative(1, 0, 0)) ||
matches(block.getBlock().getRelative(0, 0, -1)) ||
matches(block.getBlock().getRelative(0, 0, 1));
}
return false;
}
}
@@ -0,0 +1,74 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.List;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.config.types.MaterialPatternLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.definitions.BlockCriteria.Direction;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class BlockCriteriaLoader extends AbstractNodeLoader<BlockCriteria> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
private EnumLoaderBuilder<Direction> dirLoader = new EnumLoaderBuilder<Direction>(Direction.class);
public BlockCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public BlockCriteria read(ConfigurationNode node)
throws DefinitionException {
BlockResolver resolver = manager.getResolvers()
.get(BlockResolver.class, node.getString("block", BlockResolver.DEFAULT));
// Load patterns
List<MaterialPattern> patterns = node.contains(INLINE) ?
node.listOf(INLINE, materialLoader) : node.listOf("material", materialLoader);
if (patterns.size() == 0) {
throw new LoaderBuilderException("No block materials specified");
}
// Load direction
Direction direction = node.getOf("relative", dirLoader, Direction.AT);
BlockCriteria criteria = new BlockCriteria(resolver);
criteria.setPatterns(patterns);
criteria.setDirection(direction);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"block", "material", "relative");
return criteria;
}
}
@@ -0,0 +1,31 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.Context;
public class CancelAction implements Action<Context> {
@Override
public void apply(Context context) {
context.cancel();
}
}
@@ -0,0 +1,39 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class CancelActionLoader extends AbstractNodeLoader<CancelAction> {
private final CancelAction instance = new CancelAction();
@Override
public CancelAction read(ConfigurationNode node)
throws DefinitionException {
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()));
return instance;
}
}
@@ -0,0 +1,58 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class DamageCriteria implements Criteria<BukkitContext> {
private Set<DamageCause> causes = new HashSet<DamageCause>();
public DamageCriteria(Set<DamageCause> causes) {
this.causes = causes;
}
public Set<DamageCause> getCauses() {
return causes;
}
public void setCauses(Set<DamageCause> causes) {
this.causes = causes;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof EntityDamageEvent) {
return causes.contains(((EntityDamageEvent) event).getCause());
} else {
return false;
}
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.Set;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class DamageCriteriaLoader extends AbstractNodeLoader<DamageCriteria> {
private EnumLoaderBuilder<DamageCause> typeLoader =
new EnumLoaderBuilder<DamageCause>(DamageCause.class);
@Override
public DamageCriteria read(ConfigurationNode node) throws DefinitionException {
Set<DamageCause> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
DamageCriteria criteria = new DamageCriteria(types);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
@@ -0,0 +1,137 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Tameable;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.SourceEntityResolver;
public class EntityCriteria implements Criteria<BukkitContext> {
private final EntityResolver entityResolver;
private Set<EntityType> types = new HashSet<EntityType>();
private Class<?>[] ofTypes = new Class<?>[0];
private Boolean isTamed = null;
// Counteract 1.3->1.4 breaking change
private EntityType fireballType =
BukkitUtil.tryEnum(EntityType.class, "FIREBALL", "LARGE_FIREBALL");
public EntityCriteria(EntityResolver entityResolver) {
this.entityResolver = entityResolver;
}
public Class<?>[] getOfTypes() {
return ofTypes;
}
public void setOfTypes(Class<?>[] ofTypes) {
this.ofTypes = ofTypes;
}
public Set<EntityType> getTypes() {
return types;
}
public void setTypes(Set<EntityType> types) {
this.types = types;
}
public Boolean getIsTamed() {
return isTamed;
}
public void setIsTamed(Boolean isTamed) {
this.isTamed = isTamed;
}
@Override
public boolean matches(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
boolean matched = false;
// Hack because BlockIgniteEvent doesn't give an entity
if (context.getEvent() instanceof BlockIgniteEvent && entityResolver instanceof SourceEntityResolver) {
BlockIgniteEvent igniteEvent = (BlockIgniteEvent) context.getEvent();
if (igniteEvent.getCause() == IgniteCause.FIREBALL) {
if (types.contains(fireballType)) {
matched = true;
}
}
if (igniteEvent.getCause() == IgniteCause.LIGHTNING) {
if (types.contains(EntityType.LIGHTNING)) {
matched = true;
}
}
}
if (entity == null) {
return matched;
}
if (ofTypes.length != 0) {
Class<?> cls = entity.getClass();
for (Class<?> type : ofTypes) {
if (type.isAssignableFrom(cls)) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
if (isTamed != null) {
if (entity instanceof Tameable && ((Tameable) entity).isTamed() == isTamed) {
matched = true;
}
if (!matched) {
return false;
}
}
if (types.size() == 0) {
matched = types.contains(entity.getType());
if (!matched) {
return false;
}
}
return matched;
}
}
@@ -0,0 +1,91 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Creature;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class EntityCriteriaLoader extends AbstractNodeLoader<EntityCriteria> {
private final RuleListsManager manager;
private EnumLoaderBuilder<EntityType> typeLoader =
new EnumLoaderBuilder<EntityType>(EntityType.class);
public EntityCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public EntityCriteria read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
Set<EntityType> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
EntityCriteria criteria = new EntityCriteria(entityResolver);
List<Class<?>> ofTypes = new ArrayList<Class<?>>();
if (node.getBoolean("is-animal", false))
ofTypes.add(Animals.class);
if (node.getBoolean("is-monster", false))
ofTypes.add(Monster.class);
if (node.getBoolean("is-creature", false))
ofTypes.add(Creature.class);
if (node.getBoolean("is-living", false))
ofTypes.add(LivingEntity.class);
if (node.getBoolean("is-player", false))
ofTypes.add(Player.class);
if (node.getBoolean("is-tameable", false))
ofTypes.add(Tameable.class);
criteria.setTypes(types);
criteria.setOfTypes(ofTypes.toArray(new Class<?>[ofTypes.size()]));
criteria.setIsTamed(node.getBoolean("is-tamed"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "type", "is-animal", "is-monster", "is-creature",
"is-living", "is-player", "is-tameable", "is-tamed");
return criteria;
}
}
@@ -0,0 +1,131 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.List;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class ItemCriteria implements Criteria<BukkitContext> {
private final EntityResolver entityResolver;
private final ItemStackSlotResolver itemResolver;
private MaterialPattern[] patterns = new MaterialPattern[0];
private Set<PotionEffectType> potionEffects = null;
private Boolean hasData = false;
public ItemCriteria(EntityResolver entityResolver, ItemStackSlotResolver itemResolver) {
this.entityResolver = entityResolver;
this.itemResolver = itemResolver;
}
public Boolean hasDataCheck() {
return hasData;
}
public void setDataCheck(Boolean hasData) {
this.hasData = hasData;
}
public MaterialPattern[] getPatterns() {
return patterns;
}
public void setPatterns(MaterialPattern[] patterns) {
this.patterns = patterns;
}
public void setPatterns(List<MaterialPattern> patterns) {
MaterialPattern[] arr = new MaterialPattern[patterns.size()];
patterns.toArray(arr);
this.patterns = arr;
}
public Set<PotionEffectType> getPotionEffects() {
return potionEffects;
}
public void setPotionEffects(Set<PotionEffectType> effects) {
this.potionEffects = effects;
}
@Override
public boolean matches(BukkitContext context) {
ItemStack item;
boolean matched = false;
if (entityResolver == null) {
item = context.getItem();
} else {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
item = itemResolver.resolve(entity).get();
}
if (item == null) {
return false;
}
if (hasData != null) {
matched = hasData == (item.getDurability() != 0);
if (!matched) {
return false;
}
}
if (item.getType() == Material.POTION && potionEffects.size() > 0) {
for (PotionEffect effect : Potion.fromItemStack(item).getEffects()) {
if (potionEffects.contains(effect.getType())) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
for (MaterialPattern pattern : patterns) {
if (pattern.matches(item.getTypeId(), item.getDurability())) {
matched = true;
break;
}
}
return matched;
}
}
@@ -0,0 +1,92 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.List;
import java.util.Set;
import org.bukkit.potion.PotionEffectType;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.MaterialPatternLoaderBuilder;
import com.sk89q.rebar.config.types.StaticFieldLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class ItemCriteriaLoader extends AbstractNodeLoader<ItemCriteria> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
private StaticFieldLoaderBuilder<PotionEffectType> effectLoader =
new StaticFieldLoaderBuilder<PotionEffectType>(PotionEffectType.class);
public ItemCriteriaLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public ItemCriteria read(ConfigurationNode node) throws DefinitionException {
String entity = node.getString("entity");
EntityResolver entityResolver = null;
ItemStackSlotResolver resolver = null;
if (entity != null) {
entityResolver = manager.getResolvers()
.get(EntityResolver.class, entity);
resolver = manager.getResolvers()
.get(ItemStackSlotResolver.class, node.getString("item", ItemStackSlotResolver.DEFAULT));
}
// has-data
Boolean hasData = null;
if (node.contains("has-data")) {
hasData = node.getBoolean("has-data", false);
}
// Patterns
List<MaterialPattern> patterns = node.contains(INLINE) ? node.listOf(INLINE,
materialLoader) : node.listOf("material", materialLoader);
if (patterns.size() == 0 && hasData == null) {
throw new LoaderBuilderException("No block materials specified");
}
// Potion effects
Set<PotionEffectType> effects = node.setOf("potion-effect", effectLoader);
ItemCriteria criteria = new ItemCriteria(entityResolver, resolver);
criteria.setPatterns(patterns);
criteria.setDataCheck(hasData);
criteria.setPotionEffects(effects);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"item", "entity", "has-data", "material", "potion-effect");
return criteria;
}
}
@@ -0,0 +1,63 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class PermissionCriteria implements Criteria<BukkitContext> {
private final WorldGuardPlugin wg;
private final EntityResolver entityResolver;
private String permission;
public PermissionCriteria(WorldGuardPlugin wg, EntityResolver entityResolver) {
this.wg = wg;
this.entityResolver = entityResolver;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
@Override
public boolean matches(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return false;
}
if (entity instanceof Player) {
return wg.hasPermission((Player) entity, permission);
}
return false;
}
}
@@ -0,0 +1,60 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class PermissionCriteriaLoader extends AbstractNodeLoader<PermissionCriteria> {
private final WorldGuardPlugin wg;
private final RuleListsManager manager;
public PermissionCriteriaLoader(WorldGuardPlugin wg, RuleListsManager manager) {
this.wg = wg;
this.manager = manager;
}
@Override
public PermissionCriteria read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
String permission = node.contains(INLINE) ?
node.getString(INLINE, "") :
node.getString("permission", "");
PermissionCriteria criteria = new PermissionCriteria(wg, entityResolver);
criteria.setPermission(permission);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "permission");
return criteria;
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.event.Event;
import org.bukkit.event.weather.LightningStrikeEvent;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class PhenomenonCriteria implements Criteria<BukkitContext> {
private Boolean isLightning = null;
public PhenomenonCriteria(Boolean isLightning) {
}
public Boolean getIsLightning() {
return isLightning;
}
public void setIsLightning(Boolean isLightning) {
this.isLightning = isLightning;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (isLightning != null && isLightning && event instanceof LightningStrikeEvent) {
return true;
} else {
return isLightning == null;
}
}
}
@@ -0,0 +1,55 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.Set;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class PhenomenonCriteriaLoader extends AbstractNodeLoader<PhenomenonCriteria> {
public enum Phenomenon {
LIGHTNING;
}
private EnumLoaderBuilder<Phenomenon> typeLoader =
new EnumLoaderBuilder<Phenomenon>(Phenomenon.class);
@Override
public PhenomenonCriteria read(ConfigurationNode node) throws DefinitionException {
Set<Phenomenon> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
PhenomenonCriteria criteria = new PhenomenonCriteria(types.contains(Phenomenon.LIGHTNING));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
@@ -0,0 +1,65 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class SetBlockAction implements Action<BukkitContext> {
private final BlockResolver blockResolver;
private MaterialPattern material;
public SetBlockAction(BlockResolver blockResolver) {
this.blockResolver = blockResolver;
}
public MaterialPattern getMaterial() {
return material;
}
public void setMaterial(MaterialPattern material) {
this.material = material;
}
@Override
public void apply(BukkitContext context) {
BlockState state = blockResolver.resolve(context);
Event event = context.getEvent();
if (state == null) {
return;
}
state.setTypeId(material.getMaterial());
state.setRawData((byte) material.getDefaultData());
if (!(event instanceof BlockPlaceEvent || event instanceof BlockBreakEvent)) {
state.update();
}
}
}
@@ -0,0 +1,64 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.config.types.MaterialPatternLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rebar.util.MaterialPattern;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.BlockResolver;
public class SetBlockActionLoader extends AbstractNodeLoader<SetBlockAction> {
private final RuleListsManager manager;
private MaterialPatternLoaderBuilder materialLoader = new MaterialPatternLoaderBuilder();
public SetBlockActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public SetBlockAction read(ConfigurationNode node) throws DefinitionException {
BlockResolver resolver = manager.getResolvers()
.get(BlockResolver.class, node.getString("block", BlockResolver.DEFAULT));
// Load patterns
MaterialPattern material = node.contains(INLINE) ?
node.getOf(INLINE, materialLoader) : node.getOf("material", materialLoader);
if (material == null) {
throw new LoaderBuilderException("One block material must be specified");
}
SetBlockAction criteria = new SetBlockAction(resolver);
criteria.setMaterial(material);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"block", "material");
return criteria;
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.event.Event;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SetDropAction implements Action<BukkitContext> {
private Integer exp;
public Integer getExp() {
return exp;
}
public void setExp(Integer exp) {
this.exp = exp;
}
@Override
public void apply(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof PlayerDeathEvent) {
PlayerDeathEvent deathEvent = (PlayerDeathEvent) event;
if (exp != null) {
deathEvent.setDroppedExp(exp);
}
}
}
}
@@ -0,0 +1,41 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class SetDropActionLoader extends AbstractNodeLoader<SetDropAction> {
@Override
public SetDropAction read(ConfigurationNode node) throws DefinitionException {
SetDropAction criteria = new SetDropAction();
criteria.setExp(node.getInt("set-xp"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"set-xp");
return criteria;
}
}
@@ -0,0 +1,61 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.ExpressionParser;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SetMessageAction implements Action<BukkitContext> {
private ExpressionParser parser;
private String message;
public SetMessageAction(String message) {
this.message = message;
}
public ExpressionParser getParser() {
return parser;
}
public void setParser(ExpressionParser parser) {
this.parser = parser;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void apply(BukkitContext context) {
String newMessage = message;
if (parser != null) {
newMessage = parser.format(context, newMessage);
}
context.setMessage(newMessage);
}
}
@@ -0,0 +1,58 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.LoaderBuilderException;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
public class SetMessageActionLoader extends AbstractNodeLoader<SetMessageAction> {
private final RuleListsManager manager;
public SetMessageActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public SetMessageAction read(ConfigurationNode node) throws DefinitionException {
String message = node.contains(INLINE) ?
node.getString(INLINE) :
node.getString("message");
if (message == null) {
throw new LoaderBuilderException("No message specified");
}
SetMessageAction action = new SetMessageAction(message);
action.setParser(manager.getParser());
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"message");
return action;
}
}
@@ -0,0 +1,58 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.Event;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SpawnCriteria implements Criteria<BukkitContext> {
private Set<SpawnReason> causes = new HashSet<SpawnReason>();
public SpawnCriteria(Set<SpawnReason> causes) {
this.causes = causes;
}
public Set<SpawnReason> getCauses() {
return causes;
}
public void setCauses(Set<SpawnReason> causes) {
this.causes = causes;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
if (event instanceof CreatureSpawnEvent) {
return causes.contains(((CreatureSpawnEvent) event).getSpawnReason());
} else {
return false;
}
}
}
@@ -0,0 +1,53 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.Set;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class SpawnCriteriaLoader extends AbstractNodeLoader<SpawnCriteria> {
private EnumLoaderBuilder<SpawnReason> typeLoader =
new EnumLoaderBuilder<SpawnReason>(SpawnReason.class);
@Override
public SpawnCriteria read(ConfigurationNode node) throws DefinitionException {
Set<SpawnReason> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
SpawnCriteria criteria = new SpawnCriteria(types);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type");
return criteria;
}
}
@@ -0,0 +1,68 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Action;
import com.sk89q.rulelists.ExpressionParser;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class TellAction implements Action<BukkitContext> {
private ExpressionParser parser;
private EntityResolver entityResolver;
private String message;
public TellAction(EntityResolver entityResolver, String message) {
this.entityResolver = entityResolver;
this.message = message;
}
public ExpressionParser getParser() {
return parser;
}
public void setParser(ExpressionParser parser) {
this.parser = parser;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void apply(BukkitContext context) {
Entity sender = entityResolver.resolve(context);
if (sender != null && sender instanceof CommandSender) {
if (parser != null) {
message = parser.format(context, message);
}
((CommandSender) sender).sendMessage(message);
}
}
}
@@ -0,0 +1,55 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class TellActionLoader extends AbstractNodeLoader<TellAction> {
private final RuleListsManager manager;
public TellActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public TellAction read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
String message = node.contains(INLINE) ? node.getString(INLINE) : node.getString("message");
TellAction action = new TellAction(entityResolver, message);
action.setParser(manager.getParser());
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "message");
return action;
}
}
@@ -0,0 +1,344 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import com.sk89q.rulelists.Action;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class UpdateEntityAction implements Action<BukkitContext> {
private final WorldGuardPlugin wg;
private final EntityResolver entityResolver;
private Boolean explode;
private Float fallDistance;
private Integer fireTicks;
private Integer health;
private Integer damage;
private Integer remainingAir;
private Integer foodLevel;
private Float exhaustionLevel;
private Float saturationLevel;
private Float walkSpeed;
private Boolean allowFlight;
private Boolean flying;
private Float flySpeed;
private Boolean sneaking;
private Boolean sprinting;
private Boolean invincible;
private Boolean openWorkbench;
private String performCommand;
private Boolean teleportSafely;
public UpdateEntityAction(WorldGuardPlugin wg, EntityResolver entityResolver) {
this.wg = wg;
this.entityResolver = entityResolver;
}
public Boolean getExplode() {
return explode;
}
public void setExplode(Boolean explode) {
this.explode = explode;
}
public Float getFallDistance() {
return fallDistance;
}
public void setFallDistance(Float fallDistance) {
this.fallDistance = fallDistance;
}
public Integer getFireTicks() {
return fireTicks;
}
public void setFireTicks(Integer fireTicks) {
this.fireTicks = fireTicks;
}
public Integer getHealth() {
return health;
}
public void setHealth(Integer health) {
this.health = health;
}
public Integer getDamage() {
return damage;
}
public void setDamage(Integer damage) {
this.damage = damage;
}
public Integer getRemainingAir() {
return remainingAir;
}
public void setRemainingAir(Integer remainingAir) {
this.remainingAir = remainingAir;
}
public Integer getFoodLevel() {
return foodLevel;
}
public void setFoodLevel(Integer foodLevel) {
this.foodLevel = foodLevel;
}
public Float getExhaustionLevel() {
return exhaustionLevel;
}
public void setExhaustionLevel(Float exhaustionLevel) {
this.exhaustionLevel = exhaustionLevel;
}
public Float getSaturationLevel() {
return saturationLevel;
}
public void setSaturationLevel(Float saturationLevel) {
this.saturationLevel = saturationLevel;
}
public Float getWalkSpeed() {
return walkSpeed;
}
public void setWalkSpeed(Float walkSpeed) {
this.walkSpeed = walkSpeed;
}
public Boolean getAllowFlight() {
return allowFlight;
}
public void setAllowFlight(Boolean allowFlight) {
this.allowFlight = allowFlight;
}
public Boolean getFlying() {
return flying;
}
public void setFlying(Boolean flying) {
this.flying = flying;
}
public Float getFlySpeed() {
return flySpeed;
}
public void setFlySpeed(Float flySpeed) {
this.flySpeed = flySpeed;
}
public Boolean getSneaking() {
return sneaking;
}
public void setSneaking(Boolean sneaking) {
this.sneaking = sneaking;
}
public Boolean getSprinting() {
return sprinting;
}
public void setSprinting(Boolean sprinting) {
this.sprinting = sprinting;
}
public Boolean getInvincible() {
return invincible;
}
public void setInvincible(Boolean invincible) {
this.invincible = invincible;
}
public Boolean getOpenWorkbench() {
return openWorkbench;
}
public void setOpenWorkbench(Boolean openWorkbench) {
this.openWorkbench = openWorkbench;
}
public String getPerformCommand() {
return performCommand;
}
public void setPerformCommand(String performCommand) {
this.performCommand = performCommand;
}
public Boolean getTeleportSafely() {
return teleportSafely;
}
public void setTeleportSafely(Boolean teleportSafely) {
this.teleportSafely = teleportSafely;
}
@SuppressWarnings("deprecation")
@Override
public void apply(BukkitContext context) {
Entity entity = entityResolver.resolve(context);
if (explode != null)
entity.getWorld().createExplosion(null, 4);
if (fireTicks != null)
entity.setFireTicks(fireTicks);
if (fallDistance != null)
entity.setFallDistance(fallDistance);
if (entity instanceof LivingEntity) {
LivingEntity living = (LivingEntity) entity;
if (health != null)
living.setHealth(health);
if (damage != null)
living.damage(damage);
if (remainingAir != null)
living.setRemainingAir(remainingAir);
}
if (entity instanceof Player) {
Player player = (Player) entity;
if (foodLevel != null)
player.setFoodLevel(foodLevel);
if (saturationLevel != null)
player.setSaturation(saturationLevel);
if (exhaustionLevel != null)
player.setExhaustion(exhaustionLevel);
if (walkSpeed != null)
player.setWalkSpeed(walkSpeed);
if (allowFlight != null)
player.setAllowFlight(allowFlight);
if (flying != null)
player.setFlying(flying);
if (flySpeed != null)
player.setFlySpeed(flySpeed);
if (sneaking != null)
player.setSneaking(sneaking);
if (sprinting != null)
player.setSneaking(sprinting);
if (invincible != null) {
ConfigurationManager cfg = wg.getGlobalStateManager();
if (invincible) {
cfg.enableGodMode(player);
} else {
cfg.disableGodMode(player);
}
}
if (openWorkbench != null && openWorkbench)
player.openWorkbench(player.getLocation(), true);
if (performCommand != null)
player.performCommand(performCommand);
}
if (teleportSafely != null && teleportSafely) {
Location loc = entity.getLocation();
World world = loc.getWorld();
// In case we're in void!
if (loc.getY() < 1) {
loc.setY(1);
}
int maxY = world.getMaxHeight();
int x = loc.getBlockX();
int y = Math.max(0, loc.getBlockY());
int z = loc.getBlockZ();
byte free = 0;
loop:
while (y <= maxY + 2) {
if (BlockType.canPassThrough(new Location(world, x, y, z).getBlock().getTypeId())) {
++free;
} else {
free = 0;
}
if (free == 2) {
Block block = world.getBlockAt(x, y - 2, z);
int id = block.getTypeId();
int data = block.getData();
Location newLoc = new Location(world, x + 0.5,
y - 2 + BlockType.centralTopLimit(id, data), z + 0.5);
// Don't want the player falling into void
if (newLoc.getBlockY() <= 1) {
Block bottomBlock = world.getBlockAt(x, 0, z);
bottomBlock.setType(Material.GLASS);
newLoc.add(0, 1, 0);
}
entity.teleport(newLoc);
entity.setFallDistance(0);
break loop;
}
++y;
}
}
}
}
@@ -0,0 +1,81 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
public class UpdateEntityActionLoader extends AbstractNodeLoader<UpdateEntityAction> {
private final WorldGuardPlugin wg;
private final RuleListsManager manager;
public UpdateEntityActionLoader(WorldGuardPlugin wg, RuleListsManager manager) {
this.wg = wg;
this.manager = manager;
}
@Override
public UpdateEntityAction read(ConfigurationNode node) throws DefinitionException {
EntityResolver entityResolver = manager.getResolvers()
.get(EntityResolver.class, node.getString("entity", EntityResolver.DEFAULT));
UpdateEntityAction criteria = new UpdateEntityAction(wg, entityResolver);
criteria.setExplode(node.getBoolean("explode"));
criteria.setFallDistance(node.getFloat("set-fall-distance"));
criteria.setFireTicks(node.getInt("set-fire-ticks"));
criteria.setTeleportSafely(node.getBoolean("teleport-safely"));
criteria.setHealth(node.getInt("set-health"));
criteria.setDamage(node.getInt("damage"));
criteria.setRemainingAir(node.getInt("set-air"));
criteria.setFoodLevel(node.getInt("food-level"));
criteria.setSaturationLevel(node.getFloat("set-saturation"));
criteria.setExhaustionLevel(node.getFloat("set-exhaustion"));
criteria.setWalkSpeed(node.getFloat("set-walk-speed"));
criteria.setAllowFlight(node.getBoolean("set-allow-flight"));
criteria.setFlying(node.getBoolean("set-flying"));
criteria.setFlySpeed(node.getFloat("set-fly-speed"));
criteria.setSneaking(node.getBoolean("set-sneaking"));
criteria.setSprinting(node.getBoolean("set-sprinting"));
criteria.setInvincible(node.getBoolean("set-invincible"));
criteria.setOpenWorkbench(node.getBoolean("open-workbench"));
criteria.setPerformCommand(node.getString("perform-command"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"entity", "explode", "set-fall-distance",
"set-fire-ticks", "set-health", "damage", "set-air",
"food-level", "set-saturation", "set-exhaustion",
"set-walk-speed", "set-allow-flight", "set-flying",
"set-fly-speed", "set-sneaking", "set-sprinting",
"set-invincible", "open-workbench", "perform-command",
"teleport-safely");
return criteria;
}
}
@@ -0,0 +1,95 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlot;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class UpdateItemAction implements Action<BukkitContext> {
private final EntityResolver entityResolver;
private final ItemStackSlotResolver itemResolver;
private boolean destroy = false;
private short newData = -1;
public UpdateItemAction(EntityResolver entityResolver, ItemStackSlotResolver itemResolver) {
this.entityResolver = entityResolver;
this.itemResolver = itemResolver;
}
public boolean isDestroy() {
return destroy;
}
public void setDestroy(boolean destroy) {
this.destroy = destroy;
}
public short getNewData() {
return newData;
}
public void setNewData(short newData) {
this.newData = newData;
}
@Override
public void apply(BukkitContext context) {
ItemStackSlot slot = null;
ItemStack item;
if (entityResolver == null) {
item = context.getItem();
} else {
Entity entity = entityResolver.resolve(context);
if (entity == null) {
return;
}
slot = itemResolver.resolve(entity);
item = slot.get();
}
if (item == null) {
return;
}
boolean updated = false;
if (destroy) {
item = null;
updated = true;
} else if (newData >= 0) {
item.setDurability(newData);
updated = true;
}
if (updated && slot != null) {
slot.update(item);
}
}
}
@@ -0,0 +1,64 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
import com.sk89q.rulelists.RuleListsManager;
import com.sk89q.worldguard.bukkit.resolvers.EntityResolver;
import com.sk89q.worldguard.bukkit.resolvers.ItemStackSlotResolver;
public class UpdateItemActionLoader extends AbstractNodeLoader<UpdateItemAction> {
private final RuleListsManager manager;
public UpdateItemActionLoader(RuleListsManager manager) {
this.manager = manager;
}
@Override
public UpdateItemAction read(ConfigurationNode node) throws DefinitionException {
String entity = node.getString("entity");
EntityResolver entityResolver = null;
ItemStackSlotResolver resolver = null;
if (entity != null) {
entityResolver = manager.getResolvers()
.get(EntityResolver.class, entity);
resolver = manager.getResolvers()
.get(ItemStackSlotResolver.class, node.getString("item", ItemStackSlotResolver.DEFAULT));
}
boolean destroy = node.getBoolean("destroy", false);
short newData = (short) node.getInt("set-data", -1);
UpdateItemAction action = new UpdateItemAction(entityResolver, resolver);
action.setDestroy(destroy);
action.setNewData(newData);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"item", "entity", "destroy", "set-data");
return action;
}
}
@@ -0,0 +1,75 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import org.bukkit.World;
import org.bukkit.event.Event;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.world.WorldEvent;
import com.sk89q.rulelists.Action;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class UpdateWorldAction implements Action<BukkitContext> {
private Boolean storm = null;
private Boolean thunderstorm = null;
public UpdateWorldAction() {
}
public Boolean getStorm() {
return storm;
}
public void setStorm(Boolean storm) {
this.storm = storm;
}
public Boolean getThunderstorm() {
return thunderstorm;
}
public void setThunderstorm(Boolean thunderstorm) {
this.thunderstorm = thunderstorm;
}
@Override
public void apply(BukkitContext context) {
Event event = context.getEvent();
World world = null;
if (event instanceof WeatherChangeEvent) {
world = ((WeatherChangeEvent) event).getWorld();
} else if (event instanceof WorldEvent) {
world = ((WorldEvent) event).getWorld();
}
if (world != null) {
if (storm != null) {
world.setStorm(storm);
}
if (thunderstorm != null) {
world.setThundering(thunderstorm);
}
}
}
}
@@ -0,0 +1,44 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class UpdateWorldActionLoader extends AbstractNodeLoader<UpdateWorldAction> {
@Override
public UpdateWorldAction read(ConfigurationNode node) throws DefinitionException {
Boolean storm = node.getBoolean("set-storm");
Boolean thunderstorm = node.getBoolean("set-thunderstorm");
UpdateWorldAction action = new UpdateWorldAction();
action.setStorm(storm);
action.setThunderstorm(thunderstorm);
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"set-storm", "set-thunderstorm");
return action;
}
}
@@ -0,0 +1,80 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.event.Event;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import com.sk89q.rulelists.Criteria;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class WeatherCriteria implements Criteria<BukkitContext> {
public enum Type {
STORM,
THUNDERSTORM,
}
private Set<Type> causes = new HashSet<Type>();
private Boolean isStarting = null;
public WeatherCriteria(Set<Type> causes) {
this.causes = causes;
}
public Set<Type> getCauses() {
return causes;
}
public void setCauses(Set<Type> causes) {
this.causes = causes;
}
public Boolean getIsStarting() {
return isStarting;
}
public void setIsStarting(Boolean isStarting) {
this.isStarting = isStarting;
}
@Override
public boolean matches(BukkitContext context) {
Event event = context.getEvent();
boolean startVal = true;
if (isStarting != null) {
startVal = event instanceof WeatherChangeEvent &&
((WeatherChangeEvent) event).toWeatherState() == isStarting;
}
if (event instanceof WeatherChangeEvent) {
return startVal && causes.contains(Type.STORM);
} else if (event instanceof ThunderChangeEvent) {
return startVal && causes.contains(Type.THUNDERSTORM);
} else {
return startVal;
}
}
}
@@ -0,0 +1,52 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.definitions;
import static com.sk89q.rulelists.RuleEntryLoader.INLINE;
import java.util.Set;
import com.sk89q.rebar.config.AbstractNodeLoader;
import com.sk89q.rebar.config.ConfigurationNode;
import com.sk89q.rebar.config.types.EnumLoaderBuilder;
import com.sk89q.rebar.util.LoggerUtils;
import com.sk89q.rulelists.DefinitionException;
import com.sk89q.rulelists.RuleListUtils;
public class WeatherCriteriaLoader extends AbstractNodeLoader<WeatherCriteria> {
private EnumLoaderBuilder<WeatherCriteria.Type> typeLoader =
new EnumLoaderBuilder<WeatherCriteria.Type>(WeatherCriteria.Type.class);
@Override
public WeatherCriteria read(ConfigurationNode node) throws DefinitionException {
Set<WeatherCriteria.Type> types = node.contains(INLINE) ?
node.setOf(INLINE, typeLoader) :
node.setOf("type", typeLoader);
WeatherCriteria criteria = new WeatherCriteria(types);
criteria.setIsStarting(node.getBoolean("is-starting"));
RuleListUtils.warnUnknown(node, LoggerUtils.getLogger(getClass()),
"type", "is-starting");
return criteria;
}
}
@@ -0,0 +1,32 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.block.BlockState;
import com.sk89q.rulelists.Context;
import com.sk89q.rulelists.Resolver;
public interface BlockResolver extends Resolver {
public static final String DEFAULT = "target";
public BlockState resolve(Context context);
}
@@ -0,0 +1,31 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Context;
import com.sk89q.rulelists.Resolver;
public interface EntityResolver extends Resolver {
public static final String DEFAULT = "target";
public Entity resolve(Context context);
}
@@ -0,0 +1,44 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.inventory.ItemStack;
/**
* Indicates an item stack slot that can be updated with a new stack.
*
* @author sk89q
*/
public interface ItemStackSlot {
/**
* Get the current item stack.
*
* @return item stack, or null
*/
ItemStack get();
/**
* Update the slot with a new item stack.
*
* @param stack the new item stack
*/
void update(ItemStack stack);
}
@@ -0,0 +1,30 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Resolver;
public interface ItemStackSlotResolver extends Resolver {
public static final String DEFAULT = "held";
public ItemStackSlot resolve(Entity entity);
}
@@ -0,0 +1,33 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.block.BlockState;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class PlacedBlockResolver implements BlockResolver {
@Override
public BlockState resolve(Context context) {
return ((BukkitContext) context).getPlacedBlock();
}
}
@@ -0,0 +1,127 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class PlayerItemStackSlotResolver implements ItemStackSlotResolver {
public enum Slot {
HELD,
HELMET,
CHESTPLATE,
LEGGINGS,
BOOTS;
}
private final Slot slot;
public PlayerItemStackSlotResolver(Slot slot) {
this.slot = slot;
}
@Override
public ItemStackSlot resolve(Entity entity) {
if (entity != null && entity instanceof HumanEntity) {
final PlayerInventory inventory = ((HumanEntity) entity).getInventory();
switch (slot) {
case HELD:
final ItemStack item = nonNull(inventory.getItemInHand());
return new ItemStackSlot() {
@Override
public void update(ItemStack stack) {
inventory.setItemInHand(stack);
}
@Override
public ItemStack get() {
return item;
}
};
case HELMET:
final ItemStack helmet = nonNull(inventory.getHelmet());
return new ItemStackSlot() {
@Override
public void update(ItemStack stack) {
inventory.setHelmet(stack);
}
@Override
public ItemStack get() {
return helmet;
}
};
case CHESTPLATE:
final ItemStack chestPlate = nonNull(inventory.getChestplate());
return new ItemStackSlot() {
@Override
public void update(ItemStack stack) {
inventory.setChestplate(stack);
}
@Override
public ItemStack get() {
return chestPlate;
}
};
case LEGGINGS:
final ItemStack leggings = nonNull(inventory.getLeggings());
return new ItemStackSlot() {
@Override
public void update(ItemStack stack) {
inventory.setLeggings(stack);
}
@Override
public ItemStack get() {
return leggings;
}
};
case BOOTS:
final ItemStack boots = nonNull(inventory.getBoots());
return new ItemStackSlot() {
@Override
public void update(ItemStack stack) {
inventory.setBoots(stack);
}
@Override
public ItemStack get() {
return boots;
}
};
}
}
return null;
}
private static ItemStack nonNull(ItemStack item) {
return item == null ? new ItemStack(0) : item;
}
}
@@ -0,0 +1,23 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
public class SimpleMethodCaller {
}
@@ -0,0 +1,33 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.block.BlockState;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SourceBlockResolver implements BlockResolver {
@Override
public BlockState resolve(Context context) {
return ((BukkitContext) context).getSourceBlock();
}
}
@@ -0,0 +1,33 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class SourceEntityResolver implements EntityResolver {
@Override
public Entity resolve(Context context) {
return ((BukkitContext) context).getSourceEntity();
}
}
@@ -0,0 +1,33 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.block.BlockState;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class TargetBlockResolver implements BlockResolver {
@Override
public BlockState resolve(Context context) {
return ((BukkitContext) context).getTargetBlock();
}
}
@@ -0,0 +1,33 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU 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.resolvers;
import org.bukkit.entity.Entity;
import com.sk89q.rulelists.Context;
import com.sk89q.worldguard.bukkit.BukkitContext;
public class TargetEntityResolver implements EntityResolver {
@Override
public Entity resolve(Context context) {
return ((BukkitContext) context).getTargetEntity();
}
}
@@ -36,11 +36,12 @@ import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.ConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.databases.ProtectionDatabase;
import com.sk89q.worldguard.protection.databases.YAMLDatabase;
import com.sk89q.worldguard.protection.databases.MySQLDatabase;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.managers.FlatRegionManager;
import com.sk89q.worldguard.protection.managers.PRTreeRegionManager;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -159,10 +160,8 @@ public class GlobalRegionManager {
RegionManager manager = new PRTreeRegionManager(database);
manager.load();
if (plugin.getGlobalStateManager().get(world).summaryOnStart) {
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
}
plugin.getLogger().info(manager.getRegions().size()
+ " regions loaded for '" + name + "'");
return manager;
} catch (ProtectionDatabaseException e) {
@@ -0,0 +1,62 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.WeakHashMap;
/**
* To facilitate performing regions-containing-point lookups from multiple stack frames
* but within the same context (the same event), a cache is important in preventing the
* need for redundant lookups made for the same point. This class serves as such a cache.
* <p>
* A key needs to be selected to store cache entries against. The best key is one that
* is highly temporal, and would represent a certain "snapshot in time," such as
* an event object. The event objects are indexed in this class using weak references,
* and they will be removed by the garbage collector automatically. Because it
* <em>is</em> a weak reference, the key object needs to be held somewhere with a strong
* reference until the "snapshot" ends.
* <p>
* This class is abstract because implementing class should provide methods to check
* against a standard key object. This cache itself is thread-safe.
*/
public abstract class RegionQueryCache {
private final WeakHashMap<Object, RegionQueryCacheEntry> cache =
new WeakHashMap<Object, RegionQueryCacheEntry>();
public RegionQueryCache() {
}
/**
* Get the {@link RegionQueryCacheEntry} object that will cache the
* {@link ApplicableRegionSet}s for this context.
*
* @param key a standard key to store by
* @return an existing QueryCacheEntry or a new one
*/
protected synchronized RegionQueryCacheEntry get(Object key) {
RegionQueryCacheEntry entry = cache.get(key);
if (entry == null) {
entry = new RegionQueryCacheEntry();
cache.put(key, entry);
}
return entry;
}
}
@@ -0,0 +1,76 @@
// $Id$
/*
* This file is a part of WorldGuard.
* Copyright (c) sk89q <http://www.sk89q.com>
* Copyright (c) the 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
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import java.util.HashMap;
import java.util.Map;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* An object to cache a list of {@link ApplicableRegionSet}s. This class is
* thread-safe.
*
* @see RegionQueryCache
*/
public class RegionQueryCacheEntry {
private final Map<BlockVector, ApplicableRegionSet> cachedPoints =
new HashMap<BlockVector, ApplicableRegionSet>();
RegionQueryCacheEntry() {
}
/**
* Get an {@link ApplicableRegionSet} for a given point. If a lookup already has
* been performed, a cached result will be returned.
*
* @param manager the manager
* @param location the location to lookup
* @return the applicable region set
*/
public synchronized ApplicableRegionSet lookup(RegionManager manager, Vector location) {
BlockVector hashableLocation = location.toBlockVector();
ApplicableRegionSet set = cachedPoints.get(hashableLocation);
if (set == null) {
set = manager.getApplicableRegions(location);
cachedPoints.put(hashableLocation, set);
}
return set;
}
/**
* Get an {@link ApplicableRegionSet} for a given region. This method does not yet
* cache results.
*
* @param manager
* the manager
* @param region
* the area to lookup
* @return the applicable region set
*/
public synchronized ApplicableRegionSet lookup(RegionManager manager,
ProtectedRegion region) {
return manager.getApplicableRegions(region);
}
}
@@ -37,7 +37,6 @@ public final class DefaultFlag {
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", true, RegionGroup.ALL);
public static final StateFlag ENDERDRAGON_BLOCK_DAMAGE = new StateFlag("enderdragon-block-damage", true);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true, RegionGroup.ALL);
public static final StateFlag OTHER_EXPLOSION = new StateFlag("other-explosion", true);
public static final StateFlag SLEEP = new StateFlag("sleep", true);
public static final StateFlag TNT = new StateFlag("tnt", true, RegionGroup.ALL);
public static final StateFlag LIGHTER = new StateFlag("lighter", true, RegionGroup.ALL);
@@ -58,8 +57,6 @@ public final class DefaultFlag {
public static final StateFlag MUSHROOMS = new StateFlag("mushroom-growth", true);
public static final StateFlag LEAF_DECAY = new StateFlag("leaf-decay", true);
public static final StateFlag GRASS_SPREAD = new StateFlag("grass-growth", true);
public static final StateFlag MYCELIUM_SPREAD = new StateFlag("mycelium-spread", true);
public static final StateFlag VINE_GROWTH = new StateFlag("vine-growth", true);
public static final StateFlag ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false, RegionGroup.ALL);
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", true, RegionGroup.ALL);
@@ -68,7 +65,6 @@ public final class DefaultFlag {
public static final StateFlag ENTRY = new StateFlag("entry", true);
public static final StateFlag EXIT = new StateFlag("exit", true);
public static final StateFlag ITEM_DROP = new StateFlag("item-drop", true);
public static final StateFlag ENDERPEARL = new StateFlag("enderpearl", true);
public static final StateFlag ENTITY_PAINTING_DESTROY = new StateFlag("entity-painting-destroy", true);
public static final StateFlag ENTITY_ITEM_FRAME_DESTROY = new StateFlag("entity-item-frame-destroy", true);
public static final StateFlag POTION_SPLASH = new StateFlag("potion-splash", true);
@@ -86,11 +82,8 @@ public final class DefaultFlag {
public static final IntegerFlag FEED_AMOUNT = new IntegerFlag("feed-amount", RegionGroup.ALL);
public static final IntegerFlag MIN_FOOD = new IntegerFlag("feed-min-hunger", RegionGroup.ALL);
public static final IntegerFlag MAX_FOOD = new IntegerFlag("feed-max-hunger", RegionGroup.ALL);
// public static final IntegerFlag MAX_PLAYERS = new IntegerFlag("max-players-allowed", RegionGroup.ALL);
// public static final StringFlag MAX_PLAYERS_MESSAGE = new StringFlag("max-players-reject-message", RegionGroup.ALL);
public static final LocationFlag TELE_LOC = new LocationFlag("teleport", RegionGroup.MEMBERS);
public static final LocationFlag SPAWN_LOC = new LocationFlag("spawn", RegionGroup.MEMBERS);
public static final StateFlag ENABLE_SHOP = new StateFlag("allow-shop", false);
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", RegionGroup.ALL, new CommandStringFlag(null));
@@ -100,19 +93,20 @@ public final class DefaultFlag {
PASSTHROUGH, BUILD, CONSTRUCT, PVP, CHEST_ACCESS, PISTONS,
TNT, LIGHTER, USE, PLACE_VEHICLE, DESTROY_VEHICLE, SLEEP,
MOB_DAMAGE, MOB_SPAWNING, DENY_SPAWN, INVINCIBILITY, EXP_DROPS,
CREEPER_EXPLOSION, OTHER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
CREEPER_EXPLOSION, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY, ENDERPEARL,
ENTITY_ITEM_FRAME_DESTROY, ITEM_DROP, /*MAX_PLAYERS, MAX_PLAYERS_MESSAGE,*/
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_DESTROY,
ENTITY_ITEM_FRAME_DESTROY, ITEM_DROP,
HEAL_AMOUNT, HEAL_DELAY, MIN_HEAL, MAX_HEAL,
FEED_DELAY, FEED_AMOUNT, MIN_FOOD, MAX_FOOD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, MYCELIUM_SPREAD, VINE_GROWTH,
SEND_CHAT, RECEIVE_CHAT, FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, SEND_CHAT, RECEIVE_CHAT,
FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, SPAWN_LOC, POTION_SPLASH,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE, ENABLE_SHOP
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE,
};
private DefaultFlag() {
}
+713
View File
@@ -0,0 +1,713 @@
- setting: [auto-invincible, auto-invincible-permission]
rules:
- when: player-join
if:
- ?has-permission: worldguard.auto-invincible
then:
- ?: update-entity
entity: target
set-invincible: true
# ----------------------------------------------
# protection.*
# ----------------------------------------------
- setting: protection.item-durability
negate: true
rules:
- when: block-break
if:
- ?: match-item
entity: source
item: held
has-data: true
then:
- ?: update-item
entity: source
item: held
set-data: 0
- setting: protection.disable-xp-orb-drops
rules:
- when: entity-death
then:
- ?: set-drop
set-xp: 0
- setting: protection.disable-obsidian-generators
rules:
- when: block-spread
if:
- ?: match-block
material: [lava, moving_lava, air]
block: source
- ?: match-block
material: redstone_block
block: target
then:
- ?: set-block
block: target
material: air
# ----------------------------------------------
# default.*
# ----------------------------------------------
- setting: default.pumpkin-scuba
rules:
- when: entity-damage
if:
- ?match-entity: [player]
entity: target
- ?match-damage: drowning
- ?: match-item
material: pumpkin
item: helmet
entity: target
then:
- ?: update-entity
entity: target
set-air: 320
- ?: cancel
# ----------------------------------------------
# physics.*
# ----------------------------------------------
- setting: physics.no-physics-gravel
rules:
- when: block-physics
if:
- ?match-block: gravel
block: target
then:
- ?: cancel
- setting: physics.no-physics-sand
rules:
- when: block-physics
if:
- ?match-block: sand
block: target
then:
- ?: cancel
- setting: physics.no-physics-portal
rules:
- when: block-physics
if:
- ?match-block: portal
block: target
then:
- ?: cancel
- setting: physics.disable-water-damage-blocks
type: list
parameters:
target: "rules[0].if[1].?match-block"
rules:
- when: block-spread
if:
- ?match-block: [water, water_moving]
block: source
- ?match-block: VARIABLE
block: target
then:
- ?: cancel
- setting: physics.block-tnt
rules:
- when: entity-explode
if:
- ?match-entity: primed_tnt
entity: target
then:
- ?: cancel
- when: entity-damage
if:
- ?match-entity: primed_tnt
entity: source
then:
- ?: cancel
- setting: physics.block-tnt-damage
rules:
- when: block-break
if:
- ?match-entity: primed_tnt
entity: source
then:
- ?: cancel
- setting: physics.vine-like-rope-ladders
rules:
- when: block-physics
if:
- ?match-block: ladder
block: target
relative: above
- ?match-block: ladder
block: target
then:
- ?: cancel
# ----------------------------------------------
# ignition.*
# ----------------------------------------------
- setting: ignition.lighter
rules:
- when: item-use
if:
- ?match-block: fire
block: placed
- ?match-entity: [player]
entity: source
- ?match-item: lighter
# context.item
- ?has-permission: worldguard.override.lighter
negate: true
then:
- ?: cancel
# ----------------------------------------------
# fire.*
# ----------------------------------------------
- setting: fire.disable-lava-fire-spread
rules:
- when: block-spread
if:
- ?match-block: fire
block: placed
- ?match-block: [lava, moving_lava]
block: source
then:
- ?: cancel
- setting: fire.disable-all-fire-spread
rules:
- when: block-spread
if:
- ?match-block: fire
block: placed
then:
- ?: cancel
- when: block-break
if:
- ?match-block: fire
block: source
then:
- ?: cancel
- setting: fire.disable-fire-spread-blocks
type: list
parameters:
target: ["rules[0].if[0].?match-block",
"rules[1].if[0].?match-block"]
rules:
- when: block-spread
if:
- ?match-block: VARIABLE
block: target
relative: around
- ?match-block: fire
block: placed
then:
- ?: cancel
- when: block-break
if:
- ?match-block: VARIABLE
block: target
- ?match-block: fire
block: source
then:
- ?: cancel
- setting: fire.lava-spread-blocks
type: list
parameters:
target: "rules[0].if[1].?match-block"
rules:
- when: block-spread
if:
- ?match-block: [lava, moving_lava]
block: source
- ?match-block: VARIABLE
block: target
relative: below
negate: true
then:
- ?: cancel
- setting: [fire.disable-lightning-strike-fire, weather.disable-lightning-strike-fire]
rules:
- when: block-place
if:
- ?match-block: fire
block: placed
- ?match-entity: lightning
entity: source
then:
- ?: cancel
# ----------------------------------------------
# mobs.*
# ----------------------------------------------
- setting: mobs.block-enderdragon-block-damage
rules:
- when: block-break
if:
- ?match-entity: enderdragon
entity: source
then:
- ?: cancel
- setting: mobs.block-fireball-explosions
rules:
- when: entity-explode
if:
- ?match-entity: fireball
entity: target
then:
- ?: cancel
- setting: mobs.block-fireball-block-damage
rules:
- when: block-break
if:
- ?match-entity: fireball
entity: source
then:
- ?: cancel
- setting: mobs.disable-enderman-griefing
rules:
- when: [block-place, block-break]
if:
- ?match-entity: enderman
entity: source
then:
- ?: cancel
# Creepers
- setting: mobs.block-creeper-explosions
rules:
- when: entity-damage
if:
- ?match-entity: creeper # Why is this needed?
entity: source
then:
- ?: cancel
- when: entity-explode
if:
- ?match-entity: creeper
entity: target
then:
- ?: cancel
- setting: mobs.block-creeper-block-damage
rules:
- when: block-break
if:
- ?match-entity: creeper
entity: source
then:
- ?: cancel
# Make pets very low-maintenance
- setting: [mobs.wolves-practically-invincible, mobs.anti-wolf-dumbness]
rules:
- when: entity-damage
if:
- ?match-entity: wolf
entity: target
then:
- ?: cancel
- setting: mobs.ocelots-practically-invincible
rules:
- when: entity-damage
if:
- ?match-entity: ocelot
entity: target
then:
- ?: cancel
# Mobs breaking things that they shouldn't
- setting: mobs.block-painting-destroy
rules:
- when: entity-damage
if:
- ?match-entity: painting
entity: target
- ?match-entity: player
negate: true
entity: source
then:
- ?: cancel
- setting: mobs.block-item-frame-destroy
rules:
- when: entity-damage
if:
- ?match-entity: item_frame
entity: target
- ?match-entity: player
negate: true
entity: source
then:
- ?: cancel
# Spawning
- setting: mobs.block-creature-spawn
type: list
parameters:
target: "rules[0].if[0].?match-entity"
rules:
- when: entity-spawn
if:
- ?match-entity: PLACEHOLDER
entity: target
then:
- ?: cancel
- setting: mobs.block-plugin-spawning
rules:
- when: entity-spawn
if:
- ?match-spawn: plugin
then:
- ?: cancel
# Withers
- setting: mobs.block-wither-explosions
rules:
- when: entity-damage # Why is this needed?
if:
- ?match-entity: wither
entity: source
then:
- ?: cancel
- when: entity-explode
if:
- ?match-entity: wither
entity: target
then:
- ?: cancel
- setting: mobs.block-wither-block-damage
rules:
- when: block-break
if:
- ?match-entity: wither
entity: source
then:
- ?: cancel
# Wither skulls
- setting: mobs.block-wither-skull-explosions
rules:
- when: entity-damage # Why is this needed?
if:
- ?match-entity: wither_skull
entity: source
then:
- ?: cancel
- when: entity-explode
if:
- ?match-entity: wither_skull
entity: target
then:
- ?: cancel
- setting: mobs.block-wither-skull-block-damage
rules:
- when: block-break
if:
- ?match-entity: wither_skull
entity: source
then:
- ?: cancel
# ----------------------------------------------
# player-damage.*
# ----------------------------------------------
- setting: player-damage.teleport-on-suffocation
rules:
- when: entity-damage
if:
- ?match-damage: suffocation
- ?match-entity: player
entity: target
then:
- ?: update-entity
entity: target
teleport-safely: true
- ?: cancel
- setting: player-damage.teleport-on-void-falling
rules:
- when: entity-damage
if:
- ?match-damage: void
- ?match-entity: player
entity: target
then:
- ?: update-entity
entity: target
teleport-safely: true
- ?: cancel
- setting: player-damage.disable-death-messages
rules:
- when: entity-death
if:
- ?match-entity: player
entity: target
then:
- ?set-message: ""
- setting: player-damage.disable-fall-damage
rules:
- when: entity-damage
if:
- ?match-damage: fall
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-lava-damage
rules:
- when: entity-damage
if:
- ?match-damage: lava
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-fire-damage
rules:
- when: entity-damage
if:
- ?match-damage: [fire, fire_tick]
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-lightning-damage
rules:
- when: entity-damage
if:
- ?match-damage: lightning
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-drowning-damage
rules:
- when: entity-damage
if:
- ?match-damage: drowning
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-suffocation-damage
rules:
- when: entity-damage
if:
- ?match-damage: suffocation
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-contact-damage
rules:
- when: entity-damage
if:
- ?match-damage: contact
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-void-damage
rules:
- when: entity-damage
if:
- ?match-damage: void
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-explosion-damage
rules:
- when: entity-damage
if:
- ?match-damage: [entity_explosion, block_explosion]
- ?match-entity: player
entity: target
then:
- ?: cancel
- setting: player-damage.disable-mob-damage
rules:
- when: entity-damage
if:
- ?match-damage: entity_attack
- ?match-entity: player
entity: target
then:
- ?: cancel
# ----------------------------------------------
# crops.*
# ----------------------------------------------
- setting: crops.disable-creature-trampling
rules:
- when: block-interact
if:
- ?match-block: soil
- ?: match-entity
is-living: true
entity: source
then:
- ?: cancel
- setting: crops.disable-player-trampling
rules:
- when: block-interact
if:
- ?match-block: soil
- ?match-entity: player
entity: source
then:
- ?: cancel
# ----------------------------------------------
# weather.*
# ----------------------------------------------
- setting: weather.prevent-lightning-strike-blocks
type: list
parameters:
target: "rules[0].if[1].?match-block"
rules:
- when: weather-phenomenon
if:
- ?match-phenomenon: lightning
- ?match-block: VARIABLE
block: target
negate: true
then:
- ?: cancel
- setting: weather.disable-thunderstorm
rules:
- when: weather-transition
if:
- ?match-weather: thunderstorm
is-starting: true
then:
- ?: cancel
- when: world-load
then:
- ?: update-world
set-thunderstorm: false
- setting: weather.disable-weather
rules:
- when: weather-transition
if:
- ?match-weather: storm
is-starting: true
then:
- ?: cancel
- when: world-load
then:
- ?: update-world
set-storm: false
- setting: weather.disable-pig-zombification
rules:
- when: entity-strike
if:
- ?match-entity: pig
entity: target
then:
- ?: cancel
- setting: weather.disable-powered-creepers
rules:
- when: entity-strike
if:
- ?match-entity: creeper
entity: target
then:
- ?: cancel
- setting: weather.always-thundering
rules:
- when: weather-transition
if:
- ?match-weather: thunderstorm
is-starting: false
then:
- ?: cancel
- when: world-load
then:
- ?: update-world
set-thunderstorm: true
- setting: weather.always-raining
rules:
- when: weather-transition
if:
- ?match-weather: storm
is-starting: false
then:
- ?: cancel
- when: world-load
then:
- ?: update-world
set-storm: true
# ----------------------------------------------
# dynamics.*
# ----------------------------------------------
- setting: dynamics.disable-mushroom-spread
rules:
- when: block-spread
if:
- ?match-block: [red_mushroom, brown_mushroom]
block: placed
then:
- ?: cancel
- setting: dynamics.disable-ice-melting
rules:
- when: block-fade
if:
- ?match-block: ice
block: target
then:
- ?: cancel
- setting: dynamics.disable-snow-melting
rules:
- when: block-fade
if:
- ?match-block: snow
block: target
then:
- ?: cancel
- setting: dynamics.disable-snow-formation
rules:
- when: block-form
if:
- ?match-block: snow
block: placed
then:
- ?: cancel
- setting: dynamics.disable-ice-formation
rules:
- when: block-form
if:
- ?match-block: ice
block: placed
then:
- ?: cancel
- setting: dynamics.disable-leaf-decay
rules:
- when: block-fade
if:
- ?match-block: leaves
block: target
then:
- ?: cancel
- setting: dynamics.disable-grass-growth
rules:
- when: block-spread
if:
- ?match-block: grass
block: placed
then:
- ?: cancel
- setting: dynamics.disable-mycelium-spread
rules:
- when: block-spread
if:
- ?match-block: mycelium
block: placed
then:
- ?: cancel
-22
View File
@@ -1,22 +0,0 @@
#
# WorldGuard's configuration file
#
# About editing this file:
# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If
# you use an editor like Notepad++ (recommended for Windows users), you
# must configure it to "replace tabs with spaces." In Notepad++, this can
# be changed in Settings > Preferences > Language Menu.
# - Don't get rid of the indents. They are indented so some entries are
# in categories (like "enforce-single-session" is in the "protection"
# category.
# - If you want to check the format of this file before putting it
# into WorldGuard, paste it into http://yaml-online-parser.appspot.com/
# and see if it gives "ERROR:".
# - Lines starting with # are commentsand so they are ignored.
#
# WARNING:
# Remember to check the compatibility spreadsheet for WorldGuard to see
# if any features are currently broken in your version of Bukkit.
#
# -- This should be automatically replaced by the plugin in-game --
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more