Compare commits

...
77 Commits
Author SHA1 Message Date
sk89q ca95ae04a5 [maven-release-plugin] prepare release 5.5.3 2012-07-07 10:55:45 -07:00
sk89q 1ab9f85ca6 Updated CHANGELOG. 2012-07-07 10:39:37 -07:00
sk89q 01ff1b2f8f Added host key check. 2012-07-07 10:33:18 -07:00
Zak Ford 9b17fe68e7 Added configuration option to allow plugin creature spawns 2012-07-01 16:02:24 -04:00
zml2008 0fed35a80f Add bypass handling to the gamemode flag
Set a player's previous gamemode when exiting a gamemode region to the server's default gamemode if there is not a previous gamemode already set
2012-06-15 14:14:13 -07:00
TomyLobo 25280c9fa9 Set Bukkit dependency to R2.1.
That's the current CraftBukkit++ version.
2012-06-11 03:31:50 +02:00
TomyLobo a98ebfdb21 Updated dependencies and added support for fireball item blocking (id 385). 2012-06-07 13:26:28 +02:00
TomyLobo 18b5a4e106 Added @Ignore to TestPlayer.
Stupid old mavens...
2012-04-23 11:07:05 +02:00
md_5 bab420a359 Add item drop pickup flag for regions.
Closes #200
2012-04-20 20:25:25 -07:00
zml2008 4f14f1f736 Correctly convert \n to a newline for String flags 2012-04-16 17:00:41 -07:00
zml2008 166831447c Split the region greeting with \n
Improve input handling of EnumFlag
Don't block gamemode changing after the gamemode flag is no longer in
effect but while the move event is still firing
2012-04-15 21:19:02 -07:00
zml2008 f2bd5961d0 Add GameMode flag 2012-04-15 21:19:02 -07:00
zml2008 2cc990a530 Prevent commands in the allow commands list from being blocked and vice versa 2012-04-15 21:19:02 -07:00
TomyLobo f0e6008563 Updated bukkit dependency to 1.2.5-R1.2-SNAPSHOT. 2012-04-15 19:36:15 +02:00
zml2008 93f19cca0a [maven-release-plugin] prepare for next development iteration 2012-04-10 18:30:42 -07:00
zml2008 1cbe508f82 [maven-release-plugin] prepare release 5.5.2 2012-04-10 18:30:36 -07:00
zml2008 0c178c3155 Added recent commits to the changelog 2012-04-10 18:20:57 -07:00
zml2008 e67304389d Added send-chat and receive-chat flags 2012-04-07 14:43:51 -07:00
zml2008 ad5b1cdcba Make sure to update CommandBook installed status in onEnable 2012-04-07 13:46:25 -07:00
zml2008 fe1e09289f Add entity-painting-destroy flag to prevent entities from destroying paintings 2012-04-07 13:45:46 -07:00
zml2008 583ea76e4b Added potion splash flag to prevent splash potions from affecting entities 2012-04-07 12:11:00 -07:00
zml2008 a7d198893e Revert "Added allow-flight boolean flag for regions"
This conflicted with plugins maually setting a player's allow flight setting
This reverts commit 16ce56c1ad.
2012-03-31 07:53:42 -07:00
Nicholas Steicke fe62c8d0c5 Fixed regions with same name in different worlds not behaving correctly
Fixed database connection timing out

Added an error to be thrown explictly when the DB needs updating

Added a generic exception for Fatal errors when loading configuration

Exit the server when we encounter a fatal configuration exception
2012-03-27 17:18:39 -07:00
Deaygo 16ce56c1ad Added allow-flight boolean flag for regions
Closes #198
2012-03-24 18:45:56 -07:00
zml2008 15f0bfb9db Update changelog for release 2012-03-23 21:47:34 -07:00
TomyLobo 22db589742 Restructured /rg list.
- When used with a player name to filter things down, it displays indexes that can be used as "#index" in place of region names now.
- No longer displayer "+-regionname" for regions the target player is the owner of.
2012-03-23 15:13:46 +01:00
TomyLobo 69119e6db7 Added ProtectedRegion.isOwner/Member(String playerName). 2012-03-23 15:13:45 +01:00
TomyLobo 690da2332b Added Domain.contains(String playerName). 2012-03-23 15:13:45 +01:00
sk89q f2fead1444 Changed broadcastNotification() to also check if the player has permission via superperms, in addition to being in the Permissible set. 2012-03-18 13:13:13 -07:00
TomyLobo c4f6267921 A cancellable event is now fired if WorldGuard disallows PvP. 2012-03-17 09:16:03 +01:00
TomyLobo 0dc65d083f Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
Same with worldguard.region.setparent.<id>
2012-03-12 15:08:35 +01:00
TomyLobo 40c1d93f02 Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
/region claim/remove/redefine are exempt from this and require exact matches.
2012-03-12 15:05:59 +01:00
TomyLobo 2024a93126 Fixed an error that occured when clearing a non-existant region's parent. 2012-03-12 15:05:32 +01:00
TomyLobo 88d79a42e6 Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region. 2012-03-12 10:40:03 +01:00
TomyLobo b01b2cce9b Added region/role-based permissions to /region teleport. 2012-03-12 10:39:23 +01:00
TomyLobo c5b1089c96 Changed source and target java version to 1.6 and set the WE dependency to 5.3-SNAPSHOT. 2012-03-12 08:04:08 +01:00
TomyLobo 679e43758b BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
This means all teleport and spawn flags are cleared.
This also means that world, yaw and pitch are now saved with these flags.
2012-03-12 06:52:36 +01:00
TomyLobo 90e6e5a96c /region info -s now selects the region being queried. 2012-03-12 05:53:58 +01:00
TomyLobo 4fb003c4df Added /region teleport <id>. 2012-03-11 19:31:02 +01:00
TomyLobo 9d5f349a04 Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z. 2012-03-11 19:08:25 +01:00
TomyLobo f4f4a47a7f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:08:24 +01:00
TomyLobo 6a3e987668 /region info changes
- Fixed /region info <world> <id> checking the wrong permission
- Condensed /region info output a bit
- Cleaned up the source a bit
2012-03-11 19:07:25 +01:00
TomyLobo 83f943965f Made /region info show the region you're in if you don't specify an id explicitly. 2012-03-11 19:07:25 +01:00
zml2008 c9fdff169f Prevent block ignition from lightning strikes if lightning is blocked in region.
Fixes #1175
2012-03-10 21:33:24 -08:00
zml2008 5454832918 Fix trailing whitespace and correctly check both permisions systems in WorldGurdPlugin.broadcastNotification() 2012-03-10 17:56:02 -08:00
zml2008 3d6d774b17 Use ignoreCancelled for event cancelled checking 2012-03-08 19:29:53 -08:00
zml2008 1463547af4 Destroy fire blocks when fire-spread is disallowed 2012-03-08 19:03:05 -08:00
TomyLobo 0bcf4b3597 Added a "none" category to region group flags (aliases noone and deny). 2012-03-08 10:30:57 +01:00
TomyLobo 824e8dcb4b Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles. 2012-03-08 10:18:27 +01:00
TomyLobo 4b2f0c8020 Let's not confuse certain highlighters. 2012-03-08 02:05:33 +01:00
Wizjany 7fd424cf65 Added FallingSand to list of intensive entities to be removed with /halt-activiy. 2012-03-03 21:27:35 -05:00
zml2008 5ff2855eb0 Fix entry and exit group flags not working, fix vehicle destroy flag not being allowed with canBuild 2012-03-03 16:46:06 -08:00
TomyLobo 8c8c162a54 Replaced all usage of CreatureType by EntityType. 2012-03-02 20:21:04 +01:00
TomyLobo 37d52f3688 Commented an unused local variable. 2012-03-02 20:10:51 +01:00
TomyLobo f361cbfa71 Removed unused imports. 2012-03-02 20:03:18 +01:00
sk89q ddefbfe2cf Fixed NPE with null ItemStack for pumpkin scuba in EntityDamageEvent. 2012-03-02 10:33:14 -08:00
sk89q 10296cb736 Made auto-god-mode disabled by default again. 2012-03-01 20:57:34 -08:00
zml2008 49dc0599c9 Remove leftover 128 value, fix RegionGroup.ALL handling 2012-03-01 20:49:01 -08:00
zml2008 14348e170b Revert a few of the region flag changes. This should fix issues people have been having at least for now. 2012-03-01 20:11:51 -08:00
zml2008 59d1f0d817 5.5.1 release, bump to 5.5.2-SNAPSHOT to fix stuff 2012-03-01 20:11:50 -08:00
sk89q e024f134a4 Fixed another NPE with the infinite stack remover. 2012-03-01 20:06:02 -08:00
sk89q cf5a5b5b47 Fixed NPE in PlayerInteractEvent regarding infinite stack removal. 2012-03-01 19:52:53 -08:00
sk89q e957f92496 Added sign protection check disable. 2012-03-01 18:51:44 -08:00
TomyLobo 9484bb9941 Fixed some more warnings. 2012-02-25 18:58:22 +01:00
TomyLobo d781f9822f Removed some unused imports. 2012-02-25 18:54:46 +01:00
Wizjany 7845ef2de4 Revert b918b2914.
That breaks it, look at the other use flags before making changes.
2012-02-22 11:36:30 -05:00
zml2008 a9d4ecf33d Improved some group flag defaults to match pre-change behavior 2012-02-20 15:17:34 -08:00
zml2008 6f4a62c7a3 Cleaned up javadoc, deprecated duplicate methods, other cleanup 2012-02-20 15:14:55 -08:00
zml2008 6b4f872742 Added a RegionGroupFlag to evey region flag
Using the /region flag command with -g, the region group that the region flag applies to can be set
Many canBuild checks that occurred with other flag checks have been
replced with this. Some flag checks may be incorrect, and other parts of
this system may need improvement.
2012-02-19 23:31:55 -08:00
zml2008 ef4f00f8f5 Add region information to CommandBook's /whois if CommandBook is eanbled 2012-02-19 21:26:45 -08:00
zml2008 a27deb3936 Removed suppress-tick-sync-warnings setting
This setting often didn't work for people, and has been replaced in CraftBukkit's bukkit.yml with settings.warn-on-overload
2012-02-19 21:24:53 -08:00
TomyLobo 18814c7373 Set WorldGuardPlayerListener.PlayerMoveHandler to default visibility, to fix a warning about unused methods. 2012-02-14 02:32:35 +01:00
TomyLobo 1d9908e1f6 Merged the handlers for EndermanPickup/PlaceEvent into a EntityChangeBlockEvent handler. 2012-02-14 02:32:24 +01:00
TomyLobo 29529e4a06 Removed unused imports. 2012-02-14 02:23:35 +01:00
TomyLobo 74b1003c4c Upped dependency versions for bukkit and worldedit. 2012-02-14 02:21:54 +01:00
NolanSyKinsley 27ffdec323 Fixes shooting onto pvp areas from nopvp areas 2012-02-13 13:54:44 -08:00
zml2008 d9e5fc2b60 [maven-release-plugin] prepare for next development iteration 2012-02-11 16:22:22 -08:00
84 changed files with 2668 additions and 2077 deletions

No files matched your search

+46
View File
@@ -1,3 +1,49 @@
5.5.3:
- Added game mode flag.
- Added item drop pickup flag to regions.
- Added support for fireball item blocking (385).
- Added configuration option to allow creature spawns from plugins.
- Added host key check.
- Added a new line split feature to region greetings.
- Prevented commands in the allow commands list from being blocked and
vice versa.
5.5.2:
- Added potion-splash flag to block splash potions
- Add entity-painting-destroy which can be used to prevent entities from destroying paintings (skeletons firing arrows)
- Added send-chat and receive-chat flags
- Fixed having regions in multiple worlds with the same name not working with MySQL
- A cancellable event is now fired if WorldGuard disallows PvP. (for developers!)
- Made /region setparent check worldguard.region.setparent.own/member.<parent> instead of worldguard.region.setparent.own/member.<child>.
- Allowed passing #<index> in place of a region ID, where <index> is the index as displayed by /region list.
- Fixed an error that occured when clearing a non-existant region's parent.
- Added a -s flag to /region teleport, which sends you to the spawn point instead of the teleport point of a region.
- Added region/role-based permissions to /region teleport.
- BREAKING CHANGE: Added a LocationFlag class and made the teleport and spawn flags use it.
- /region info -s now selects the region being queried.
- Added /region teleport <id>.
- Vector flags can now be set to the current location with the value "here" and to a specific position with x,y,z.
- Made /region info show the region you're in if you don't specify an id explicitly.
- Prevent block ignition from lightning strikes if lightning is blocked in region. Fixes #1175
- Correctly check both WEPIF and superperms in WorldGurdPlugin.broadcastNotification()
- Destroy fire blocks when fire-spread is disallowed
- Added a construct flag that can be used to restrict block placing/destroying in zones to certain roles.
- Added FallingSand to list of intensive entities to be removed with /halt-activiy.
- Replaced all usage of CreatureType by EntityType.
- Updated to support Bukkit 1.2-R0.3 and newer
- Made auto-god-mode disabled by default again.
- Added sign protection check disable.
- Cleaned up javadoc, deprecated duplicate methods, other cleanup
- Added a RegionGroupFlag to evey region flag Using the /region flag command with -g, the region group that the region flag applies to can be set.
5.5.1:
- Fixed attacking with arrows from non-PVP to PVP areas
- Compatibility with Bukkit 1.1-R5
- Removed broken suppress-tick-sync-warnings config option. See bukkit.yml's setings.warn-on-overload option instead.
- Add region and 'can build' information to CommandBook's /whois
Contributions thanks to: NolanSyKinsley
5.5:
- Removed WorldEdit.jar from the classpath to stop conflicts with Bukkit's plugin loader
- Now using Bukkit's tagged logging
+13 -9
View File
@@ -1,13 +1,13 @@
<!--
Maven build file for WorldGuard
Copyright (c) 2011 sk89q <http://www.sk89q.com>
Copyright (c) 2011 sk89q <http://www.sk89q.com>
WorldGuard is available under the GNU General Public License v3
-->
<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.5</version>
<version>5.5.3</version>
<name>WorldGuard</name>
<description>WorldGuard protects your Minecraft servers</description>
@@ -40,23 +40,23 @@
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.2</version>
<version>5.4-SNAPSHOT</version>
</dependency>
<!-- Bukkit -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.1-R3</version>
<version>1.2.5-R4.0</version>
</dependency>
<!-- CommandBook -->
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>commandbook</artifactId>
<version>2.0</version>
</dependency>
<!-- Additional libraries -->
<dependency>
<groupId>com.nijikokun</groupId>
@@ -112,6 +112,10 @@
<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>
<!-- JAR creation plugin -->
@@ -160,7 +164,7 @@
<!-- Assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<version>2.2-beta-2</version>
<configuration>
<descriptor>${basedir}/src/main/assembly/default.xml</descriptor>
</configuration>
@@ -188,7 +192,7 @@
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Javadocs -->
Executable → Regular
+144 -111
View File
@@ -2,180 +2,213 @@ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `group`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `group` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `world`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `world` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 9
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region` (
`id` VARCHAR(128) NOT NULL ,
`world_id` INT UNSIGNED NOT NULL ,
`type` ENUM('cuboid','poly2d','global') NOT NULL ,
`priority` SMALLINT NOT NULL DEFAULT 0 ,
`parent` VARCHAR(128) NULL ,
`id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`type` ENUM('cuboid','poly2d','global') CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`priority` SMALLINT(6) NOT NULL DEFAULT '0' ,
`parent` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NULL DEFAULT NULL ,
PRIMARY KEY (`id`, `world_id`) ,
INDEX `parent` (`parent` ASC) ,
INDEX `fk_region_world` (`world_id` ASC) ,
CONSTRAINT `parent`
FOREIGN KEY (`parent` )
REFERENCES `region` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
INDEX `parent` (`parent` ASC) ,
CONSTRAINT `fk_region_world1`
FOREIGN KEY (`world_id` )
REFERENCES `world` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_flag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_flag` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`flag` VARCHAR(64) NOT NULL ,
`value` VARCHAR(256) NOT NULL ,
INDEX `fk_flags_region` (`region_id` ASC) ,
PRIMARY KEY (`id`) ,
CONSTRAINT `fk_flags_region1`
FOREIGN KEY (`region_id` )
ON UPDATE CASCADE,
CONSTRAINT `parent`
FOREIGN KEY (`parent` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_cuboid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_cuboid` (
`region_id` VARCHAR(128) NOT NULL ,
`min_z` BIGINT NOT NULL ,
`min_y` BIGINT NOT NULL ,
`min_x` BIGINT NOT NULL ,
`max_z` BIGINT NOT NULL ,
`max_y` BIGINT NOT NULL ,
`max_x` BIGINT NOT NULL ,
PRIMARY KEY (`region_id`) ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`min_x` BIGINT(20) NOT NULL ,
`min_y` BIGINT(20) NOT NULL ,
`min_z` BIGINT(20) NOT NULL ,
`max_x` BIGINT(20) NOT NULL ,
`max_y` BIGINT(20) NOT NULL ,
`max_z` BIGINT(20) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`) ,
INDEX `fk_region_cuboid_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_poly2d`
-- Table `region_flag`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d` (
`region_id` VARCHAR(128) NOT NULL ,
`max_y` INT NOT NULL ,
`min_y` INT NOT NULL ,
PRIMARY KEY (`region_id`) ,
INDEX `fk_region_poly2d_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
CREATE TABLE IF NOT EXISTS `region_flag` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`flag` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`value` VARCHAR(256) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_flags_region` (`region_id` ASC, `world_id` ASC) ,
CONSTRAINT `fk_flags_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_players`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_players` (
`region_id` VARCHAR(128) NOT NULL ,
`user_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `user_id`) ,
INDEX `fk_region_players_region` (`region_id` ASC) ,
INDEX `fk_region_players_user` (`user_id` ASC) ,
CONSTRAINT `fk_region_players_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_players_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
ENGINE = InnoDB
AUTO_INCREMENT = 3246
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_groups` (
`region_id` VARCHAR(128) NOT NULL ,
`group_id` INT UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `group_id`) ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`group_id` INT(10) UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`, `group_id`) ,
INDEX `fk_region_groups_region` (`region_id` ASC) ,
INDEX `fk_region_groups_group` (`group_id` ASC) ,
CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` )
REFERENCES `region` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(64) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name` (`name` ASC) )
ENGINE = InnoDB
AUTO_INCREMENT = 82
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_players`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_players` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`user_id` INT(10) UNSIGNED NOT NULL ,
`owner` TINYINT(1) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`, `user_id`) ,
INDEX `fk_region_players_region` (`region_id` ASC) ,
INDEX `fk_region_users_user` (`user_id` ASC) ,
CONSTRAINT `fk_region_users_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_region_users_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_poly2d`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d` (
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`min_y` INT(11) NOT NULL ,
`max_y` INT(11) NOT NULL ,
PRIMARY KEY (`region_id`, `world_id`) ,
INDEX `fk_region_poly2d_region` (`region_id` ASC) ,
CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `region_poly2d_point`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `region_poly2d_point` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) NOT NULL ,
`z` BIGINT NOT NULL ,
`x` BIGINT NOT NULL ,
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT ,
`region_id` VARCHAR(128) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
`world_id` INT(10) UNSIGNED NOT NULL ,
`x` BIGINT(20) NOT NULL ,
`z` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC) ,
INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC, `world_id` ASC) ,
CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` )
REFERENCES `region_poly2d` (`region_id` )
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region_poly2d` (`region_id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
ENGINE = InnoDB
AUTO_INCREMENT = 15
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
+106
View File
@@ -0,0 +1,106 @@
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
ALTER TABLE `region_cuboid` DROP FOREIGN KEY `fk_region_cuboid_region` ;
ALTER TABLE `region_flag` DROP FOREIGN KEY `fk_flags_region1` ;
ALTER TABLE `region_groups` DROP FOREIGN KEY `fk_region_groups_region` ;
ALTER TABLE `region_players` DROP FOREIGN KEY `fk_region_players_user` , DROP FOREIGN KEY `fk_region_players_region` ;
ALTER TABLE `region_poly2d` DROP FOREIGN KEY `fk_region_poly2d_region` ;
ALTER TABLE `region_poly2d_point` DROP FOREIGN KEY `fk_region_poly2d_point_region_poly2d` ;
ALTER TABLE `group` COLLATE = utf8_bin ;
ALTER TABLE `region_cuboid` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `min_x` `min_x` BIGINT(20) NOT NULL AFTER `world_id` , CHANGE COLUMN `min_y` `min_y` BIGINT(20) NOT NULL AFTER `min_x` , CHANGE COLUMN `max_x` `max_x` BIGINT(20) NOT NULL AFTER `min_z` , CHANGE COLUMN `max_y` `max_y` BIGINT(20) NOT NULL AFTER `max_x` ,
ADD CONSTRAINT `fk_region_cuboid_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`) ;
ALTER TABLE `region_flag` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `flag` `flag` VARCHAR(45) CHARACTER SET 'utf8' COLLATE 'utf8_bin' NOT NULL ,
ADD CONSTRAINT `fk_flags_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP INDEX `fk_flags_region`
, ADD INDEX `fk_flags_region` (`region_id` ASC, `world_id` ASC) ;
ALTER TABLE `region_groups` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , DROP FOREIGN KEY `fk_region_groups_group` ;
ALTER TABLE `region_groups`
ADD CONSTRAINT `fk_region_groups_group`
FOREIGN KEY (`group_id` )
REFERENCES `group` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT `fk_region_groups_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`, `group_id`) ;
ALTER TABLE `region_players` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` ,
ADD CONSTRAINT `fk_region_users_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT `fk_region_users_user`
FOREIGN KEY (`user_id` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`, `user_id`)
, ADD INDEX `fk_region_users_user` (`user_id` ASC)
, DROP INDEX `fk_region_players_user` ;
ALTER TABLE `region_poly2d` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `min_y` `min_y` INT(11) NOT NULL AFTER `world_id` ,
ADD CONSTRAINT `fk_region_poly2d_region`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region` (`id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP PRIMARY KEY
, ADD PRIMARY KEY (`region_id`, `world_id`) ;
ALTER TABLE `region_poly2d_point` COLLATE = utf8_bin , ADD COLUMN `world_id` INT(10) UNSIGNED NOT NULL AFTER `region_id` , CHANGE COLUMN `x` `x` BIGINT(20) NOT NULL AFTER `world_id` ,
ADD CONSTRAINT `fk_region_poly2d_point_region_poly2d`
FOREIGN KEY (`region_id` , `world_id` )
REFERENCES `region_poly2d` (`region_id` , `world_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
, DROP INDEX `fk_region_poly2d_point_region_poly2d`
, ADD INDEX `fk_region_poly2d_point_region_poly2d` (`region_id` ASC, `world_id` ASC) ;
ALTER TABLE `user` COLLATE = utf8_bin ;
ALTER TABLE `world` COLLATE = utf8_bin ;
UPDATE `region_cuboid` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_flag` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_groups` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_players` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_poly2d` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
UPDATE `region_poly2d_point` AS c SET c.`world_id` = (SELECT p.`world_id` FROM `region` AS p WHERE p.`id` = c.`region_id`);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+1 -1
View File
@@ -3,7 +3,6 @@
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>
@@ -30,6 +29,7 @@
<include>NOTICE.txt</include>
<include>CHANGELOG.txt</include>
<include>blacklist_table.sql</include>
<include>region_storage.sql</include>
</includes>
</fileSet>
</fileSets>
@@ -25,58 +25,58 @@ public abstract class LocalPlayer {
/**
* Get a player's name.
*
* @return
* @return The player's name
*/
public abstract String getName();
/**
* Returns true if the player is inside a group.
*
* @param group
* @return
* @param group The group to check
* @return Whether this player is in {@code group}
*/
public abstract boolean hasGroup(String group);
/**
* Get the player's position.
*
* @return
* @return The player's position
*/
public abstract Vector getPosition();
/**
* Kick the player.
*
* @param msg
* @param msg The message to kick the player with
*/
public abstract void kick(String msg);
/**
* Ban the player.
*
* @param msg
* @param msg The message to ban the player with
*/
public abstract void ban(String msg);
/**
* Send the player a message;
*
* @param msg
* @param msg The message to send to the player
*/
public abstract void printRaw(String msg);
/**
* Get the player's list of groups.
*
* @return
* @return The groups this player is in
*/
public abstract String[] getGroups();
/**
* Returns whether a player has permission.
*
* @param perm
* @return
* @param perm The permission to check
* @return Whether this player has {@code perm}
*/
public abstract boolean hasPermission(String perm);
@@ -73,7 +73,7 @@ public abstract class Blacklist {
/**
* Returns whether the list is empty.
*
* @return
* @return whether the blacklist is empty
*/
public boolean isEmpty() {
return blacklist.isEmpty();
@@ -82,8 +82,8 @@ public abstract class Blacklist {
/**
* Get the entries for an item or list.
*
* @param id
* @return
* @param id The item id to get blacklist information for
* @return The blacklist entries for {@code id}
*/
public List<BlacklistEntry> getEntries(int id) {
return blacklist.get(id);
@@ -92,7 +92,7 @@ public abstract class Blacklist {
/**
* Get the number of individual items that have blacklist entries.
*
* @return
* @return The number of items in the blacklist
*/
public int getItemCount() {
return blacklist.size();
@@ -101,7 +101,7 @@ public abstract class Blacklist {
/**
* Returns whether the blacklist is used as a whitelist.
*
* @return
* @return whether the blacklist is be used as a whitelist
*/
public boolean isWhitelist() {
return useAsWhitelist;
@@ -110,7 +110,7 @@ public abstract class Blacklist {
/**
* Get the logger.
*
* @return
* @return The logger used in this blacklist
*/
public BlacklistLogger getLogger() {
return blacklistLogger;
@@ -119,10 +119,10 @@ public abstract class Blacklist {
/**
* Method to handle the event.
*
* @param event
* @param forceRepeat
* @param silent
* @return
* @param event The event to check
* @param forceRepeat Whether to force quickly repeating notifications
* @param silent Whether to force-deny notifications
* @return Whether the event is allowed
*/
public boolean check(BlacklistEvent event, boolean forceRepeat, boolean silent) {
List<BlacklistEntry> entries = getEntries(event.getType());
@@ -141,8 +141,8 @@ public abstract class Blacklist {
/**
* Load the blacklist.
*
* @param file
* @throws IOException
* @param file The file to load from
* @throws IOException if an error occurred reading from the file
*/
public void load(File file) throws IOException {
FileReader input = null;
@@ -170,7 +170,7 @@ public abstract class Blacklist {
currentEntries = new ArrayList<BlacklistEntry>();
for (String item : items) {
int id = 0;
int id;
try {
id = Integer.parseInt(item.trim());
@@ -248,7 +248,7 @@ public abstract class Blacklist {
if (input != null) {
input.close();
}
} catch (IOException e2) {
} catch (IOException ignore) {
}
}
}
@@ -256,7 +256,7 @@ public abstract class Blacklist {
/**
* Get the last event.
*
* @return
* @return The last event
*/
public BlacklistEvent getLastEvent() {
return lastEvent;
@@ -265,8 +265,8 @@ public abstract class Blacklist {
/**
* Notify administrators.
*
* @param event
* @param comment
* @param event The event to notify about
* @param comment The comment to notify with
*/
public void notify(BlacklistEvent event, String comment) {
lastEvent = event;
@@ -282,14 +282,14 @@ public abstract class Blacklist {
/**
* Sends a notification to all subscribing users.
*
* @param msg
* @param msg The message to broadcast
*/
public abstract void broadcastNotification(String msg);
/**
* Forget a player.
*
* @param player
* @param player The player to forget
*/
public void forgetPlayer(LocalPlayer player) {
lastAffected.remove(player.getName());
@@ -305,7 +305,8 @@ public abstract class Blacklist {
/**
* Get an item's ID from its name.
*
* @param name
* @param name the name of the item to look up
* @return the id for name if contained in ItemId, else -1
*/
private static int getItemID(String name) {
ItemType type = ItemType.lookup(name);
@@ -319,7 +320,8 @@ public abstract class Blacklist {
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The id to look up
* @return The item's friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -69,7 +69,7 @@ public class BlacklistEntry {
/**
* Construct the object.
*
* @param blacklist
* @param blacklist The blacklist that contains this entry
*/
public BlacklistEntry(Blacklist blacklist) {
this.blacklist = blacklist;
@@ -112,98 +112,98 @@ public class BlacklistEntry {
}
/**
* @return
* @return The actions that occur when breaking
*/
public String[] getBreakActions() {
return breakActions;
}
/**
* @param actions
* @param actions The actions to occur when breaking
*/
public void setBreakActions(String[] actions) {
this.breakActions = actions;
}
/**
* @return
* @return The actions that occur when destroying with a specific item
*/
public String[] getDestroyWithActions() {
return destroyWithActions;
}
/**
* @param actions
* @param actions The actions to occur when destroying with an item
*/
public void setDestroyWithActions(String[] actions) {
this.destroyWithActions = actions;
}
/**
* @return
* @return The actions that will occur when placing
*/
public String[] getPlaceActions() {
return placeActions;
}
/**
* @param actions
* @param actions The actions to occur when placing
*/
public void setPlaceActions(String[] actions) {
this.placeActions = actions;
}
/**
* @return
* @return The actions that will occur when interacting
*/
public String[] getInteractActions() {
return interactActions;
}
/**
* @param actions
* @param actions The actions to occur when interacting
*/
public void setInteractActions(String[] actions) {
this.interactActions = actions;
}
/**
* @return
* @return The actions that will occur when using
*/
public String[] getUseActions() {
return useActions;
}
/**
* @param actions
* @param actions The actions to occur when using
*/
public void setUseActions(String[] actions) {
this.useActions = actions;
}
/**
* @return
* @return The actions that will occur when dropping
*/
public String[] getDropActions() {
return dropActions;
}
/**
* @param actions
* @param actions The actions to occur when dropping
*/
public void setDropActions(String[] actions) {
this.dropActions = actions;
}
/**
* @return
* @return The actions that will occur when acquiring
*/
public String[] getAcquireActions() {
return acquireActions;
}
/**
* @param actions
* @param actions The actions to occur when acquiring
*/
public void setAcquireActions(String[] actions) {
this.acquireActions = actions;
@@ -240,8 +240,8 @@ public class BlacklistEntry {
/**
* Returns true if this player should be ignored.
*
* @param player
* @return
* @param player The player to check
* @return whether this player should be ignored for blacklist blocking
*/
public boolean shouldIgnore(LocalPlayer player) {
if (ignoreGroups != null) {
@@ -266,8 +266,8 @@ public class BlacklistEntry {
/**
* Get the associated actions with an event.
*
* @param event
* @return
* @param event The event to check
* @return The actions for the given event
*/
private String[] getActions(BlacklistEvent event) {
if (event instanceof BlockBreakBlacklistEvent) {
@@ -299,11 +299,11 @@ public class BlacklistEntry {
/**
* Method to handle the event.
*
* @param useAsWhitelist
* @param event
* @param forceRepeat
* @param silent
* @return
* @param useAsWhitelist Whether this entry is buing used in a whitelist
* @param event The event to check
* @param forceRepeat Whether to force repeating notifications even within the delay limit
* @param silent Whether to prevent notifications from happening
* @return Whether the action was allowed
*/
public boolean check(boolean useAsWhitelist, BlacklistEvent event, boolean forceRepeat, boolean silent) {
LocalPlayer player = event.getPlayer();
@@ -329,11 +329,11 @@ public class BlacklistEntry {
String actions[] = getActions(event);
boolean ret = useAsWhitelist ? false : true;
boolean ret = !useAsWhitelist;
// Nothing to do
if (actions == null) {
return useAsWhitelist ? false : true;
return ret;
}
for (String action : actions) {
@@ -412,7 +412,7 @@ public class BlacklistEntry {
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The id to get a name for
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -39,16 +39,16 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Add a handler.
*
* @param handler
* @param handler The handler to add
*/
public void addHandler(BlacklistLoggerHandler handler) {
handlers.add(handler);
}
/**
* Add a handler.
* Remove a handler.
*
* @param handler
* @param handler The handler to remove
*/
public void removeHandler(BlacklistLoggerHandler handler) {
handlers.remove(handler);
@@ -64,7 +64,7 @@ public class BlacklistLogger implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
for (BlacklistLoggerHandler handler : handlers) {
@@ -32,8 +32,8 @@ public class BlacklistTrackedEvent {
/**
* Construct the object.
*
* @param event
* @param time
* @param event The event tracked
* @param time The time at which the event occurred
*/
public BlacklistTrackedEvent(BlacklistEvent event, long time) {
this.event = event;
@@ -39,9 +39,9 @@ public abstract class BlacklistEvent {
/**
* Construct the object.
*
* @param player
* @param pos
* @param type
* @param player The player associated with this event
* @param pos The position the event occurred at
* @param type The type of item used
*/
public BlacklistEvent(LocalPlayer player, Vector pos, int type) {
this.player = player;
@@ -51,8 +51,8 @@ public abstract class BlacklistEvent {
/**
* Get the player.
*
* @return
*
* @return The player associated with this event
*/
public LocalPlayer getPlayer() {
return player;
@@ -61,16 +61,16 @@ public abstract class BlacklistEvent {
/**
* Get the position.
*
* @return
* @return The position of this event
*/
public Vector getPosition() {
return pos;
}
/**
* Get the type.
* Get the item type.
*
* @return
* @return The type associated with this event
*/
public int getType() {
return type;
@@ -79,7 +79,7 @@ public abstract class BlacklistEvent {
/**
* Get a short description such as "break" or "destroy with."
*
* @return
* @return The event description
*/
public abstract String getDescription();
}
@@ -26,12 +26,7 @@ public class BlockBreakBlacklistEvent extends BlockBlacklistEvent {
public BlockBreakBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "break";
@@ -26,12 +26,7 @@ public class BlockInteractBlacklistEvent extends BlockBlacklistEvent {
public BlockInteractBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "interact with";
@@ -26,12 +26,7 @@ public class BlockPlaceBlacklistEvent extends BlockBlacklistEvent {
public BlockPlaceBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "place";
@@ -26,12 +26,7 @@ public class DestroyWithBlacklistEvent extends BlacklistEvent {
public DestroyWithBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "destroy with";
@@ -26,12 +26,7 @@ public class ItemAcquireBlacklistEvent extends ItemBlacklistEvent {
public ItemAcquireBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "acquire";
@@ -26,12 +26,7 @@ public class ItemDropBlacklistEvent extends ItemBlacklistEvent {
public ItemDropBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "drop";
@@ -26,12 +26,7 @@ public class ItemUseBlacklistEvent extends ItemBlacklistEvent {
public ItemUseBlacklistEvent(LocalPlayer player, Vector pos, int type) {
super(player, pos, type);
}
/**
* Get a short description such as "break" or "destroy with."
*
* @return
*/
@Override
public String getDescription() {
return "use";
@@ -48,11 +48,6 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
this.logger = logger;
}
/**
* Log an event.
*
* @param event
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
@@ -113,14 +108,15 @@ public class ConsoleLoggerHandler implements BlacklistLoggerHandler {
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The item id
* @return The friendly name of the item
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
if (type != null) {
return type.getName() + " (#" + id + ")";
} else {
return "#" + id + "";
return "#" + id;
}
}
@@ -73,11 +73,12 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Construct the object.
*
* @param dsn
* @param user
* @param pass
* @param table
* @param worldName
* @param dsn The DSN for the connection
* @param user The username to connect with
* @param pass The password to connect with
* @param table The table to log to
* @param worldName The name of the world to log
* @param logger The logger to log errors to
*/
public DatabaseLoggerHandler(String dsn, String user, String pass, String table, String worldName, Logger logger) {
this.dsn = dsn;
@@ -91,8 +92,8 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Gets the database connection.
*
* @return
* @throws SQLException
* @return The database connection
* @throws SQLException when the connection cannot be created
*/
private Connection getConnection() throws SQLException {
if (conn == null || conn.isClosed()) {
@@ -104,11 +105,11 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event to the database.
*
* @param event
* @param player
* @param pos
* @param item
* @param comment
* @param event The event to log
* @param player The player associated with the event
* @param pos The location of the event
* @param item The item used
* @param comment The comment associated with the event
*/
private void logEvent(String event, LocalPlayer player, Vector pos, int item,
String comment) {
@@ -137,7 +138,7 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
@@ -197,7 +198,7 @@ public class DatabaseLoggerHandler implements BlacklistLoggerHandler {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
} catch (SQLException ignore) {
}
}
@@ -39,13 +39,6 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.blacklist.events.BlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockInteractBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.BlockPlaceBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.DestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemAcquireBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
/**
*
@@ -85,8 +78,9 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Construct the object.
*
* @param pathPattern
* @param worldName
* @param pathPattern The pattern for the logflie path
* @param worldName The name of the world
* @param logger The logger used to log errors
*/
public FileLoggerHandler(String pathPattern, String worldName, Logger logger) {
this.pathPattern = pathPattern;
@@ -97,9 +91,10 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Construct the object.
*
* @param pathPattern
* @param cacheSize
* @param worldName
* @param pathPattern The pattern for logfile paths
* @param cacheSize The size of the file cache
* @param worldName The name of the associated world
* @param logger The logger to log errors with
*/
public FileLoggerHandler(String pathPattern, int cacheSize, String worldName, Logger logger) {
if (cacheSize < 1) {
@@ -114,7 +109,8 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Build the path.
*
* @return
* @param playerName The name of the playername
* @return The path for the logfile
*/
private String buildPath(String playerName) {
GregorianCalendar calendar = new GregorianCalendar();
@@ -171,8 +167,9 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Log a message.
*
* @param player
* @param message
* @param player The player to log
* @param message The message to log
* @param comment The comment associated with the logged event
*/
private void log(LocalPlayer player, String message, String comment) {
String path = buildPath(player.getName());
@@ -220,7 +217,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
Map.Entry<String,FileLoggerWriter> entry = it.next();
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
it.remove();
@@ -240,8 +237,8 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Gets the coordinates in text form for the log.
*
* @param pos
* @return
* @param pos The position to get coordinates for
* @return The position's coordinates in human-readable form
*/
private String getCoordinates(Vector pos) {
return "@" + pos.getBlockX() + "," + pos.getBlockY() + "," + pos.getBlockZ();
@@ -255,55 +252,17 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
/**
* Log an event.
*
* @param event
* @param event The event to log
*/
public void logEvent(BlacklistEvent event, String comment) {
// Block break
if (event instanceof BlockBreakBlacklistEvent) {
BlockBreakBlacklistEvent evt = (BlockBreakBlacklistEvent)event;
logEvent(event, "break", evt.getType(), evt.getPosition(), comment);
// Block place
} else if (event instanceof BlockPlaceBlacklistEvent) {
BlockPlaceBlacklistEvent evt = (BlockPlaceBlacklistEvent)event;
logEvent(event, "place", evt.getType(), evt.getPosition(), comment);
// Block interact
} else if (event instanceof BlockInteractBlacklistEvent) {
BlockInteractBlacklistEvent evt = (BlockInteractBlacklistEvent)event;
logEvent(event, "interact with", evt.getType(), evt.getPosition(), comment);
// Destroy with
} else if (event instanceof DestroyWithBlacklistEvent) {
DestroyWithBlacklistEvent evt = (DestroyWithBlacklistEvent)event;
logEvent(event, "destroy with", evt.getType(), evt.getPosition(), comment);
// Acquire
} else if (event instanceof ItemAcquireBlacklistEvent) {
ItemAcquireBlacklistEvent evt = (ItemAcquireBlacklistEvent)event;
logEvent(event, "acquire", evt.getType(), evt.getPosition(), comment);
// Drop
} else if (event instanceof ItemDropBlacklistEvent) {
ItemDropBlacklistEvent evt = (ItemDropBlacklistEvent)event;
logEvent(event, "drop", evt.getType(), evt.getPosition(), comment);
// Use
} else if (event instanceof ItemUseBlacklistEvent) {
ItemUseBlacklistEvent evt = (ItemUseBlacklistEvent)event;
logEvent(event, "use", evt.getType(), evt.getPosition(), comment);
// Unknown
} else {
log(event.getPlayer(), "Unknown event: "
+ event.getClass().getCanonicalName(), comment);
}
logEvent(event, event.getDescription(), event.getType(), event.getPosition(), comment);
}
/**
* Get an item's friendly name with its ID.
*
* @param id
* @param id The id to get a friendly name for
* @return The friendly name
*/
private static String getFriendlyItemName(int id) {
ItemType type = ItemType.fromID(id);
@@ -321,7 +280,7 @@ public class FileLoggerHandler implements BlacklistLoggerHandler {
for (Map.Entry<String,FileLoggerWriter> entry : writers.entrySet()) {
try {
entry.getValue().getWriter().close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
@@ -42,8 +42,8 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* Construct the object.
*
* @param path
* @param writer
* @param path The path to write to
* @param writer The writer for the file
*/
public FileLoggerWriter(String path, BufferedWriter writer) {
this.path = path;
@@ -54,14 +54,14 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
/**
* File path.
*
* @return
* @return The path the logger is logging to
*/
public String getPath() {
return path;
}
/**
* @return the writer
* @return the writer being logged to
*/
public BufferedWriter getWriter() {
return writer;
@@ -81,12 +81,6 @@ public class FileLoggerWriter implements Comparable<FileLoggerWriter> {
lastUse = System.currentTimeMillis();
}
/**
* Comparison function.
*
* @param other
* @return
*/
public int compareTo(FileLoggerWriter other) {
if (lastUse > other.lastUse) {
return 1;
@@ -57,6 +57,7 @@ public class BukkitPlayer extends LocalPlayer {
@Override
public void ban(String msg) {
player.setBanned(true);
player.kickPlayer(msg);
}
@@ -35,6 +35,8 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.FallingSand;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.BlockVector;
@@ -44,34 +46,34 @@ import com.sk89q.worldedit.blocks.BlockType;
public class BukkitUtil {
private BukkitUtil() {
}
/**
* Converts the location of a Bukkit block to a WorldEdit vector.
*
* @param block
* @return
*
* @param block The block to convert
* @return The block's location as a BlockVector
*/
public static BlockVector toVector(Block block) {
return new BlockVector(block.getX(), block.getY(), block.getZ());
}
/**
* Converts a Bukkit location to a WorldEdit vector.
*
* @param loc
* @return
*
* @param loc A Bukkit Location
* @return A Vector with the location's x, y, and z values
*/
public static Vector toVector(Location loc) {
return new Vector(loc.getX(), loc.getY(), loc.getZ());
}
/**
* Converts a Bukkit vector to a WorldEdit vector.
*
* @param vector
* @return
*
* @param vector The Bukkit vector
* @return A WorldEdit vector with the same values as the Bukkit vector.
*/
public static Vector toVector(org.bukkit.util.Vector vector) {
return new Vector(vector.getX(), vector.getY(), vector.getZ());
@@ -79,22 +81,24 @@ public class BukkitUtil {
/**
* Converts a WorldEdit vector to a Bukkit location.
*
* @param world
* @param vec
* @return
*
* @param world The World to create the new Location with
* @param vec The vector to use for coordinates
* @return The Vector as a location with a World of world
*/
public static Location toLocation(World world, Vector vec) {
return new Location(world, vec.getX(), vec.getY(), vec.getZ());
}
/**
* Matches one player based on name.
*
* @param server
* @param name
* @return
*
* @param server The server to check
* @param name The name to attempt to match
* @deprecated see {@link WorldGuardPlugin#matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @return The matched player if any, otherwise null
*/
@Deprecated
public static Player matchSinglePlayer(Server server, String name) {
List<Player> players = server.matchPlayer(name);
if (players.size() == 0) {
@@ -102,12 +106,14 @@ public class BukkitUtil {
}
return players.get(0);
}
/**
* Drops a sign item and removes a sign.
*
* @param block
*
* @param block The block
* @deprecated see {@link org.bukkit.block.Block#breakNaturally()}
*/
@Deprecated
public static void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
@@ -117,7 +123,7 @@ public class BukkitUtil {
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
*
* @param world
* @param ox
* @param oy
@@ -133,12 +139,12 @@ public class BukkitUtil {
/**
* Checks if the given block is water
*
*
* @param world
* @param ox
* @param oy
* @param oz
* @return
* @return
*/
public static boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
@@ -168,7 +174,7 @@ public class BukkitUtil {
byte free = 0;
while (y <= 129) {
while (y <= world.getMaxHeight() + 1) {
if (BlockType.canPassThrough(world.getBlockTypeIdAt(x, y, z))) {
free++;
} else {
@@ -242,8 +248,9 @@ public class BukkitUtil {
return entity instanceof Item
|| entity instanceof TNTPrimed
|| entity instanceof ExperienceOrb
|| entity instanceof FallingSand
|| (entity instanceof LivingEntity
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
&& !(entity instanceof Tameable)
&& !(entity instanceof Player));
}
}
@@ -90,15 +90,15 @@ public class ConfigurationManager {
* List of people who can breathe underwater.
*/
private Set<String> hasAmphibious = new HashSet<String>();
private boolean hasCommandBookGodMode = false;
public boolean suppressTickSyncWarnings;
public boolean useRegionsScheduler;
public boolean activityHaltToggle = false;
public boolean autoGodMode;
public boolean usePlayerMove;
public Map<String, String> hostKeys = new HashMap<String, String>();
/**
* Region Storage Configuration method, and config values
*/
@@ -110,7 +110,7 @@ public class ConfigurationManager {
/**
* Construct the object.
*
* @param plugin
* @param plugin The plugin instance
*/
public ConfigurationManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -120,6 +120,7 @@ public class ConfigurationManager {
/**
* Load the configuration.
*/
@SuppressWarnings("unchecked")
public void load() {
// Create the default configuration file
plugin.createDefaultConfiguration(
@@ -133,14 +134,26 @@ public class ConfigurationManager {
e.printStackTrace();
}
suppressTickSyncWarnings = config.getBoolean(
"suppress-tick-sync-warnings", false);
config.removeProperty("suppress-tick-sync-warnings");
useRegionsScheduler = config.getBoolean(
"regions.use-scheduler", true);
autoGodMode = config.getBoolean(
"auto-invincible", config.getBoolean("auto-invincible-permission", true));
"auto-invincible", config.getBoolean("auto-invincible-permission", false));
config.removeProperty("auto-invincible-permission");
usePlayerMove = config.getBoolean(
"use-player-move-event", true);
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);
@@ -154,10 +167,7 @@ public class ConfigurationManager {
get(world);
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
if (!config.save()) {
plugin.getLogger().severe("Error saving configuration!");
@@ -174,8 +184,8 @@ public class ConfigurationManager {
/**
* Get the configuration for a world.
*
* @param world
* @return
* @param world The world to get the configuration for
* @return {@code world}'s configuration
*/
public WorldConfiguration get(World world) {
String worldName = world.getName();
@@ -192,7 +202,7 @@ public class ConfigurationManager {
/**
* Forget a player.
*
* @param player
* @param player The player to forget about
*/
public void forgetPlayer(LocalPlayer player) {
for (Map.Entry<String, WorldConfiguration> entry
@@ -212,17 +222,18 @@ public class ConfigurationManager {
/**
* Enable god mode for a player.
*
* @param player
* @param player The player to enable god mode for.
*/
@Deprecated
public void enableGodMode(Player player) {
hasGodMode.add(player.getName());
}
/**
* Disable god mode for a player.
*
* @param player
* @param player The player to disable godmode for
*/
@Deprecated
public void disableGodMode(Player player) {
@@ -232,8 +243,8 @@ public class ConfigurationManager {
/**
* Check to see if god mode is enabled for a player.
*
* @param player
* @return
* @param player The player to check
* @return Whether the player has godmode through WorldGuard or CommandBook
*/
public boolean hasGodMode(Player player) {
if (hasCommandBookGodMode) {
@@ -248,7 +259,7 @@ public class ConfigurationManager {
/**
* Enable amphibious mode for a player.
*
* @param player
* @param player The player to enable amphibious mode for
*/
public void enableAmphibiousMode(Player player) {
hasAmphibious.add(player.getName());
@@ -257,22 +268,22 @@ public class ConfigurationManager {
/**
* Disable amphibious mode for a player.
*
* @param player
* @param player The player to disable amphibious mode for
*/
public void disableAmphibiousMode(Player player) {
hasAmphibious.remove(player.getName());
}
/**
* Check to see if amphibious mode is enabled for a player.
* Check to see if amphibious mode is enabled for a player.
*
* @param player
* @return
* @param player The player to check
* @return Whether {@code player} has amphibious mode
*/
public boolean hasAmphibiousMode(Player player) {
return hasAmphibious.contains(player.getName());
}
public void updateCommandBookGodMode() {
try {
if (plugin.getServer().getPluginManager().isPluginEnabled("CommandBook")) {
@@ -283,7 +294,7 @@ public class ConfigurationManager {
} catch (ClassNotFoundException ignore) {}
hasCommandBookGodMode = false;
}
public boolean hasCommandBookGodMode() {
return hasCommandBookGodMode;
}
@@ -36,24 +36,24 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* This processes per-player state information and is also meant to be used
* as a scheduled task.
*
*
* @author sk89q
*/
public class FlagStateManager implements Runnable {
public static final int RUN_DELAY = 20;
private WorldGuardPlugin plugin;
private Map<String, PlayerFlagState> states;
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public FlagStateManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
states = new HashMap<String, PlayerFlagState>();
}
@@ -66,16 +66,16 @@ public class FlagStateManager implements Runnable {
for (Player player : players) {
WorldConfiguration worldConfig = config.get(player.getWorld());
if (!worldConfig.useRegions) {
continue;
}
PlayerFlagState state;
synchronized (this) {
state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
@@ -87,7 +87,7 @@ public class FlagStateManager implements Runnable {
.get(player.getWorld());
ApplicableRegionSet applicable = regionManager
.getApplicableRegions(playerLocation);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
&& !(player.getGameMode() == GameMode.CREATIVE)) {
@@ -96,28 +96,28 @@ public class FlagStateManager implements Runnable {
}
}
}
/**
* Process healing for a player.
*
* @param applicable
* @param player
* @param state
*
* @param applicable The set of applicable regions
* @param player The player to process healing flags on
* @param state The player's state
*/
private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
@@ -127,7 +127,7 @@ public class FlagStateManager implements Runnable {
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
@@ -137,13 +137,13 @@ public class FlagStateManager implements Runnable {
state.lastHeal = now;
}
}
/**
* Process restoring hunger for a player.
*
* @param applicable
* @param player
* @param state
*
* @param applicable The set of applicable regions
* @param player The player to process hunger flags on
* @param state The player's state
*/
private void processFeed(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
@@ -154,7 +154,7 @@ public class FlagStateManager implements Runnable {
Integer feedDelay = applicable.getFlag(DefaultFlag.FEED_DELAY);
Integer minHunger = applicable.getFlag(DefaultFlag.MIN_FOOD);
Integer maxHunger = applicable.getFlag(DefaultFlag.MAX_FOOD);
if (feedAmount == null || feedDelay == null || feedAmount == 0 || feedDelay < 0) {
return;
}
@@ -177,8 +177,8 @@ public class FlagStateManager implements Runnable {
/**
* Forget a player.
*
* @param player
*
* @param player The player to forget
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
@@ -192,22 +192,23 @@ public class FlagStateManager implements Runnable {
}
/**
* Get a player's flag state.
*
* @param player
* @return
* Get a player's flag state. A new state will be created if there is no existing
* state for the player.
*
* @param player The player to get a state for
* @return The {@code player}'s state
*/
public synchronized PlayerFlagState getState(Player player) {
PlayerFlagState state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
return state;
}
/**
* Keeps state per player.
*/
@@ -219,6 +220,7 @@ public class FlagStateManager implements Runnable {
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public GameMode lastGameMode;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
@@ -26,8 +26,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import org.bukkit.World;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
@@ -44,7 +42,7 @@ public class LegacyWorldGuardMigration {
/**
* Port over the blacklist.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateBlacklist(WorldGuardPlugin plugin) {
World mainWorld = plugin.getServer().getWorlds().get(0);
@@ -77,7 +75,7 @@ public class LegacyWorldGuardMigration {
/**
* Migrate region settings.
*
* @param plugin
* @param plugin The plugin instance
*/
public static void migrateRegions(WorldGuardPlugin plugin) {
try {
@@ -111,8 +109,8 @@ public class LegacyWorldGuardMigration {
/**
* Copies a file.
*
* @param from
* @param to
* @param from The source file
* @param to The destination file
* @return true if successful
*/
private static boolean copyFile(File from, File to) {
@@ -133,20 +131,20 @@ public class LegacyWorldGuardMigration {
out.close();
return true;
} catch (FileNotFoundException ex) {
} catch (IOException e) {
} catch (FileNotFoundException ignore) {
} catch (IOException ignore) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
@@ -19,8 +19,6 @@
package com.sk89q.worldguard.bukkit;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.GodComponent;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
@@ -61,7 +59,7 @@ public class RegionQueryUtil {
set = mgr.getApplicableRegions(vec);
}
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY);
state.wasInvincible = set.allows(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
}
return state.wasInvincible;
@@ -73,7 +71,7 @@ public class RegionQueryUtil {
Vector vec = new Vector(state.lastInvincibleX, state.lastInvincibleY, state.lastInvincibleZ);
StateFlag.State regionState = plugin.getGlobalRegionManager().get(world).
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY);
getApplicableRegions(vec).getFlag(DefaultFlag.INVINCIBILITY, plugin.wrapPlayer(player));
if (regionState == StateFlag.State.ALLOW) {
return Boolean.TRUE;
} else if (regionState == StateFlag.State.DENY) {
@@ -127,7 +127,7 @@ public class ReportWriter {
configLog.put(field.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -274,7 +274,7 @@ public class ReportWriter {
configLog.put(field.getName(), String.valueOf(val));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException ignore) {
}
}
@@ -324,7 +324,7 @@ public class ReportWriter {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
@@ -28,12 +28,12 @@ public class SpongeUtil {
/**
* Remove water around a sponge.
*
* @param plugin
* @param world
* @param ox
* @param oy
* @param oz
*
* @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();
@@ -53,11 +53,11 @@ public class SpongeUtil {
/**
* Add water around a sponge.
*
* @param plugin
* @param world
* @param ox
* @param oy
* @param oz
* @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();
@@ -29,12 +29,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import org.bukkit.block.Block;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import com.sk89q.worldguard.blacklist.Blacklist;
@@ -69,7 +67,6 @@ public class WorldConfiguration {
private String worldName;
private YAMLProcessor parentConfig;
private YAMLProcessor config;
private File configFile;
private File blacklistFile;
private Blacklist blacklist;
@@ -100,6 +97,8 @@ public class WorldConfiguration {
public boolean blockEnderDragonBlockDamage;
public boolean blockFireballExplosions;
public boolean blockFireballBlockDamage;
public boolean blockEntityPaintingDestroy;
public boolean blockPluginSpawning;
public boolean disableContactDamage;
public boolean disableFallDamage;
public boolean disableLavaDamage;
@@ -115,7 +114,7 @@ public class WorldConfiguration {
public boolean useRegions;
public boolean highFreqFlags;
public int regionWand = 287;
public Set<CreatureType> blockCreatureSpawn;
public Set<EntityType> blockCreatureSpawn;
// public boolean useiConomy;
// public boolean buyOnClaim;
// public double buyOnClaimPrice;
@@ -124,6 +123,7 @@ public class WorldConfiguration {
public int maxRegionCountPerPlayer;
public boolean antiWolfDumbness;
public boolean signChestProtection;
public boolean disableSignChestProtectionCheck;
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
@@ -147,7 +147,7 @@ public class WorldConfiguration {
public boolean regionInvinciblityRemovesMobs;
public boolean disableDeathMessages;
public boolean disableObsidianGenerators;
private Map<String, Integer> maxRegionCounts;
/* Configuration data end */
@@ -161,7 +161,7 @@ public class WorldConfiguration {
*/
public WorldConfiguration(WorldGuardPlugin plugin, String worldName, YAMLProcessor parentConfig) {
File baseFolder = new File(plugin.getDataFolder(), "worlds/" + worldName);
configFile = new File(baseFolder, "config.yml");
File configFile = new File(baseFolder, "config.yml");
blacklistFile = new File(baseFolder, "blacklist.txt");
this.plugin = plugin;
@@ -171,10 +171,10 @@ public class WorldConfiguration {
plugin.createDefaultConfiguration(configFile, "config_world.yml");
plugin.createDefaultConfiguration(blacklistFile, "blacklist.txt");
config = new YAMLProcessor(this.configFile, true, YAMLFormat.EXTENDED);
config = new YAMLProcessor(configFile, true, YAMLFormat.EXTENDED);
loadConfiguration();
plugin.getLogger().info("Loaded configuration for world '" + worldName + '"');
plugin.getLogger().info("Loaded configuration for world '" + worldName + "'");
}
private boolean getBoolean(String node, boolean def) {
@@ -315,6 +315,8 @@ public class WorldConfiguration {
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);
blockPluginSpawning = getBoolean("mobs.block-plugin-spawning", true);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -331,6 +333,7 @@ public class WorldConfiguration {
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);
@@ -358,11 +361,11 @@ public class WorldConfiguration {
regionWand = getInt("regions.wand", 287);
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);
maxRegionCounts = new HashMap<String, Integer>();
maxRegionCounts.put(null, maxRegionCountPerPlayer);
for (String key : getKeys("regions.max-region-count-per-player")) {
if (!key.equalsIgnoreCase("default")) {
Object val = getProperty("regions.max-region-count-per-player." + key);
@@ -376,12 +379,14 @@ public class WorldConfiguration {
// buyOnClaim = getBoolean("iconomy.buy-on-claim", false);
// buyOnClaimPrice = getDouble("iconomy.buy-on-claim-price", 1.0);
blockCreatureSpawn = new HashSet<CreatureType>();
blockCreatureSpawn = new HashSet<EntityType>();
for (String creatureName : getStringList("mobs.block-creature-spawn", null)) {
CreatureType creature = CreatureType.fromName(creatureName);
EntityType creature = EntityType.fromName(creatureName);
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);
}
@@ -472,10 +477,7 @@ public class WorldConfiguration {
}
}
try {
config.setHeader(CONFIG_HEADER);
} catch (Throwable t) {
}
config.setHeader(CONFIG_HEADER);
config.save();
}
@@ -531,7 +533,7 @@ public class WorldConfiguration {
public ChestProtection getChestProtection() {
return chestProtection;
}
public int getMaxRegionCount(Player player) {
int max = -1;
for (String group : plugin.getGroups(player)) {
@@ -18,12 +18,10 @@
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.dropSign;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
@@ -61,7 +59,7 @@ import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* The listener for block events.
*
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
@@ -70,8 +68,8 @@ public class WorldGuardBlockListener implements Listener {
/**
* Construct the object.
*
* @param plugin
*
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -86,9 +84,9 @@ public class WorldGuardBlockListener implements Listener {
/**
* Get the world configuration given a world.
*
* @param world
* @return
*
* @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);
@@ -96,23 +94,19 @@ public class WorldGuardBlockListener implements Listener {
/**
* Get the world configuration given a player.
*
* @param player
* @return
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected WorldConfiguration getWorldConfig(Player player) {
return plugin.getGlobalStateManager().get(player.getWorld());
return getWorldConfig(player.getWorld());
}
/**
/*
* Called when a block is damaged.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Block blockDamaged = event.getBlock();
@@ -126,16 +120,12 @@ public class WorldGuardBlockListener implements Listener {
}
}
}
/**
/*
* Called when a block is broken.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
@@ -149,7 +139,8 @@ public class WorldGuardBlockListener implements Listener {
}
}
if (!plugin.getGlobalRegionManager().canBuild(player, event.getBlock())) {
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.");
event.setCancelled(true);
return;
@@ -172,7 +163,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
if (wcfg.isChestProtected(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setCancelled(true);
@@ -180,15 +171,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when fluids flow.
*/
@EventHandler
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
if (event.isCancelled()) {
return;
}
World world = event.getBlock().getWorld();
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
@@ -239,7 +226,7 @@ public class WorldGuardBlockListener implements Listener {
// 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);
@@ -249,7 +236,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.allowedLavaSpreadOver.size() > 0 && isLava) {
int targetId = blockTo.getRelative(0, -1, 0).getTypeId();
if (!wcfg.allowedLavaSpreadOver.contains(targetId)) {
event.setCancelled(true);
return;
@@ -277,15 +264,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block gets ignited.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.isCancelled()) {
return;
}
IgniteCause cause = event.getCause();
Block block = event.getBlock();
World world = block.getWorld();
@@ -297,7 +280,6 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
@@ -315,7 +297,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (wcfg.blockLighter && cause == IgniteCause.FLINT_AND_STEEL
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
@@ -356,7 +338,7 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
if (!set.allows(DefaultFlag.LIGHTER)
if (!set.allows(DefaultFlag.LIGHTER, localPlayer)
&& !plugin.hasPermission(player, "worldguard.override.lighter")) {
event.setCancelled(true);
return;
@@ -375,20 +357,19 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
}
if (cause == IgniteCause.LIGHTNING && !set.allows(DefaultFlag.LIGHTNING)) {
event.setCancelled(true);
return;
}
}
}
/**
/*
* Called when a block is destroyed from burning.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -403,7 +384,9 @@ public class WorldGuardBlockListener implements Listener {
}
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
@@ -412,6 +395,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.disableFireSpreadBlocks.contains(block.getTypeId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), BlockID.FIRE);
return;
}
}
@@ -420,14 +404,18 @@ public class WorldGuardBlockListener implements Listener {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Block block = event.getBlock();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
Vector pt = toVector(block);
RegionManager mgr = plugin.getGlobalRegionManager().get(block.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, BlockID.FIRE);
event.setCancelled(true);
return;
}
@@ -435,16 +423,26 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
private void checkAndDestroyAround(World world, int x, int y, int z, int required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
}
private void checkAndDestroy(World world, int x, int y, int z, int required) {
if (world.getBlockTypeIdAt(x, y, z) == required) {
world.getBlockAt(x, y, z).setTypeId(BlockID.AIR);
}
}
/*
* Called when block physics occurs.
*/
@EventHandler
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -471,16 +469,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a player places a block.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block blockPlaced = event.getBlock();
Player player = event.getPlayer();
World world = blockPlaced.getWorld();
@@ -489,7 +482,9 @@ public class WorldGuardBlockListener implements Listener {
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, blockPlaced.getLocation())) {
final Location location = blockPlaced.getLocation();
if (!plugin.getGlobalRegionManager().canBuild(player, location)
|| !plugin.getGlobalRegionManager().canConstruct(player, location)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
@@ -504,7 +499,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
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.");
@@ -526,12 +521,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when redstone changes.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
Block blockTo = event.getBlock();
World world = blockTo.getWorld();
@@ -562,29 +556,28 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a sign is changed.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
if (wcfg.signChestProtection) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
if (wcfg.isChestProtectedPlacement(event.getBlock(), player)) {
player.sendMessage(ChatColor.DARK_RED + "You do not own the adjacent chest.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
if (event.getBlock().getTypeId() != BlockID.SIGN_POST) {
player.sendMessage(ChatColor.RED
+ "The [Lock] sign must be a sign post, not a wall sign.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
@@ -593,11 +586,11 @@ public class WorldGuardBlockListener implements Listener {
player.sendMessage(ChatColor.RED
+ "The first owner line must be your name.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
int below = event.getBlock().getRelative(0, -1, 0).getTypeId();
if (below == BlockID.TNT || below == BlockID.SAND
@@ -605,21 +598,21 @@ public class WorldGuardBlockListener implements Listener {
player.sendMessage(ChatColor.RED
+ "That is not a safe block that you're putting this sign on.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
event.setLine(0, "[Lock]");
player.sendMessage(ChatColor.YELLOW
+ "A chest or double chest above is now protected.");
}
} else {
} else if (!wcfg.disableSignChestProtectionCheck) {
if (event.getLine(0).equalsIgnoreCase("[Lock]")) {
player.sendMessage(ChatColor.RED
+ "WorldGuard's sign chest protection is disabled.");
dropSign(event.getBlock());
event.getBlock().breakNaturally();
event.setCancelled(true);
return;
}
@@ -632,12 +625,8 @@ public class WorldGuardBlockListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -659,15 +648,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block is formed based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -703,15 +688,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block spreads based on world conditions.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -747,14 +728,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a block fades.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -786,15 +764,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a piston extends
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -812,15 +786,11 @@ public class WorldGuardBlockListener implements Listener {
}
}
/**
/*
* Called when a piston retracts
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getBlock().getWorld());
@@ -828,6 +798,7 @@ public class WorldGuardBlockListener implements Listener {
if (!(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getRetractLocation()))
|| !(plugin.getGlobalRegionManager().allows(DefaultFlag.PISTONS, event.getBlock().getLocation()))) {
event.setCancelled(true);
return;
}
}
}
@@ -0,0 +1,75 @@
/*
* WorldGuard
* Copyright (C) 2012 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 com.sk89q.commandbook.InfoComponent;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
/**
* @author zml2008
*/
public class WorldGuardCommandBookListener implements Listener {
private final WorldGuardPlugin plugin;
public WorldGuardCommandBookListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onPlayerWhois(InfoComponent.PlayerWhoisEvent event) {
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (plugin.getGlobalStateManager().get(player.getWorld()).useRegions) {
ApplicableRegionSet regions = plugin.getGlobalRegionManager()
.get(player.getWorld()).getApplicableRegions(player.getLocation());
// Current regions
StringBuilder regionStr = new StringBuilder();
boolean first = true;
for (ProtectedRegion region : regions) {
if (!first) {
regionStr.append(", ");
}
if (region.isOwner(localPlayer)) {
regionStr.append("+");
} else if (region.isMemberOnly(localPlayer)) {
regionStr.append("-");
}
regionStr.append(region.getId());
first = false;
}
if (regions.size() > 0) {
event.addWhoisInformation("Current Regions", regionStr);
}
event.addWhoisInformation("Can build", regions.canBuild(localPlayer));
}
}
}
}
@@ -21,18 +21,21 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creature;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
@@ -47,8 +50,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EndermanPickupEvent;
import org.bukkit.event.entity.EndermanPlaceEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
@@ -62,6 +64,7 @@ import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
@@ -70,12 +73,13 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Listener for entity related events.
*
*
* @author sk89q
*/
public class WorldGuardEntityListener implements Listener {
@@ -84,8 +88,8 @@ public class WorldGuardEntityListener implements Listener {
/**
* Construct the object;
*
* @param plugin
*
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -98,10 +102,7 @@ public class WorldGuardEntityListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when an entity interacts with another object.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
@@ -116,9 +117,6 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called when an entity dies.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
@@ -128,20 +126,11 @@ public class WorldGuardEntityListener implements Listener {
event.setDroppedExp(0);
}
try {
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
}
} catch (Throwable t) {
// old CraftBukkit, eat it
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
}
}
/**
* Called on entity damage by a block.
*
* @param event
*/
private void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
@@ -191,11 +180,6 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called on entity damage by an entity.
*
* @param event
*/
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getCause() == DamageCause.PROJECTILE) {
onEntityDamageByProjectile(event);
@@ -204,7 +188,7 @@ public class WorldGuardEntityListener implements Listener {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
@@ -212,7 +196,7 @@ public class WorldGuardEntityListener implements Listener {
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
@@ -227,6 +211,7 @@ public class WorldGuardEntityListener implements Listener {
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
@@ -258,9 +243,9 @@ public class WorldGuardEntityListener implements Listener {
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP) || !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
@@ -275,7 +260,7 @@ public class WorldGuardEntityListener implements Listener {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT)) {
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -294,13 +279,13 @@ public class WorldGuardEntityListener implements Listener {
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP) || !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP)) {
((Player) fireball.getShooter()).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL)) {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -326,13 +311,13 @@ public class WorldGuardEntityListener implements Listener {
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE)) {
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION)) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -343,21 +328,17 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called on entity damage by a projectile.
*
* @param event
*/
private void onEntityDamageByProjectile(EntityDamageByEntityEvent event) {
Entity defender = event.getEntity();
Entity attacker = ((Projectile) event.getDamager()).getShooter();
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
event.setCancelled(true);
return;
@@ -366,11 +347,12 @@ public class WorldGuardEntityListener implements Listener {
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP)) {
((Player) attacker).sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
@@ -384,7 +366,7 @@ public class WorldGuardEntityListener implements Listener {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE)) {
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
@@ -394,14 +376,8 @@ public class WorldGuardEntityListener implements Listener {
}
/**
* Called on entity damage.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled()) {
return;
}
if (event instanceof EntityDamageByEntityEvent) {
this.onEntityDamageByEntity((EntityDamageByEntityEvent) event);
@@ -437,9 +413,12 @@ public class WorldGuardEntityListener implements Listener {
return;
}
ItemStack helmet = player.getInventory().getHelmet();
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& (player.getInventory().getHelmet().getTypeId() == BlockID.PUMPKIN
|| player.getInventory().getHelmet().getTypeId() == BlockID.JACKOLANTERN)) {
&& helmet != null
&& (helmet.getTypeId() == BlockID.PUMPKIN
|| helmet.getTypeId() == BlockID.JACKOLANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -475,15 +454,8 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called on entity combust.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
if (event.isCancelled()) {
return;
}
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -499,15 +471,11 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
/*
* Called on entity explode.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
@@ -525,7 +493,7 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
@@ -566,7 +534,7 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
@@ -587,7 +555,7 @@ public class WorldGuardEntityListener implements Listener {
event.blockList().clear();
return;
}
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
@@ -616,15 +584,11 @@ public class WorldGuardEntityListener implements Listener {
}
/**
/*
* Called on explosion prime
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
Entity ent = event.getEntity();
@@ -636,15 +600,8 @@ public class WorldGuardEntityListener implements Listener {
}
/**
* Called on creature spawn.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (cfg.activityHaltToggle) {
@@ -653,15 +610,20 @@ public class WorldGuardEntityListener implements Listener {
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
CreatureType creaType = event.getCreatureType();
if (wcfg.blockCreatureSpawn.contains(creaType)) {
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM)
return;
EntityType entityType = event.getEntityType();
if (wcfg.blockCreatureSpawn.contains(entityType)) {
event.setCancelled(true);
return;
}
Location eventLoc = event.getLocation();
if (wcfg.useRegions) {
Vector pt = toVector(eventLoc);
RegionManager mgr = plugin.getGlobalRegionManager().get(eventLoc.getWorld());
@@ -674,23 +636,16 @@ public class WorldGuardEntityListener implements Listener {
return;
}
Set<CreatureType> creatureTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (creatureTypes != null && creatureTypes.contains(creaType)) {
Set<EntityType> entityTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (entityTypes != null && entityTypes.contains(entityType)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on pig zap.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
@@ -699,15 +654,8 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called on creeper power.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
@@ -716,58 +664,63 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called when a painting is removed.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (breakEvent.isCancelled()) {
return;
}
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
if (!(event.getRemover() instanceof Player)) {
return;
}
Painting painting= event.getPainting();
Player player = (Player) event.getRemover();
World world = painting.getWorld();
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
if (event.getRemover() instanceof Player) {
Player player = (Player) event.getRemover();
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} 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) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
}
/**
* Called on painting place.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
@@ -778,7 +731,7 @@ public class WorldGuardEntityListener implements Listener {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), 321), false, false)) {
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
@@ -793,14 +746,8 @@ public class WorldGuardEntityListener implements Listener {
}
}
/**
* Called on entity health regain.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (event.isCancelled()) {
return;
}
Entity ent = event.getEntity();
World world = ent.getWorld();
@@ -815,62 +762,54 @@ public class WorldGuardEntityListener implements Listener {
}
/**
* Called when an enderman picks a block up.
* Called when an enderman picks up or puts down a block and some other cases.
*
* @param event Relevant event details
*/
@EventHandler(priority = EventPriority.HIGH)
public void onEndermanPickup(EndermanPickupEvent event) {
if (event.isCancelled()) {
return;
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEndermanPickup(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (ent instanceof Enderman) {
if (event.getTo() == Material.AIR) {
// pickup
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, block.getLocation())) {
event.setCancelled(true);
return;
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
} else {
// place
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
}
}
}
/**
* Called when an enderman places a block.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onEndermanPlace(EndermanPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Entity ent = event.getEntity();
Location loc = event.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, loc)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
@@ -880,13 +819,28 @@ public class WorldGuardEntityListener implements Listener {
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
GlobalRegionManager global = plugin.getGlobalRegionManager();
int blockedEntities = 0;
for (LivingEntity e : event.getAffectedEntities()) {
if (!global.allows(DefaultFlag.POTION_SPLASH, e.getLocation(), e instanceof Player ? plugin.wrapPlayer((Player) e) : null)) {
event.setIntensity(e, 0);
++blockedEntities;
}
}
if (blockedEntities == event.getAffectedEntities().size()) {
event.setCancelled(true);
}
}
/**
* Check if a player is invincible, via either god mode or region flag. If
* the region denies invincibility, the player must have an extra permission
* to override it. (worldguard.god.override-regions)
*
* @param player
* @return
*
* @param player The player to check
* @return Whether {@code player} is invincible
*/
private boolean isInvincible(Player player) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -895,7 +849,7 @@ public class WorldGuardEntityListener implements Listener {
boolean god = cfg.hasGodMode(player);
if (wcfg.useRegions) {
Boolean flag = RegionQueryUtil.isAllowedInvinciblity(plugin, player);
boolean allowed = flag == null || flag == true;
boolean allowed = flag == null || flag;
boolean invincible = RegionQueryUtil.isInvincible(plugin, player);
if (allowed) {
@@ -908,4 +862,23 @@ public class WorldGuardEntityListener implements Listener {
return god;
}
}
/**
* Using a DisallowedPVPEvent, notifies other plugins that WorldGuard
* wants to cancel a PvP damage event.<br />
* If this event is not cancelled, the attacking player is notified that
* PvP is disabled and WorldGuard cancels the damage event.
*
* @param attackingPlayer The attacker
* @param defendingPlayer The defender
* @param event The event that caused WorldGuard to act
*/
public void tryCancelPVPEvent(final Player attackingPlayer, final Player defendingPlayer, EntityDamageByEntityEvent event) {
final DisallowedPVPEvent disallowedPVPEvent = new DisallowedPVPEvent(attackingPlayer, defendingPlayer, event);
plugin.getServer().getPluginManager().callEvent(disallowedPVPEvent);
if (!disallowedPVPEvent.isCancelled()) {
attackingPlayer.sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
}
}
}
@@ -22,11 +22,10 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
@@ -41,11 +40,14 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
@@ -65,8 +67,6 @@ import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.bukkit.FlagStateManager.PlayerFlagState;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag.RegionGroup;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -79,7 +79,7 @@ public class WorldGuardPlayerListener implements Listener {
/**
* Construct the object;
*
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
@@ -97,15 +97,10 @@ public class WorldGuardPlayerListener implements Listener {
pm.registerEvents(new PlayerMoveHandler(), plugin);
}
}
private class PlayerMoveHandler implements Listener {
/**
* Called when a player attempts to move.
*
* @param event
*/
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(PlayerMoveEvent event) {
class PlayerMoveHandler implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
@@ -125,7 +120,7 @@ public class WorldGuardPlayerListener implements Listener {
plugin.getFlagStateManager().forget(player);
state = plugin.getFlagStateManager().getState(player);
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
boolean hasBypass = plugin.getGlobalRegionManager().hasBypass(player, world);
@@ -163,23 +158,28 @@ public class WorldGuardPlayerListener implements Listener {
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);//, localPlayer);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);//, localPlayer);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);//, localPlayer);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);//, localPlayer);
GameMode gameMode = set.getFlag(DefaultFlag.GAME_MODE);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
for (String line : replacedFarewell.split("\n")) {
player.sendMessage(ChatColor.AQUA + " ** " + line);
}
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
for (String line : replacedGreeting.split("\n")) {
player.sendMessage(ChatColor.AQUA + " ** " + line);
}
}
if ((notifyLeave == null || !notifyLeave)
@@ -207,6 +207,21 @@ public class WorldGuardPlayerListener implements Listener {
+ regionList);
}
if (!hasBypass && gameMode != null) {
if (player.getGameMode() != gameMode) {
state.lastGameMode = player.getGameMode();
player.setGameMode(gameMode);
} else if (state.lastGameMode == null) {
state.lastGameMode = player.getServer().getDefaultGameMode();
}
} else {
if (state.lastGameMode != null) {
GameMode mode = state.lastGameMode;
state.lastGameMode = null;
player.setGameMode(mode);
}
}
state.lastGreeting = greeting;
state.lastFarewell = farewell;
state.notifiedForEnter = notifyEnter;
@@ -221,10 +236,22 @@ public class WorldGuardPlayerListener implements Listener {
}
}
/**
* Called when a player joins a server.
*/
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
if (wcfg.useRegions && !plugin.getGlobalRegionManager().hasBypass(player, player.getWorld())) {
GameMode gameMode = plugin.getGlobalRegionManager().get(player.getWorld())
.getApplicableRegions(player.getLocation()).getFlag(DefaultFlag.GAME_MODE);
if (plugin.getFlagStateManager().getState(player).lastGameMode != null
&& gameMode != null && event.getNewGameMode() != gameMode) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Your game mode is locked to "
+ gameMode + "in this region!");
}
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
@@ -256,12 +283,12 @@ public class WorldGuardPlayerListener implements Listener {
player.sendMessage(ChatColor.YELLOW
+ "Fire spread is currently globally disabled for this world.");
}
if (!cfg.hasCommandBookGodMode() && cfg.autoGodMode && (plugin.inGroup(player, "wg-invincible")
|| plugin.hasPermission(player, "worldguard.auto-invincible"))) {
cfg.enableGodMode(player);
}
if (plugin.inGroup(player, "wg-amphibious")) {
cfg.enableAmphibiousMode(player);
}
@@ -276,9 +303,52 @@ public class WorldGuardPlayerListener implements Listener {
}
}
/**
* Called when a player leaves a server.
*/
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.SEND_CHAT, player.getLocation())) {
player.sendMessage(ChatColor.RED + "You don't have permission to chat in this region!");
event.setCancelled(true);
return;
}
for (Iterator<Player> i = event.getRecipients().iterator(); i.hasNext();) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.RECEIVE_CHAT, i.next().getLocation())) {
i.remove();
}
}
if (event.getRecipients().size() == 0) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
String hostKey = cfg.hostKeys.get(player.getName().toLowerCase());
if (hostKey != null) {
String hostname = event.getHostname();
int colonIndex = hostname.indexOf(':');
if (colonIndex != -1) {
hostname = hostname.substring(0, colonIndex);
}
if (!hostname.equals(hostKey)) {
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
"You did not join with the valid host key!");
plugin.getLogger().warning("WorldGuard host key check: " +
player.getName() + " joined with '" + hostname +
"' but '" + hostKey + "' was expected. Kicked!");
return;
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
@@ -321,14 +391,11 @@ public class WorldGuardPlayerListener implements Listener {
plugin.forgetPlayer(player);
}
/**
* Called when a player interacts with an item.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
handleBlockRightClick(event);
} else if (event.getAction() == Action.RIGHT_CLICK_AIR) {
@@ -340,25 +407,25 @@ public class WorldGuardPlayerListener implements Listener {
} else if (event.getAction() == Action.PHYSICAL) {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int slot = player.getInventory().getHeldItemSlot();
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem.getAmount() < 0) {
if (heldItem != null && heldItem.getAmount() < 0) {
player.getInventory().setItem(slot, null);
player.sendMessage(ChatColor.RED + "Infinite stack removed.");
}
}
}
/**
* Called when a player left clicks air.
*
* @param event
* @param event Thrown event
*/
private void handleAirLeftClick(PlayerInteractEvent event) {
// I don't think we have to do anything here yet.
@@ -368,7 +435,7 @@ public class WorldGuardPlayerListener implements Listener {
/**
* Called when a player left clicks a block.
*
* @param event
* @param event Thrown event
*/
private void handleBlockLeftClick(PlayerInteractEvent event) {
if (event.isCancelled()) return;
@@ -393,7 +460,7 @@ public class WorldGuardPlayerListener implements Listener {
|| type == BlockID.TRAP_DOOR
|| type == BlockID.NOTE_BLOCK) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.allows(DefaultFlag.USE, localPlayer)
&& !set.canBuild(localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to use that in this area.");
event.setUseInteractedBlock(Result.DENY);
@@ -430,8 +497,8 @@ public class WorldGuardPlayerListener implements Listener {
/**
* Called when a player right clicks air.
*
* @param event
*
* @param event Thrown event
*/
private void handleAirRightClick(PlayerInteractEvent event) {
if (event.isCancelled()) {
@@ -456,11 +523,11 @@ public class WorldGuardPlayerListener implements Listener {
}
}
}
/**
* Called when a player right clicks a block.
*
* @param event
*
* @param event Thrown event
*/
private void handleBlockRightClick(PlayerInteractEvent event) {
if (event.isCancelled()) {
@@ -528,7 +595,7 @@ public class WorldGuardPlayerListener implements Listener {
Block placedOn = block.getRelative(event.getBlockFace());
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !plugin.getGlobalRegionManager().allows(
DefaultFlag.TNT, placedOn.getLocation())) {
DefaultFlag.TNT, placedOn.getLocation(), localPlayer)) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
}
@@ -547,7 +614,7 @@ public class WorldGuardPlayerListener implements Listener {
if (type == BlockID.BED) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.SLEEP)) {
&& !set.allows(DefaultFlag.SLEEP, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You're not allowed to use that bed.");
event.setUseInteractedBlock(Result.DENY);
event.setCancelled(true);
@@ -562,8 +629,8 @@ public class WorldGuardPlayerListener implements Listener {
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.BREWING_STAND) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.CHEST_ACCESS)
&& !set.canBuild(localPlayer)) {
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.CHEST_ACCESS, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to open that in this area.");
event.setUseInteractedBlock(Result.DENY);
event.setCancelled(true);
@@ -589,8 +656,8 @@ public class WorldGuardPlayerListener implements Listener {
|| type == BlockID.CAULDRON
|| type == BlockID.DRAGON_EGG) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.USE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to use that in this area.");
event.setUseInteractedBlock(Result.DENY);
event.setCancelled(true);
@@ -611,18 +678,18 @@ public class WorldGuardPlayerListener implements Listener {
if (BlockType.isRailBlock(type) && item.getTypeId() == ItemID.MINECART) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
&& !set.allows(DefaultFlag.PLACE_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place vehicles here.");
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
return;
}
}
if (item.getTypeId() == ItemID.WOOD_BOAT) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.PLACE_VEHICLE)) {
&& !set.allows(DefaultFlag.PLACE_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place vehicles here.");
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
@@ -675,7 +742,7 @@ public class WorldGuardPlayerListener implements Listener {
|| type == BlockID.BURNING_FURNACE
|| type == BlockID.ENCHANTMENT_TABLE
|| type == BlockID.BREWING_STAND)) {
if (wcfg.isChestProtected(block, player)) {
player.sendMessage(ChatColor.DARK_RED + "The chest is protected.");
event.setUseInteractedBlock(Result.DENY);
@@ -723,7 +790,7 @@ public class WorldGuardPlayerListener implements Listener {
}
} else {
player.sendMessage(ChatColor.RED + "Region: " + regionId + " is not buyable");
}
}
} else {
player.sendMessage(ChatColor.DARK_RED + "The region " + regionId + " does not exist.");
}
@@ -737,7 +804,7 @@ public class WorldGuardPlayerListener implements Listener {
/**
* Called when a player steps on a pressure plate or tramples crops.
*
* @param event
* @param event Thrown event
*/
private void handlePhysicalInteract(PlayerInteractEvent event) {
if (event.isCancelled()) return;
@@ -763,8 +830,8 @@ public class WorldGuardPlayerListener implements Listener {
if (type == BlockID.STONE_PRESSURE_PLATE || type == BlockID.WOODEN_PRESSURE_PLATE) {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.allows(DefaultFlag.USE)
&& !set.canBuild(localPlayer)) {
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.USE, localPlayer)) {
event.setUseInteractedBlock(Result.DENY);
event.setCancelled(true);
return;
@@ -840,17 +907,18 @@ public class WorldGuardPlayerListener implements Listener {
}
}*/
/**
* Called when a player attempts to drop an item.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
Player player = event.getPlayer();
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ITEM_DROP, player.getLocation())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You don't have permission to do that in this area.");
}
}
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
@@ -864,15 +932,8 @@ public class WorldGuardPlayerListener implements Listener {
}
}
/**
* Called when a player attempts to pickup an item.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getPlayer().getWorld());
@@ -888,59 +949,22 @@ public class WorldGuardPlayerListener implements Listener {
}
}
/**
* Called when a bucket is filled.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event.getItemStack().getTypeId() == ItemID.MILK_BUCKET) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.USE, player.getLocation().add(0, 1, 0))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to use this in this area.");
event.setCancelled(true);
return;
}
} else if (!plugin.getGlobalRegionManager().canBuild(
player, event.getBlockClicked().getRelative(event.getBlockFace()))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), event.getBucket().getId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
/**
* Called when a bucket is empty.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (!plugin.getGlobalRegionManager().canBuild(
player, event.getBlockClicked().getRelative(event.getBlockFace()))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
@@ -950,72 +974,74 @@ public class WorldGuardPlayerListener implements Listener {
}
}
}
/**
* Called when a player is respawned.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.useRegions) {
Vector pt = toVector(location);
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
Vector spawn = set.getFlag(DefaultFlag.SPAWN_LOC);
if (spawn != null) {
RegionGroup group = set.getFlag(DefaultFlag.SPAWN_PERM);
Location spawnLoc = BukkitUtil.toLocation(player.getWorld(), spawn);
if (group != null) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (RegionGroupFlag.isMember(set, group, localPlayer)) {
event.setRespawnLocation(spawnLoc);
}
} else {
event.setRespawnLocation(spawnLoc);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
Player player = event.getPlayer();
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (!plugin.getGlobalRegionManager().canBuild(
player, event.getBlockClicked().getRelative(event.getBlockFace()))) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), event.getBucket().getId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.useRegions) {
Vector pt = toVector(location);
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
LocalPlayer localPlayer = plugin.wrapPlayer(player);
com.sk89q.worldedit.Location spawn = set.getFlag(DefaultFlag.SPAWN_LOC, localPlayer);
if (spawn != null) {
event.setRespawnLocation(com.sk89q.worldedit.bukkit.BukkitUtil.toLocation(spawn));
}
}
}
/**
* Called when a player changes their held item.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
int newSlot = event.getNewSlot();
ItemStack heldItem = player.getInventory().getItem(newSlot);
if (heldItem.getAmount() < 0) {
if (heldItem != null && heldItem.getAmount() < 0) {
player.getInventory().setItem(newSlot, null);
player.sendMessage(ChatColor.RED + "Infinite stack removed.");
}
}
}
/**
* Called when a player enters a bed.
*/
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
if (event.isCancelled()) {
return;
}
Player player = event.getPlayer();
Location location = player.getLocation();
@@ -1028,7 +1054,7 @@ public class WorldGuardPlayerListener implements Listener {
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!plugin.getGlobalRegionManager().hasBypass(player, player.getWorld())
&& !set.allows(DefaultFlag.SLEEP)) {
&& !set.allows(DefaultFlag.SLEEP, plugin.wrapPlayer(player))) {
event.setCancelled(true);
player.sendMessage("This bed doesn't belong to you!");
return;
@@ -1036,12 +1062,10 @@ public class WorldGuardPlayerListener implements Listener {
}
}
/**
* Called on command run.
*/
@EventHandler(priority = EventPriority.LOWEST)
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
World world = player.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
@@ -1050,27 +1074,23 @@ public class WorldGuardPlayerListener implements Listener {
Vector pt = toVector(player.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
ProtectedRegion globalRegion = mgr.getRegion("__global__");
String[] parts = event.getMessage().split(" ");
String lowerCommand = parts[0].toLowerCase();
Set<String> allowedCommands = set.getFlag(DefaultFlag.ALLOWED_CMDS);
if (allowedCommands == null && globalRegion != null) {
allowedCommands = globalRegion.getFlag(DefaultFlag.ALLOWED_CMDS);
}
if (allowedCommands != null && !allowedCommands.contains(parts[0].toLowerCase())) {
Set<String> allowedCommands = set.getFlag(DefaultFlag.ALLOWED_CMDS, localPlayer);
Set<String> blockedCommands = set.getFlag(DefaultFlag.BLOCKED_CMDS, localPlayer);
player.sendMessage(ChatColor.RED + parts[0].toLowerCase() + " is not allowed in this area.");
if (allowedCommands != null && !allowedCommands.contains(lowerCommand)
&& (blockedCommands == null || blockedCommands.contains(lowerCommand))) {
player.sendMessage(ChatColor.RED + lowerCommand + " is not allowed in this area.");
event.setCancelled(true);
return;
}
Set<String> blockedCommands = set.getFlag(DefaultFlag.BLOCKED_CMDS);
if (blockedCommands == null && globalRegion != null) {
blockedCommands = globalRegion.getFlag(DefaultFlag.BLOCKED_CMDS);
}
if (blockedCommands != null && blockedCommands.contains(parts[0].toLowerCase())) {
player.sendMessage(ChatColor.RED + parts[0].toLowerCase() + " is blocked in this area.");
if (blockedCommands != null && blockedCommands.contains(lowerCommand)
&& (allowedCommands == null || !allowedCommands.contains(lowerCommand))) {
player.sendMessage(ChatColor.RED + lowerCommand + " is blocked in this area.");
event.setCancelled(true);
return;
}
@@ -28,9 +28,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.logging.Filter;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
@@ -43,26 +42,28 @@ import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.TickSyncDelayLoggerFilter;
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.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.
@@ -74,12 +75,12 @@ public class WorldGuardPlugin extends JavaPlugin {
* Handles the region databases for all worlds.
*/
private final GlobalRegionManager globalRegionManager;
/**
* Handles all configuration.
*/
private final ConfigurationManager configuration;
/**
* Used for scheduling flags.
*/
@@ -101,7 +102,7 @@ public class WorldGuardPlugin extends JavaPlugin {
}
};
}
/**
* Called on plugin enable.
*/
@@ -115,7 +116,7 @@ public class WorldGuardPlugin extends JavaPlugin {
final CommandsManagerRegistration reg = new CommandsManagerRegistration(this, commands);
reg.register(ToggleCommands.class);
reg.register(ProtectionCommands.class);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
@@ -132,11 +133,16 @@ public class WorldGuardPlugin extends JavaPlugin {
// This must be done before configuration is loaded
LegacyWorldGuardMigration.migrateBlacklist(this);
// Load the configuration
configuration.load();
globalRegionManager.preload();
try {
// Load the configuration
configuration.load();
globalRegionManager.preload();
} catch (FatalConfigurationLoadingException e) {
e.printStackTrace();
getServer().shutdown();
}
// Migrate regions after the regions were loaded because
// the migration code reuses the loaded region managers
LegacyWorldGuardMigration.migrateRegions(this);
@@ -147,16 +153,6 @@ public class WorldGuardPlugin extends JavaPlugin {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, flagStateManager, FlagStateManager.RUN_DELAY, FlagStateManager.RUN_DELAY);
}
if (configuration.suppressTickSyncWarnings) {
Logger.getLogger("Minecraft").setFilter(
new TickSyncDelayLoggerFilter());
} else {
Filter filter = Logger.getLogger("Minecraft").getFilter();
if (filter != null && filter instanceof TickSyncDelayLoggerFilter) {
Logger.getLogger("Minecraft").setFilter(null);
}
}
// Register events
(new WorldGuardPlayerListener(this)).registerEvents();
(new WorldGuardBlockListener(this)).registerEvents();
@@ -164,6 +160,11 @@ public class WorldGuardPlugin extends JavaPlugin {
(new WorldGuardWeatherListener(this)).registerEvents();
(new WorldGuardVehicleListener(this)).registerEvents();
(new WorldGuardServerListener(this)).registerEvents();
configuration.updateCommandBookGodMode();
if (getServer().getPluginManager().isPluginEnabled("CommandBook")) {
getServer().getPluginManager().registerEvents(new WorldGuardCommandBookListener(this), this);
}
// handle worlds separately to initialize already loaded worlds
WorldGuardWorldListener worldListener = (new WorldGuardWorldListener(this));
@@ -191,7 +192,7 @@ public class WorldGuardPlugin extends JavaPlugin {
configuration.unload();
this.getServer().getScheduler().cancelTasks(this);
}
/**
* Handle a command.
*/
@@ -217,43 +218,43 @@ public class WorldGuardPlugin extends JavaPlugin {
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
/**
* Get the GlobalRegionManager.
*
* @return
*
* @return The plugin's global region manager
*/
public GlobalRegionManager getGlobalRegionManager() {
return globalRegionManager;
}
/**
* Get the WorldGuardConfiguraton.
* Get the WorldGuard Configuration.
*
* @return
* @return ConfigurationManager
* @deprecated Use {@link #getGlobalStateManager()} instead
*/
@Deprecated
public ConfigurationManager getGlobalConfiguration() {
return getGlobalStateManager();
}
/**
* Gets the flag state manager.
*
* @return
*
* @return The flag state manager
*/
public FlagStateManager getFlagStateManager() {
return flagStateManager;
}
/**
* Get the WorldGuardConfiguraton.
*
* @return
* Get the global ConfigurationManager.
* USe this to access global configuration values and per-world configuration values.
* @return The global ConfigurationManager
*/
public ConfigurationManager getGlobalStateManager() {
return configuration;
@@ -261,10 +262,11 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Check whether a player is in a group.
*
* @param player
* @param group
* @return
* This calls the corresponding method in PermissionsResolverManager
*
* @param player The player to check
* @param group The group
* @return whether {@code player} is in {@code group}
*/
public boolean inGroup(Player player, String group) {
try {
@@ -277,9 +279,9 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Get the groups of a player.
*
* @param player
* @return
* This calls the corresponding method in PermissionsResolverManager.
* @param player The player to check
* @return The names of each group the playe is in.
*/
public String[] getGroups(Player player) {
try {
@@ -289,42 +291,44 @@ public class WorldGuardPlugin extends JavaPlugin {
return new String[0];
}
}
/**
* Gets the name of a command sender. This is a unique name and this
* method should never return a "display name".
*
* @param sender
* @return
*
* @param sender The sender to get the name of
* @return The unique name of the sender.
*/
public String toUniqueName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else {
return sender.getName();
}
}
/**
* Gets the name of a command sender. This play be a display name.
*
* @param sender
* @return
*
* @param sender The CommandSender to get the name of.
* @return The name of the given sender
*/
public String toName(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
} else {
if (sender instanceof ConsoleCommandSender) {
return "*Console*";
} else if (sender instanceof Player) {
return ((Player) sender).getDisplayName();
} else {
return sender.getName();
}
}
/**
* Checks permissions.
*
* @param sender
* @param perm
* @return
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @return whether {@code sender} has {@code perm}
*/
public boolean hasPermission(CommandSender sender, String perm) {
if (sender.isOp()) {
@@ -337,22 +341,22 @@ public class WorldGuardPlugin extends JavaPlugin {
return true;
}
}
// Invoke the permissions resolver
if (sender instanceof Player) {
Player player = (Player) sender;
return PermissionsResolverManager.getInstance().hasPermission(player.getWorld().getName(), player.getName(), perm);
}
return false;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param sender
* @param perm
* @throws CommandPermissionsException
*
* @param sender The sender to check the permission on.
* @param perm The permission to check the permission on.
* @throws CommandPermissionsException if {@code sender} doesn't have {@code perm}
*/
public void checkPermission(CommandSender sender, String perm)
throws CommandPermissionsException {
@@ -360,13 +364,13 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandPermissionsException();
}
}
/**
* Checks to see if the sender is a player, otherwise throw an exception.
*
* @param sender
* @return
* @throws CommandException
*
* @param sender The {@link CommandSender} to check
* @return {@code sender} casted to a player
* @throws CommandException if {@code sender} isn't a {@link Player}
*/
public Player checkPlayer(CommandSender sender)
throws CommandException {
@@ -376,22 +380,27 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandException("A player is expected.");
}
}
/**
* Match player names.
*
* @param filter
* @return
*
* The filter string uses the following format:
* @[name] looks up all players with the exact {@code name}
* *[name] matches any player whose name contains {@code name}
* [name] matches any player whose name starts with {@code name}
*
* @param filter The filter string to check.
* @return A {@link List} of players who match {@code filter}
*/
public List<Player> matchPlayerNames(String filter) {
Player[] players = getServer().getOnlinePlayers();
filter = filter.toLowerCase();
// Allow exact name matching
if (filter.charAt(0) == '@' && filter.length() >= 2) {
filter = filter.substring(1);
for (Player player : players) {
if (player.getName().equalsIgnoreCase(filter)) {
List<Player> list = new ArrayList<Player>();
@@ -399,43 +408,43 @@ public class WorldGuardPlugin extends JavaPlugin {
return list;
}
}
return new ArrayList<Player>();
// Allow partial name matching
} else if (filter.charAt(0) == '*' && filter.length() >= 2) {
filter = filter.substring(1);
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().contains(filter)) {
list.add(player);
}
}
return list;
// Start with name matching
} else {
List<Player> list = new ArrayList<Player>();
for (Player player : players) {
if (player.getName().toLowerCase().startsWith(filter)) {
list.add(player);
}
}
return list;
}
}
/**
* Checks if the given list of players is greater than size 0, otherwise
* throw an exception.
*
* @param players
* @return
* @throws CommandException
*
* @param players The {@link List} to check
* @return {@code players} as an {@link Iterable}
* @throws CommandException If {@code players} is empty
*/
protected Iterable<Player> checkPlayerMatch(List<Player> players)
throws CommandException {
@@ -443,25 +452,32 @@ public class WorldGuardPlugin extends JavaPlugin {
if (players.size() == 0) {
throw new CommandException("No players matched query.");
}
return players;
}
/**
* Checks permissions and throws an exception if permission is not met.
*
* @param source
* @param filter
* Matches players based on the specified filter string
*
* The filter string format is as follows:
* * returns all the players currently online
* If {@code sender} is a {@link Player}:
* #world returns all players in the world that {@code sender} is in
* #near reaturns all players within 30 blocks of {@code sender}'s location
* Otherwise, the format is as specified in {@link #matchPlayerNames(String)}
*
* @param source The CommandSender who is trying to find a player
* @param filter The filter string for players
* @return iterator for players
* @throws CommandException no matches found
* @throws CommandException if no matches are found
*/
public Iterable<Player> matchPlayers(CommandSender source, String filter)
throws CommandException {
if (getServer().getOnlinePlayers().length == 0) {
throw new CommandException("No players matched query.");
}
if (filter.equals("*")) {
return checkPlayerMatch(Arrays.asList(getServer().getOnlinePlayers()));
}
@@ -474,7 +490,7 @@ public class WorldGuardPlugin extends JavaPlugin {
List<Player> players = new ArrayList<Player>();
Player sourcePlayer = checkPlayer(source);
World sourceWorld = sourcePlayer.getWorld();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)) {
players.add(player);
@@ -482,7 +498,7 @@ public class WorldGuardPlugin extends JavaPlugin {
}
return checkPlayerMatch(players);
// Handle #near, which is for nearby players.
} else if (filter.equalsIgnoreCase("#near")) {
List<Player> players = new ArrayList<Player>();
@@ -490,7 +506,7 @@ public class WorldGuardPlugin extends JavaPlugin {
World sourceWorld = sourcePlayer.getWorld();
org.bukkit.util.Vector sourceVector
= sourcePlayer.getLocation().toVector();
for (Player player : getServer().getOnlinePlayers()) {
if (player.getWorld().equals(sourceWorld)
&& player.getLocation().toVector().distanceSquared(
@@ -500,32 +516,33 @@ public class WorldGuardPlugin extends JavaPlugin {
}
return checkPlayerMatch(players);
} else {
throw new CommandException("Invalid group '" + filter + "'.");
}
}
List<Player> players = matchPlayerNames(filter);
return checkPlayerMatch(players);
}
/**
* Match only a single player.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*
* @param sender The {@link CommandSender} who is requesting a player match
* @param filter The filter string.
* @see #matchPlayers(org.bukkit.entity.Player) for filter string syntax
* @return The single player
* @throws CommandException If more than one player match was found
*/
public Player matchSinglePlayer(CommandSender sender, String filter)
throws CommandException {
// This will throw an exception if there are no matches
Iterator<Player> players = matchPlayers(sender, filter).iterator();
Player match = players.next();
// We don't want to match the wrong person, so fail if if multiple
// players were found (we don't want to just pick off the first one,
// as that may be the wrong player)
@@ -533,48 +550,58 @@ public class WorldGuardPlugin extends JavaPlugin {
throw new CommandException("More than one player found! " +
"Use @<name> for exact matching.");
}
return match;
}
/**
* Match only a single player or console.
*
* @param sender
* @param filter
* @return
* @throws CommandException
*
* The filter string syntax is as follows:
* #console, *console, or ! return the server console
* All syntax from {@link #matchSinglePlayer(org.bukkit.command.CommandSender, String)}
* @param sender The sender trying to match a CommandSender
* @param filter The filter string
* @return The resulting CommandSender
* @throws CommandException if either zero or more than one player matched.
*/
public CommandSender matchPlayerOrConsole(CommandSender sender, String filter)
throws CommandException {
// Let's see if console is wanted
if (filter.equalsIgnoreCase("#console")
|| filter.equalsIgnoreCase("*console*")
|| filter.equalsIgnoreCase("!")) {
return getServer().getConsoleSender();
}
return matchSinglePlayer(sender, filter);
}
/**
* Get a single player as an iterator for players.
*
* @param player
* @return iterator for players
*
* @param player The player to return in an Iterable
* @return iterator for player
*/
public Iterable<Player> matchPlayers(Player player) {
return Arrays.asList(new Player[] {player});
return Arrays.asList(player);
}
/**
* Match a world.
* @param sender
*
* @param filter
* @return
* @throws CommandException
*
* The filter string syntax is as follows:
* #main returns the main world
* #normal returns the first world with a normal environment
* #nether return the first world with a nether environment
* #player:[name] returns the world that a player named {@code name} is located in, if the player is online.
* [name] A world with the name {@code name}
*
* @param sender The sender requesting a match
* @param filter The filter string
* @return The resulting world
* @throws CommandException if no world matches
*/
public World matchWorld(CommandSender sender, String filter) throws CommandException {
List<World> worlds = getServer().getWorlds();
@@ -584,7 +611,7 @@ public class WorldGuardPlugin extends JavaPlugin {
// #main for the main world
if (filter.equalsIgnoreCase("#main")) {
return worlds.get(0);
// #normal for the first normal world
} else if (filter.equalsIgnoreCase("#normal")) {
for (World world : worlds) {
@@ -594,7 +621,7 @@ public class WorldGuardPlugin extends JavaPlugin {
}
throw new CommandException("No normal world found.");
// #nether for the first nether world
} else if (filter.equalsIgnoreCase("#nether")) {
for (World world : worlds) {
@@ -608,65 +635,65 @@ public class WorldGuardPlugin extends JavaPlugin {
// Handle getting a world from a player
} else if (filter.matches("^#player$")) {
String parts[] = filter.split(":", 2);
// They didn't specify an argument for the player!
if (parts.length == 1) {
throw new CommandException("Argument expected for #player.");
}
return matchPlayers(sender, parts[1]).iterator().next().getWorld();
} else {
throw new CommandException("Invalid identifier '" + filter + "'.");
}
}
for (World world : worlds) {
if (world.getName().equals(filter)) {
return world;
}
}
throw new CommandException("No world by that exact name found.");
}
/**
* Gets a copy of the WorldEdit plugin.
*
* @return
* @throws CommandException
*
* @return The WorldEditPlugin instance
* @throws CommandException If there is no WorldEditPlugin available
*/
public WorldEditPlugin getWorldEdit() throws CommandException {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
}
if (worldEdit instanceof WorldEditPlugin) {
return (WorldEditPlugin) worldEdit;
} else {
throw new CommandException("WorldEdit detection failed (report error).");
}
}
/**
* Wrap a player as a LocalPlayer.
*
* @param player
* @return
*
* @param player The player to wrap
* @return The wrapped player
*/
public LocalPlayer wrapPlayer(Player player) {
return new BukkitPlayer(this, player);
}
/**
* Create a default configuration file from the .jar.
*
* @param actual
* @param defaultName
*
* @param actual The destination file
* @param defaultName The name of the file inside the jar's defaults folder
*/
public void createDefaultConfiguration(File actual,
String defaultName) {
// Make parent directories
File parent = actual.getParentFile();
if (!parent.exists()) {
@@ -687,7 +714,7 @@ public class WorldGuardPlugin extends JavaPlugin {
} catch (IOException e) {
getLogger().severe("Unable to read default configuration: " + defaultName);
}
if (input != null) {
FileOutputStream output = null;
@@ -708,60 +735,68 @@ public class WorldGuardPlugin extends JavaPlugin {
if (input != null) {
input.close();
}
} catch (IOException e) {
} catch (IOException ignore) {
}
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
} catch (IOException ignore) {
}
}
}
}
/**
* Notifies all with the notify permission.
*
* @param msg
* Notifies all with the worldguard.notify permission.
* This will check both superperms and WEPIF,
* but makes sure WEPIF checks don't result in duplicate notifications
*
* @param msg The notification to broadcast
*/
public void broadcastNotification(String msg) {
getServer().broadcast(msg, "worldguard.notify");
Set<Permissible> subs = getServer().getPluginManager().getPermissionSubscriptions("worldguard.notify");
for (Player player : getServer().getOnlinePlayers()) {
if (hasPermission(player, "worldguard.notify")) {
if (!(subs.contains(player) && player.hasPermission("worldguard.notify")) &&
hasPermission(player, "worldguard.notify")) { // Make sure the player wasn't already broadcasted to.
player.sendMessage(msg);
}
}
getLogger().info(msg);
}
/**
* Forgets a player.
*
* @param player
*
* @param player The player to remove state information for
*/
public void forgetPlayer(Player player) {
flagStateManager.forget(player);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param loc
* @return
*
* @param player The player to check.
* @param loc The location to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.Location)
* @return whether {@code player} can build at {@code loc}
*/
public boolean canBuild(Player player, Location loc) {
return getGlobalRegionManager().canBuild(player, loc);
}
/**
* Checks to see if a player can build at a location. This will return
* true if region protection is disabled.
*
* @param player
* @param block
* @return
*
* @param player The player to check
* @param block The block to check at.
* @see GlobalRegionManager#canBuild(org.bukkit.entity.Player, org.bukkit.block.Block)
* @return whether {@code player} can build at {@code block}'s location
*/
public boolean canBuild(Player player, Block block) {
return getGlobalRegionManager().canBuild(player, block);
@@ -784,9 +819,17 @@ public class WorldGuardPlugin extends JavaPlugin {
/**
* Replace macros in the text.
*
* @param sender
* @param message
* @return
* The macros replaced are as follows:
* %name%: The name of {@code sender}. See {@link #toName(org.bukkit.command.CommandSender)}
* %id%: The unique name of the sender. See {@link #toUniqueName(org.bukkit.command.CommandSender)}
* %online%: The number of players currently online on the server
* If {@code sender} is a Player:
* %world%: The name of the world {@code sender} is located in
* %health%: The health of {@code sender}. See {@link org.bukkit.entity.Player#getHealth()}
*
* @param sender The sender to check
* @param message The message to replace macros in
* @return The message with macros replaced
*/
public String replaceMacros(CommandSender sender, String message) {
Player[] online = getServer().getOnlinePlayers();
@@ -24,11 +24,15 @@ public class WorldGuardServerListener implements Listener {
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
plugin.getGlobalStateManager().updateCommandBookGodMode();
}
}
}
@@ -7,8 +7,6 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@@ -46,9 +44,6 @@ public class WorldGuardVehicleListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a vehicle is destroyed.
*/
@EventHandler
public void onVehicleDestroy(VehicleDestroyEvent event) {
Vehicle vehicle = event.getVehicle();
@@ -69,7 +64,7 @@ public class WorldGuardVehicleListener implements Listener {
if (!plugin.getGlobalRegionManager().hasBypass(player, world)
&& !set.canBuild(localPlayer)
&& !set.allows(DefaultFlag.DESTROY_VEHICLE)) {
&& !set.allows(DefaultFlag.DESTROY_VEHICLE, localPlayer)) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to destroy vehicles here.");
event.setCancelled(true);
return;
@@ -77,9 +72,6 @@ public class WorldGuardVehicleListener implements Listener {
}
}
/**
* Called when a vehicle moves.
*/
@EventHandler
public void onVehicleMove(VehicleMoveEvent event) {
Vehicle vehicle = event.getVehicle();
@@ -127,44 +119,44 @@ public class WorldGuardVehicleListener implements Listener {
return;
}
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE);
if (state.lastFarewell != null && (farewell == null
String greeting = set.getFlag(DefaultFlag.GREET_MESSAGE, localPlayer);
String farewell = set.getFlag(DefaultFlag.FAREWELL_MESSAGE, localPlayer);
Boolean notifyEnter = set.getFlag(DefaultFlag.NOTIFY_ENTER, localPlayer);
Boolean notifyLeave = set.getFlag(DefaultFlag.NOTIFY_LEAVE, localPlayer);
if (state.lastFarewell != null && (farewell == null
|| !state.lastFarewell.equals(farewell))) {
String replacedFarewell = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(state.lastFarewell));
player.sendMessage(ChatColor.AQUA + " ** " + replacedFarewell);
}
if (greeting != null && (state.lastGreeting == null
|| !state.lastGreeting.equals(greeting))) {
String replacedGreeting = plugin.replaceMacros(
player, BukkitUtil.replaceColorMacros(greeting));
player.sendMessage(ChatColor.AQUA + " ** " + replacedGreeting);
}
if ((notifyLeave == null || !notifyLeave)
&& state.notifiedForLeave != null && state.notifiedForLeave) {
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " left NOTIFY region");
}
if (notifyEnter != null && notifyEnter && (state.notifiedForEnter == null
|| !state.notifiedForEnter)) {
StringBuilder regionList = new StringBuilder();
for (ProtectedRegion region : set) {
if (regionList.length() != 0) {
regionList.append(", ");
}
regionList.append(region.getId());
}
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
plugin.broadcastNotification(ChatColor.GRAY + "WG: "
+ ChatColor.LIGHT_PURPLE + player.getName()
+ ChatColor.GOLD + " entered NOTIFY region: "
+ ChatColor.WHITE
@@ -20,8 +20,6 @@ package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -44,7 +42,7 @@ public class WorldGuardWeatherListener implements Listener {
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -54,11 +52,8 @@ public class WorldGuardWeatherListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -73,12 +68,8 @@ public class WorldGuardWeatherListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -93,12 +84,8 @@ public class WorldGuardWeatherListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
if (event.isCancelled()) {
return;
}
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getWorld());
@@ -5,8 +5,6 @@
*/
package com.sk89q.worldguard.bukkit;
import java.util.logging.Logger;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
@@ -21,7 +19,7 @@ public class WorldGuardWorldListener implements Listener {
/**
* Construct the object;
*
* @param plugin
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -34,9 +32,6 @@ public class WorldGuardWorldListener implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Called when a chunk is loaded.
*/
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
@@ -58,14 +53,19 @@ public class WorldGuardWorldListener implements Listener {
}
}
/**
* Called when a world is loaded.
*/
@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) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
@@ -20,8 +20,10 @@
package com.sk89q.worldguard.bukkit.commands;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
@@ -35,7 +37,9 @@ import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
@@ -58,7 +62,7 @@ import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
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.util.RegionUtil;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
public class RegionCommands {
private final WorldGuardPlugin plugin;
@@ -118,7 +122,7 @@ public class RegionCommands {
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionUtil.parseDomainString(args.getSlice(1), 1));
region.setOwners(RegionDBUtil.parseDomainString(args.getSlice(1), 1));
}
mgr.addRegion(region);
@@ -147,12 +151,12 @@ public class RegionCommands {
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion existing = mgr.getRegion(id);
ProtectedRegion existing = mgr.getRegionExact(id);
if (existing == null) {
throw new CommandException("Could not find a region by that ID.");
}
if (existing.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.redefine.own");
} else if (existing.isMember(localPlayer)) {
@@ -191,7 +195,7 @@ public class RegionCommands {
region.setPriority(existing.getPriority());
try {
region.setParent(existing.getParent());
} catch (CircularInheritanceException e) {
} catch (CircularInheritanceException ignore) {
}
mgr.addRegion(region);
@@ -256,7 +260,7 @@ public class RegionCommands {
// Get the list of region owners
if (args.argsLength() > 1) {
region.setOwners(RegionUtil.parseDomainString(args.getSlice(1), 1));
region.setOwners(RegionDBUtil.parseDomainString(args.getSlice(1), 1));
}
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(player.getWorld());
@@ -270,7 +274,7 @@ public class RegionCommands {
}
}
ProtectedRegion existing = mgr.getRegion(id);
ProtectedRegion existing = mgr.getRegionExact(id);
// Check for an existing region
if (existing != null) {
@@ -336,240 +340,317 @@ public class RegionCommands {
+ e.getMessage());
}
}
@Command(aliases = {"select", "sel", "s"}, usage = "<id>",
desc = "Load a region as a WorldEdit selection", min = 1, max = 1)
public void select(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);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
@Command(aliases = {"select", "sel", "s"}, usage = "[id]",
desc = "Load a region as a WorldEdit selection", min = 0, max = 1)
public void select(CommandContext args, CommandSender sender) throws CommandException {
final Player player = plugin.checkPlayer(sender);
final World world = player.getWorld();
final LocalPlayer localPlayer = plugin.wrapPlayer(player);
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final String id;
if (args.argsLength() == 0) {
final Vector pt = localPlayer.getPosition();
final ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (set.size() == 0) {
throw new CommandException("No region ID specified and no region found at current location!");
}
id = set.iterator().next().getId();
}
else {
id = args.getString(0);
}
final ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
selectRegion(player, localPlayer, region);
}
public void selectRegion(Player player, LocalPlayer localPlayer, ProtectedRegion region) throws CommandException, CommandPermissionsException {
final WorldEditPlugin worldEdit = plugin.getWorldEdit();
final String id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.select.own." + id.toLowerCase());
plugin.checkPermission(player, "worldguard.region.select.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.select.member." + id.toLowerCase());
plugin.checkPermission(player, "worldguard.region.select.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.select." + id.toLowerCase());
plugin.checkPermission(player, "worldguard.region.select." + id.toLowerCase());
}
final World world = player.getWorld();
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
Vector pt1 = cuboid.getMinimumPoint();
Vector pt2 = cuboid.getMaximumPoint();
CuboidSelection selection = new CuboidSelection(world, pt1, pt2);
final ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
final Vector pt1 = cuboid.getMinimumPoint();
final Vector pt2 = cuboid.getMaximumPoint();
final CuboidSelection selection = new CuboidSelection(world, pt1, pt2);
worldEdit.setSelection(player, selection);
sender.sendMessage(ChatColor.YELLOW + "Region selected as a cuboid.");
player.sendMessage(ChatColor.YELLOW + "Region selected as a cuboid.");
} else if (region instanceof ProtectedPolygonalRegion) {
ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
Polygonal2DSelection selection = new Polygonal2DSelection(world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(), poly2d.getMaximumPoint().getBlockY());
final ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
final Polygonal2DSelection selection = new Polygonal2DSelection(
world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(),
poly2d.getMaximumPoint().getBlockY()
);
worldEdit.setSelection(player, selection);
sender.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
player.sendMessage(ChatColor.YELLOW + "Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
throw new CommandException("Can't select global regions.");
} else {
throw new CommandException("Unknown region type: " + region.getClass().getCanonicalName());
}
}
@Command(aliases = {"info", "i"}, usage = "[world] <id>",
desc = "Get information about a region", min = 1, max = 2)
@Command(aliases = {"info", "i"}, usage = "[world] [id]", flags = "s",
desc = "Get information about a region", min = 0, max = 2)
public void info(CommandContext args, CommandSender sender) throws CommandException {
Player player = null;
LocalPlayer localPlayer = null;
World world;
String id;
// Get different values based on provided arguments
if (args.argsLength() == 1) {
player = plugin.checkPlayer(sender);
final LocalPlayer localPlayer;
final World world;
if (sender instanceof Player) {
final Player player = (Player) sender;
localPlayer = plugin.wrapPlayer(player);
world = player.getWorld();
id = args.getString(0).toLowerCase();
} else if (args.argsLength() < 2) {
throw new CommandException("A player is expected.");
} else {
localPlayer = null;
world = plugin.matchWorld(sender, args.getString(0));
}
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final String id;
// Get different values based on provided arguments
switch (args.argsLength()) {
case 0:
if (localPlayer == null) {
throw new CommandException("A player is expected.");
}
final Vector pt = localPlayer.getPosition();
final ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (set.size() == 0) {
throw new CommandException("No region ID specified and no region found at current location!");
}
id = set.iterator().next().getId();
break;
case 1:
id = args.getString(0).toLowerCase();
break;
default:
id = args.getString(1).toLowerCase();
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
if (!mgr.hasRegion(id)) {
final ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
}
ProtectedRegion region = mgr.getRegion(id);
displayRegionInfo(sender, localPlayer, region);
if (player != null) {
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.own");
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.member");
} else {
plugin.checkPermission(sender, "worldguard.region.info");
}
if (args.hasFlag('s')) {
selectRegion(plugin.checkPlayer(sender), localPlayer, region);
}
}
public void displayRegionInfo(CommandSender sender, final LocalPlayer localPlayer, ProtectedRegion region) throws CommandPermissionsException {
if (localPlayer == null) {
plugin.checkPermission(sender, "worldguard.region.info");
} else if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.own");
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.info.member");
} else {
plugin.checkPermission(sender, "worldguard.region.info");
}
DefaultDomain owners = region.getOwners();
DefaultDomain members = region.getMembers();
final String id = region.getId();
sender.sendMessage(ChatColor.YELLOW + "Region: " + id
+ ChatColor.GRAY + " (type: " + region.getTypeName() + ")");
if (!ProtectedRegion.isValidId(id)) {
sender.sendMessage(ChatColor.RED + "This region has an invalid ID. "
+ "Please ask the owner to delete it and recreate it.");
}
sender.sendMessage(ChatColor.BLUE + "Priority: " + region.getPriority());
StringBuilder s = new StringBuilder();
sender.sendMessage(ChatColor.YELLOW + "Region: " + id + ChatColor.GRAY + ", type: " + region.getTypeName() + ", " + ChatColor.BLUE + "Priority: " + region.getPriority());
boolean hasFlags = false;
final StringBuilder s = new StringBuilder(ChatColor.BLUE + "Flags: ");
for (Flag<?> flag : DefaultFlag.getFlags()) {
Object val = region.getFlag(flag);
if (val == null) {
continue;
}
if (s.length() > 0) {
s.append(", ");
}
s.append(flag.getName() + ": " + String.valueOf(val));
hasFlags = true;
}
if (hasFlags) {
sender.sendMessage(s.toString());
}
sender.sendMessage(ChatColor.BLUE + "Flags: " + s.toString());
sender.sendMessage(ChatColor.BLUE + "Parent: "
+ (region.getParent() == null ? "(none)" : region.getParent().getId()));
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Owners: "
+ owners.toUserFriendlyString());
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Members: "
+ members.toUserFriendlyString());
BlockVector min = region.getMinimumPoint();
BlockVector max = region.getMaximumPoint();
String c = "(" + min.getBlockX() + "," + min.getBlockY() + "," + min.getBlockZ() + ")";
c += " (" +max.getBlockX() + "," + max.getBlockY() + "," + max.getBlockZ() + ")";
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds: " + c);
if (region.getParent() != null) {
sender.sendMessage(ChatColor.BLUE + "Parent: " + region.getParent().getId());
}
final DefaultDomain owners = region.getOwners();
if (owners.size() != 0) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Owners: " + owners.toUserFriendlyString());
}
final DefaultDomain members = region.getMembers();
if (members.size() != 0) {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Members: " + members.toUserFriendlyString());
}
final BlockVector min = region.getMinimumPoint();
final BlockVector max = region.getMaximumPoint();
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Bounds:"
+ " (" + min.getBlockX() + "," + min.getBlockY() + "," + min.getBlockZ() + ")"
+ " (" + max.getBlockX() + "," + max.getBlockY() + "," + max.getBlockZ() + ")"
);
}
public class RegionEntry implements Comparable<RegionEntry>{
private final String id;
private final int index;
private boolean isOwner;
private boolean isMember;
public RegionEntry(String id, int index) {
this.id = id;
this.index = index;
}
@Override
public int compareTo(RegionEntry o) {
if (isOwner != o.isOwner) {
return isOwner ? 1 : -1;
}
if (isMember != o.isMember) {
return isMember ? 1 : -1;
}
return id.compareTo(o.id);
}
@Override
public String toString() {
if (isOwner) {
return (index + 1) + ". +" + id;
} else if (isMember) {
return (index + 1) + ". -" + id;
} else {
return (index + 1) + ". " + id;
}
}
}
@Command(aliases = {"list"}, usage = "[.player] [page] [world]",
desc = "Get a list of regions", max = 3)
// @CommandPermissions({"worldguard.region.list"})
//@CommandPermissions({"worldguard.region.list"})
public void list(CommandContext args, CommandSender sender) throws CommandException {
World world;
int page = 0;
int argl = 0;
int argOffset = 0;
String name = "";
boolean own = false;
LocalPlayer localPlayer = null;
final String senderName = sender.getName().toLowerCase();
if (args.argsLength() > 0 && args.getString(0).startsWith(".")) {
name = args.getString(0).substring(1).toLowerCase();
argl = 1;
if (name.equals("me") || name.isEmpty() ||
name.equals(plugin.checkPlayer(sender).getDisplayName().toLowerCase())) {
plugin.checkPermission(sender, "worldguard.region.list.own");
name = plugin.checkPlayer(sender).getDisplayName().toLowerCase();
localPlayer = plugin.wrapPlayer(plugin.checkPlayer(sender));
argOffset = 1;
if (name.equals("me") || name.isEmpty() || name.equals(senderName)) {
own = true;
}
}
if (!own)
plugin.checkPermission(sender, "worldguard.region.list");
if (args.argsLength() > 0 + argl) {
page = Math.max(0, args.getInteger(0 + argl) - 1);
// Make /rg list default to "own" mode if the "worldguard.region.list" permission is not given
if (!own && !plugin.hasPermission(sender, "worldguard.region.list")) {
own = true;
}
if (args.argsLength() > 1 + argl) {
world = plugin.matchWorld(sender, args.getString(1 + argl));
if (own) {
plugin.checkPermission(sender, "worldguard.region.list.own");
name = senderName;
localPlayer = plugin.wrapPlayer(plugin.checkPlayer(sender));
}
if (args.argsLength() > argOffset) {
page = Math.max(0, args.getInteger(argOffset) - 1);
}
if (args.argsLength() > 1 + argOffset) {
world = plugin.matchWorld(sender, args.getString(1 + argOffset));
} else {
world = plugin.checkPlayer(sender).getWorld();
}
int listSize = 10;
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
Map<String, ProtectedRegion> regions = mgr.getRegions();
final RegionManager mgr = plugin.getGlobalRegionManager().get(world);
final Map<String, ProtectedRegion> regions = mgr.getRegions();
int size = regions.size();
String[] regionIDList = new String[size];
List<RegionEntry> regionEntries = new ArrayList<RegionEntry>();
int index = 0;
boolean show = false;
String prefix = "";
for (String id : regions.keySet()) {
show = false;
prefix = "";
if (name.isEmpty()) {
show = true;
}
else {
RegionEntry entry = new RegionEntry(id, index++);
if (!name.isEmpty()) {
if (own) {
if (regions.get(id).isOwner(localPlayer)) {
show = true;
prefix += "+";
}
else if (regions.get(id).isMember(localPlayer)) {
show = true;
prefix += "-";
}
entry.isOwner = regions.get(id).isOwner(localPlayer);
entry.isMember = regions.get(id).isMember(localPlayer);
}
else {
if (regions.get(id).getOwners().getPlayers().contains(name)) {
show = true;
prefix += "+";
}
if (regions.get(id).getMembers().getPlayers().contains(name)) {
show = true;
prefix += "-";
}
entry.isOwner = regions.get(id).isOwner(name);
entry.isMember = regions.get(id).isMember(name);
}
if (!entry.isOwner && !entry.isMember) {
continue;
}
}
if (show) {
regionIDList[index] = prefix + " " + id;
index++;
}
regionEntries.add(entry);
}
if (!name.isEmpty())
regionIDList = Arrays.copyOf(regionIDList, index);
Arrays.sort(regionIDList);
size = index;
int pages = (int) Math.ceil(size / (float) listSize);
Collections.sort(regionEntries);
final int totalSize = regionEntries.size();
final int pageSize = 10;
final int pages = (int) Math.ceil(totalSize / (float) pageSize);
sender.sendMessage(ChatColor.RED
+ (name.equals("") ? "Regions (page " : "Regions for " + name + " (page ")
+ (page + 1) + " of " + pages + "):");
if (page < pages) {
for (int i = page * listSize; i < page * listSize + listSize; i++) {
if (i >= size) {
for (int i = page * pageSize; i < page * pageSize + pageSize; i++) {
if (i >= totalSize) {
break;
}
sender.sendMessage(ChatColor.YELLOW.toString() + (i + 1) +
"." + regionIDList[i]);
sender.sendMessage(ChatColor.YELLOW.toString() + regionEntries.get(i));
}
}
}
@Command(aliases = {"flag", "f"}, usage = "<id> <flag> [value]",
@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 {
@@ -668,23 +749,40 @@ public class RegionCommands {
} else {
plugin.checkPermission(sender, "worldguard.region.flag.flags."
+ foundFlag.getName() + "." + id.toLowerCase());
}
if (value != null) {
}
if (args.hasFlag('g')) {
String group = args.getFlag('g');
if (foundFlag.getRegionGroupFlag() == null) {
throw new CommandException("Region flag '" + foundFlag.getName()
+ "' does not have a group flag!");
}
try {
setFlag(region, foundFlag, sender, value);
setFlag(region, foundFlag.getRegionGroupFlag(), sender, group);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' set.");
+ "Region group flag for '" + foundFlag.getName() + "' set.");
} else {
// Clear the flag
region.setFlag(foundFlag, null);
if (value != null) {
try {
setFlag(region, foundFlag, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' cleared.");
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' set.");
} else {
// Clear the flag
region.setFlag(foundFlag, null);
sender.sendMessage(ChatColor.YELLOW
+ "Region flag '" + foundFlag.getName() + "' cleared.");
}
}
try {
@@ -717,11 +815,12 @@ public class RegionCommands {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setpriority.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -759,11 +858,16 @@ public class RegionCommands {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
throw new CommandException("Could not find a target region by that ID.");
}
id = region.getId();
if (args.argsLength() == 1) {
try {
region.setParent(null);
} catch (CircularInheritanceException e) {
} catch (CircularInheritanceException ignore) {
}
sender.sendMessage(ChatColor.YELLOW
@@ -772,10 +876,6 @@ public class RegionCommands {
String parentId = args.getString(1);
ProtectedRegion parent = mgr.getRegion(parentId);
if (region == null) {
throw new CommandException("Could not find a target region by that ID.");
}
if (parent == null) {
throw new CommandException("Could not find the parent region by that ID.");
}
@@ -789,11 +889,11 @@ public class RegionCommands {
}
if (parent.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.own." + id.toLowerCase());
plugin.checkPermission(sender, "worldguard.region.setparent.own." + parentId.toLowerCase());
} else if (parent.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.setparent.member." + id.toLowerCase());
plugin.checkPermission(sender, "worldguard.region.setparent.member." + parentId.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.setparent." + id.toLowerCase());
plugin.checkPermission(sender, "worldguard.region.setparent." + parentId.toLowerCase());
}
try {
@@ -826,7 +926,7 @@ public class RegionCommands {
String id = args.getString(0);
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
ProtectedRegion region = mgr.getRegion(id);
ProtectedRegion region = mgr.getRegionExact(id);
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
@@ -965,17 +1065,63 @@ public class RegionCommands {
AbstractDatabaseMigrator migrator = cls.getConstructor(WorldGuardPlugin.class).newInstance(plugin);
migrator.migrate();
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException ignore) {
} catch (SecurityException ignore) {
} catch (InstantiationException ignore) {
} catch (IllegalAccessException ignore) {
} catch (InvocationTargetException ignore) {
} catch (NoSuchMethodException ignore) {
} catch (MigrationException e) {
throw new CommandException("Error migrating database: " + e.getMessage());
}
sender.sendMessage(ChatColor.YELLOW + "Regions have been migrated successfuly.\n" +
sender.sendMessage(ChatColor.YELLOW + "Regions have been migrated successfully.\n" +
"If you wish to use the destination format as your new backend, please update your config and reload WorldGuard.");
}
@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);
final RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
String id = args.getString(0);
final ProtectedRegion region = mgr.getRegion(id);
if (region == null) {
if (!ProtectedRegion.isValidId(id)) {
throw new CommandException("Invalid region ID specified!");
}
throw new CommandException("A region with ID '" + id + "' doesn't exist.");
}
id = region.getId();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.teleport.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.teleport.member." + id.toLowerCase());
} else {
plugin.checkPermission(sender, "worldguard.region.teleport." + id.toLowerCase());
}
final Location teleportLocation;
if (args.hasFlag('s')) {
teleportLocation = region.getFlag(DefaultFlag.SPAWN_LOC);
if (teleportLocation == null) {
throw new CommandException("The region has no spawn point associated.");
}
} else {
teleportLocation = region.getFlag(DefaultFlag.TELE_LOC);
if (teleportLocation == null) {
throw new CommandException("The region has no teleport point associated.");
}
}
player.teleport(BukkitUtil.toLocation(teleportLocation));
sender.sendMessage("Teleported you to the region '" + id + "'.");
}
}
@@ -34,7 +34,7 @@ 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.util.RegionUtil;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
// @TODO: A lot of code duplication here! Need to fix.
@@ -61,7 +61,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.addmember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -70,7 +72,7 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.addmember." + id.toLowerCase());
}
RegionUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.addToDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
@@ -100,9 +102,11 @@ public class RegionMemberCommands {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
Boolean flag = region.getFlag(DefaultFlag.BUYABLE);
DefaultDomain owners = region.getOwners();
if (flag != null && flag == true && owners != null && owners.size() == 0) {
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)
@@ -121,7 +125,7 @@ public class RegionMemberCommands {
}
}
RegionUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.addToDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
@@ -150,7 +154,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removemember.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -159,7 +165,7 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.removemember." + id.toLowerCase());
}
RegionUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.removeFromDomain(region.getMembers(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
@@ -189,7 +195,9 @@ public class RegionMemberCommands {
if (region == null) {
throw new CommandException("Could not find a region by that ID.");
}
id = region.getId();
if (region.isOwner(localPlayer)) {
plugin.checkPermission(sender, "worldguard.region.removeowner.own." + id.toLowerCase());
} else if (region.isMember(localPlayer)) {
@@ -198,7 +206,7 @@ public class RegionMemberCommands {
plugin.checkPermission(sender, "worldguard.region.removeowner." + id.toLowerCase());
}
RegionUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
RegionDBUtil.removeFromDomain(region.getOwners(), args.getPaddedSlice(2, 0), 0);
sender.sendMessage(ChatColor.YELLOW
+ "Region '" + id + "' updated.");
@@ -31,9 +31,9 @@ public interface ChestProtection {
/**
* Returns whether a block is protected.
*
* @param block
* @param player
* @return
* @param block The block to check
* @param player The player to check
* @return Whether the block is protected for player
*/
public boolean isProtected(Block block, Player player);
@@ -41,26 +41,27 @@ public interface ChestProtection {
* Returns whether a location where a chest block is trying to be created
* is protected.
*
* @param block
* @param player
* @return
* @param block The block to check
* @param player The player to check
* @return Whether {@code player} can place a block at the specified block
*/
public boolean isProtectedPlacement(Block block, Player player);
/**
* Returns whether an adjacent chest is protected.
*
* @param searchBlock
* @param player
* @return
* @param searchBlock The block to check
* @param player The player to check
* @return Whether {@code searchBlock} is protected from access by {@code player}
*/
public boolean isAdjacentChestProtected(Block searchBlock, Player player);
/**
* Returns whether a material is a chest.
*
* @param material
* @return
*
* @param material The material to check
* @deprecated see {@link #isChest(int)}
* @return {@link #isChest(int)}
*/
@Deprecated
public boolean isChest(Material material);
@@ -68,8 +69,8 @@ public interface ChestProtection {
/**
* Returns whether a material is a chest.
*
* @param type
* @return
* @param type The type to check
* @return Whether type is a 'chest' (block that can be protected)
*/
public boolean isChest(int type);
@@ -127,23 +127,23 @@ public class SignChestProtection implements ChestProtection {
side = searchBlock;
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(-1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(1, 0, 0);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, -1);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
side = searchBlock.getRelative(0, 0, 1);
res = isProtected(side, player);
if (res != null && res == true) return res;
if (res != null && res) return res;
return false;
}
@@ -70,20 +70,26 @@ public class DefaultDomain implements Domain {
return players;
}
@Override
public boolean contains(LocalPlayer player) {
if (players.contains(player.getName().toLowerCase())) {
if (contains(player.getName())) {
return true;
}
for (String group : groups) {
if (player.hasGroup(group)) {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
return players.contains(playerName.toLowerCase());
}
public int size() {
return groups.size() + players.size();
}
@@ -5,9 +5,18 @@ import com.sk89q.worldguard.LocalPlayer;
public interface Domain {
/**
* Returns true if a domain contains a player.
*
* @param player
* @return
*
* @param player The player to check
* @return whether this domain contains {@code player}
*/
public boolean contains(LocalPlayer player);
boolean contains(LocalPlayer player);
/**
* Returns true if a domain contains a player.<br />
* This method doesn't check for groups!
*
* @param playerName The name of the player to check
* @return whether this domain contains a player by that name
*/
boolean contains(String playerName);
}
@@ -26,31 +26,42 @@ import com.sk89q.worldguard.LocalPlayer;
public class DomainCollection implements Domain {
private Set<Domain> domains;
public DomainCollection() {
domains = new LinkedHashSet<Domain>();
}
public void add(Domain domain) {
domains.add(domain);
}
public void remove(Domain domain) {
domains.remove(domain);
}
public int size() {
return domains.size();
}
@Override
public boolean contains(LocalPlayer player) {
for (Domain domain : domains) {
if (domain.contains(player)) {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
for (Domain domain : domains) {
if (domain.contains(playerName)) {
return true;
}
}
return false;
}
}
@@ -27,15 +27,15 @@ import com.sk89q.worldguard.LocalPlayer;
public class GroupDomain implements Domain {
private Set<String> groups;
public GroupDomain() {
this.groups = new LinkedHashSet<String>();
}
public GroupDomain(String[] groups) {
this.groups = new LinkedHashSet<String>(Arrays.asList(groups));
}
public void addGroup(String name) {
groups.add(name);
}
@@ -46,12 +46,16 @@ public class GroupDomain implements Domain {
return true;
}
}
return false;
}
@Override
public boolean contains(String playerName) {
return false; // GroupDomains can't contain player names.
}
public int size() {
return groups.size();
}
}
@@ -26,29 +26,33 @@ import com.sk89q.worldguard.LocalPlayer;
public class PlayerDomain implements Domain {
private Set<String> players;
public PlayerDomain() {
this.players = new HashSet<String>();
}
public PlayerDomain(String[] players) {
this.players = new HashSet<String>();
for (String name : players) {
this.players.add(name.toLowerCase());
}
}
public void addPlayer(String name) {
players.add(name.toLowerCase());
}
public boolean contains(LocalPlayer player) {
return players.contains(player.getName().toLowerCase());
return contains(player.getName());
}
@Override
public boolean contains(String playerName) {
return players.contains(playerName.toLowerCase());
}
public int size() {
return players.size();
}
}
@@ -29,6 +29,7 @@ import java.util.Set;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
@@ -52,8 +53,8 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Construct the object.
*
* @param applicable
* @param globalRegion
* @param applicable The regions contained in this set
* @param globalRegion The global region, set aside for special handling.
*/
public ApplicableRegionSet(Collection<ProtectedRegion> applicable,
ProtectedRegion globalRegion) {
@@ -64,19 +65,26 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Checks if a player can build in an area.
*
* @param player
* @param player The player to chec
* @return build ability
*/
public boolean canBuild(LocalPlayer player) {
return internalGetState(DefaultFlag.BUILD, player, null, null);
return internalGetState(DefaultFlag.BUILD, player, null);
}
public boolean canConstruct(LocalPlayer player) {
final RegionGroup flag = getFlag(DefaultFlag.CONSTRUCT, player);
return RegionGroupFlag.isMember(this, flag, player);
}
/**
* Checks if a player can use buttons and such in an area.
*
* @param player
* @param player The player to check
* @return able to use items
* @deprecated This method seems to be the opposite of its name
*/
@Deprecated
public boolean canUse(LocalPlayer player) {
return !allows(DefaultFlag.USE, player)
&& !canBuild(player);
@@ -93,7 +101,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, null, null);
return internalGetState(flag, null, null);
}
/**
@@ -108,7 +116,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
if (flag == DefaultFlag.BUILD) {
throw new IllegalArgumentException("Can't use build flag with allows()");
}
return internalGetState(flag, null, flag.getGroupFlag(), player);
return internalGetState(flag, null, player);
}
/**
@@ -149,12 +157,10 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
*
* @param flag flag to check
* @param player null to not check owners and members
* @param groupFlag group flag to check
* @param groupPlayer player to use for the group flag check
* @return
* @return the allow/deny state for the flag
*/
private boolean internalGetState(StateFlag flag, LocalPlayer player,
RegionGroupFlag groupFlag,
LocalPlayer groupPlayer) {
boolean found = false;
boolean hasFlagDefined = false;
@@ -229,10 +235,10 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
}
// Check group permissions
if (groupPlayer != null && groupFlag != null) {
RegionGroupFlag.RegionGroup group = region.getFlag(groupFlag);
if (groupPlayer != null && flag.getRegionGroupFlag() != null) {
RegionGroup group = region.getFlag(flag.getRegionGroupFlag());
if (group == null) {
group = groupFlag.getDefault();
group = flag.getRegionGroupFlag().getDefault();
}
if (!RegionGroupFlag.isMember(region, group, groupPlayer)) {
continue;
@@ -276,16 +282,16 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
found = true;
}
return found == false ? def :
return !found ? def :
(allowed || (player != null && needsClear.size() == 0));
}
/**
* Clear a region's parents for isFlagAllowed().
*
* @param needsClear
* @param hasCleared
* @param region
* @param needsClear The regions that should be cleared
* @param hasCleared The regions already cleared
* @param region The region to start from
*/
private void clearParents(Set<ProtectedRegion> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
@@ -300,15 +306,25 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
}
}
/**
* @see #getFlag(com.sk89q.worldguard.protection.flags.Flag, com.sk89q.worldguard.LocalPlayer)
* @param flag flag to check
* @return value of the flag
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
return getFlag(flag, null);
}
/**
* Gets the value of a flag. Do not use this for state flags
* (use {@link #allows(StateFlag, LocalPlayer)} for that).
*
* @param flag flag to check
* @param groupPlayer player to check {@link RegionGroup}s against
* @return value of the flag
* @throws IllegalArgumentException if a StateFlag is given
*/
public <T extends Flag<V>, V> V getFlag(T flag) {
public <T extends Flag<V>, V> V getFlag(T flag, LocalPlayer groupPlayer) {
/*
if (flag instanceof StateFlag) {
throw new IllegalArgumentException("Cannot use StateFlag with getFlag()");
@@ -331,6 +347,17 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
break;
}
// Check group permissions
if (groupPlayer != null && flag.getRegionGroupFlag() != null) {
RegionGroup group = region.getFlag(flag.getRegionGroupFlag());
if (group == null) {
group = flag.getRegionGroupFlag().getDefault();
}
if (!RegionGroupFlag.isMember(region, group, groupPlayer)) {
continue;
}
}
if (hasCleared.contains(region)) {
// Already cleared, so do nothing
} else if (region.getFlag(flag) != null){
@@ -358,9 +385,9 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Clear a region's parents for getFlag().
*
* @param needsClear
* @param hasCleared
* @param region
* @param needsClear The regions that should be cleared
* @param hasCleared The regions already cleared
* @param region The region to start from
*/
private void clearParents(Map<ProtectedRegion, ?> needsClear,
Set<ProtectedRegion> hasCleared, ProtectedRegion region) {
@@ -378,7 +405,7 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Get the number of regions that are included.
*
* @return
* @return the size of this ApplicbleRegionSet
*/
public int size() {
return applicable.size();
@@ -386,8 +413,6 @@ public class ApplicableRegionSet implements Iterable<ProtectedRegion> {
/**
* Get an iterator of affected regions.
*
* @return
*/
public Iterator<ProtectedRegion> iterator() {
return applicable.iterator();
@@ -21,8 +21,9 @@ package com.sk89q.worldguard.protection;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.World;
@@ -75,7 +76,7 @@ public class GlobalRegionManager {
/**
* Construct the object.
*
* @param plugin
* @param plugin The plugin instance
*/
public GlobalRegionManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
@@ -95,8 +96,8 @@ public class GlobalRegionManager {
/**
* Get the path for a world's regions file.
*
* @param name
* @return
* @param name The name of the world
* @return The region file path for a world's region file
*/
protected File getPath(String name) {
return new File(plugin.getDataFolder(),
@@ -106,13 +107,12 @@ public class GlobalRegionManager {
/**
* Unload region information for a world.
*
* @param name
* @param name The name of the world to unload
*/
public void unload(String name) {
RegionManager manager = managers.get(name);
RegionManager manager = managers.remove(name);
if (manager != null) {
managers.remove(name);
lastModified.remove(name);
}
}
@@ -128,12 +128,12 @@ public class GlobalRegionManager {
/**
* Load region information for a world.
*
* @param world
* @return
* @param world The world to load a RegionManager for
* @return the loaded RegionManager
*/
public RegionManager load(World world) {
String name = world.getName();
ProtectionDatabase database = null;
ProtectionDatabase database;
File file = null;
try {
@@ -165,10 +165,10 @@ public class GlobalRegionManager {
logStr += "file \"" + file + "\" ";
}
plugin.getLogger().info(logStr + " : " + e.getMessage());
plugin.getLogger().log(Level.SEVERE, logStr + " : " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
plugin.getLogger().info("Error loading regions for world \""
} catch (FileNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "Error loading regions for world \""
+ name + "\": " + e.toString() + "\n\t" + e.getMessage());
e.printStackTrace();
}
@@ -211,7 +211,7 @@ public class GlobalRegionManager {
load(world);
}
}
} catch (Exception e) {
} catch (Exception ignore) {
}
}
}
@@ -219,8 +219,8 @@ public class GlobalRegionManager {
/**
* Get the region manager for a particular world.
*
* @param world
* @return
* @param world The world to get a RegionManager for
* @return The region manager.
*/
public RegionManager get(World world) {
RegionManager manager = managers.get(world.getName());
@@ -235,9 +235,9 @@ public class GlobalRegionManager {
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
* @param player The player to check
* @param world The world to check for
* @return Whether {@code player} has bypass permission for {@code world}
*/
public boolean hasBypass(LocalPlayer player, World world) {
return player.hasPermission("worldguard.region.bypass."
@@ -247,21 +247,21 @@ public class GlobalRegionManager {
/**
* Returns whether the player can bypass.
*
* @param player
* @param world
* @return
* @param player The player to check
* @param world The world to check
* @return Whether {@code player} has bypass permission for {@code world}
*/
public boolean hasBypass(Player player, World world) {
return plugin.hasPermission(player, "worldguard.region.bypass."
+ world.getName());
+ world.getName());
}
/**
* Check if a player has permission to build at a block.
*
* @param player
* @param block
* @return
* @param player The player to check
* @param block The block to check at
* @return Whether {@code player} can build at {@code block}'s location
*/
public boolean canBuild(Player player, Block block) {
return canBuild(player, block.getLocation());
@@ -270,9 +270,9 @@ public class GlobalRegionManager {
/**
* Check if a player has permission to build at a location.
*
* @param player
* @param loc
* @return
* @param player The player to check
* @param loc The location to check
* @return Whether {@code player} can build at {@code loc}
*/
public boolean canBuild(Player player, Location loc) {
World world = loc.getWorld();
@@ -296,14 +296,56 @@ public class GlobalRegionManager {
return true;
}
public boolean canConstruct(Player player, Block block) {
return canConstruct(player, block.getLocation());
}
public boolean canConstruct(Player player, Location loc) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
if (!worldConfig.useRegions) {
return true;
}
LocalPlayer localPlayer = plugin.wrapPlayer(player);
if (!hasBypass(player, world)) {
RegionManager mgr = get(world);
final ApplicableRegionSet applicableRegions = mgr.getApplicableRegions(BukkitUtil.toVector(loc));
if (!applicableRegions.canBuild(localPlayer)) {
return false;
}
if (!applicableRegions.canConstruct(localPlayer)) {
return false;
}
}
return true;
}
/**
* Checks to see whether a flag is allowed.
*
* @param flag
* @param loc
* @return
* @see #allows(com.sk89q.worldguard.protection.flags.StateFlag, org.bukkit.Location, com.sk89q.worldguard.LocalPlayer)
* @param flag The flag to check
* @param loc The location to check the flag at
* @return Whether the flag is allowed
*/
public boolean allows(StateFlag flag, Location loc) {
return allows(flag, loc, null);
}
/**
* Checks to see whether a flag is allowed.
*
* @param flag The flag to check
* @param loc The location to check the flag at
* @param player The player to check for the flag's {@link com.sk89q.worldguard.protection.flags.RegionGroup}
* @return Whether the flag is allowed
*/
public boolean allows(StateFlag flag, Location loc, LocalPlayer player) {
World world = loc.getWorld();
WorldConfiguration worldConfig = config.get(world);
@@ -312,6 +354,6 @@ public class GlobalRegionManager {
}
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
return mgr.getApplicableRegions(toVector(loc)).allows(flag);
return mgr.getApplicableRegions(toVector(loc)).allows(flag, player);
}
}
@@ -48,6 +48,21 @@ import com.sk89q.worldguard.util.ArrayReader;
* @author sk89q
*/
public class CSVDatabase extends AbstractProtectionDatabase {
private static final Map<String, StateFlag> legacyFlagCodes = new HashMap<String, StateFlag>();
static {
legacyFlagCodes.put("z", DefaultFlag.PASSTHROUGH);
legacyFlagCodes.put("b", DefaultFlag.BUILD);
legacyFlagCodes.put("p", DefaultFlag.PVP);
legacyFlagCodes.put("m", DefaultFlag.MOB_DAMAGE);
legacyFlagCodes.put("c", DefaultFlag.CREEPER_EXPLOSION);
legacyFlagCodes.put("t", DefaultFlag.TNT);
legacyFlagCodes.put("l", DefaultFlag.LIGHTER);
legacyFlagCodes.put("f", DefaultFlag.FIRE_SPREAD);
legacyFlagCodes.put("F", DefaultFlag.LAVA_FIRE);
legacyFlagCodes.put("C", DefaultFlag.CHEST_ACCESS);
}
private final Logger logger;
/**
@@ -63,7 +78,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
* Construct the database with a path to a file. No file is read or
* written at this time.
*
* @param file
* @param file The file in CSV format containing the region database
* @param logger The logger to log errors to
*/
public CSVDatabase(File file, Logger logger) {
this.file = file;
@@ -77,9 +93,6 @@ public class CSVDatabase extends AbstractProtectionDatabase {
throw new UnsupportedOperationException("CSV format is no longer implemented");
}
/**
* Load the database from file.
*/
public void load() throws ProtectionDatabaseException {
Map<String,ProtectedRegion> regions =
new HashMap<String,ProtectedRegion>();
@@ -193,8 +206,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* Used to parse the specified domain in the CSV file.
*
* @param data
* @return
* @param data The domain data as a string
* @return The domain data as a DefaultDomain
*/
private DefaultDomain parseDomains(String data) {
if (data == null) {
@@ -236,7 +249,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* Used to parse the list of flags.
*
* @param data
* @param data The flag data in string format
*/
private void parseFlags(ProtectedRegion region, String data) {
if (data == null) {
@@ -267,7 +280,7 @@ public class CSVDatabase extends AbstractProtectionDatabase {
flagStr = String.valueOf(k);
}
StateFlag flag = DefaultFlag.getLegacyFlag(flagStr);
StateFlag flag = legacyFlagCodes.get(flagStr);
if (flag != null) {
region.setFlag(flag, curState);
} else {
@@ -321,8 +334,8 @@ public class CSVDatabase extends AbstractProtectionDatabase {
/**
* Returns a null if a string is null or empty.
*
* @param str
* @return
* @param str The string to format
* @return null if the string is empty or null, otherwise the provided string
*/
protected String nullEmptyString(String str) {
if (str == null) {
@@ -334,18 +347,10 @@ public class CSVDatabase extends AbstractProtectionDatabase {
}
}
/**
* Get a list of protected regions.
*
* @return
*/
public Map<String,ProtectedRegion> getRegions() {
return regions;
}
/**
* Get a list of protected regions.
*/
public void setRegions(Map<String,ProtectedRegion> regions) {
this.regions = regions;
}
@@ -0,0 +1,20 @@
package com.sk89q.worldguard.protection.databases;
import com.sk89q.worldguard.util.FatalConfigurationLoadingException;
public class InvalidTableFormatException extends FatalConfigurationLoadingException {
private static final long serialVersionUID = 1L;
protected String updateFile;
public InvalidTableFormatException(String updateFile) {
super();
this.updateFile = updateFile;
}
public String toString() {
return "You need to update your database to the latest version.\n" +
"\t\tPlease see " + this.updateFile;
}
}
@@ -70,6 +70,18 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
try {
connect();
try {
// Test if the database is up to date, if not throw a critical error
PreparedStatement verTest = this.conn.prepareStatement(
"SELECT `world_id` FROM `region_cuboid` LIMIT 0,1;"
);
verTest.execute();
} catch (SQLException ex) {
throw new InvalidTableFormatException(
"region_storage_update_20110325.sql"
);
}
PreparedStatement worldStmt = conn.prepareStatement(
"SELECT `id` FROM " +
@@ -113,6 +125,20 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
}
private void connect() throws SQLException {
if (conn != null) {
// Make a dummy query to check the connnection is alive.
try {
conn.prepareStatement("SELECT 1;").execute();
} catch (SQLException ex) {
// Test if the dummy query failed because the connection is dead,
// and if it is mark the connection as closed (the MySQL Driver
// does not ensure that the connection is marked as closed unless
// the close() method has been called.
if ("08S01".equals(ex.getSQLState())) {
conn.close();
}
}
}
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(config.sqlDsn, config.sqlUsername, config.sqlPassword);
}
@@ -126,7 +152,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`region_flag`.`flag`, " +
"`region_flag`.`value` " +
"FROM `region_flag` " +
"WHERE `region_flag`.`region_id` = ? "
"WHERE `region_flag`.`region_id` = ? " +
"AND `region_flag`.`world_id` = " + this.worldDbId
);
flagsStatement.setString(1, region.getId().toLowerCase());
@@ -178,7 +205,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"LEFT JOIN `user` ON ( " +
"`region_players`.`user_id` = " +
"`user`.`id`) " +
"WHERE `region_players`.`region_id` = ? "
"WHERE `region_players`.`region_id` = ? " +
"AND `region_players`.`world_id` = " + this.worldDbId
);
usersStatement.setString(1, region.getId().toLowerCase());
@@ -203,7 +231,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"LEFT JOIN `group` ON ( " +
"`region_groups`.`group_id` = " +
"`group`.`id`) " +
"WHERE `region_groups`.`region_id` = ? "
"WHERE `region_groups`.`region_id` = ? " +
"AND `region_groups`.`world_id` = " + this.worldDbId
);
groupsStatement.setString(1, region.getId().toLowerCase());
@@ -235,7 +264,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region` " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`type` = 'global' " +
"AND `region`.`world_id` = ? "
);
@@ -289,9 +319,11 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region_cuboid` " +
"LEFT JOIN `region` " +
"ON (`region_cuboid`.`region_id` = `region`.`id`) " +
"ON (`region_cuboid`.`region_id` = `region`.`id` " +
"AND `region_cuboid`.`world_id` = `region`.`world_id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`world_id` = ? "
);
@@ -358,9 +390,11 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`parent`.`id` AS `parent` " +
"FROM `region_poly2d` " +
"LEFT JOIN `region` " +
"ON (`region_poly2d`.`region_id` = `region`.`id`) " +
"ON (`region_poly2d`.`region_id` = `region`.`id` " +
"AND `region_poly2d`.`world_id` = `region`.`world_id`) " +
"LEFT JOIN `region` AS `parent` " +
"ON (`region`.`parent` = `parent`.`id`) " +
"ON (`region`.`parent` = `parent`.`id` " +
"AND `region`.`world_id` = `parent`.`world_id`) " +
"WHERE `region`.`world_id` = ? "
);
@@ -372,7 +406,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`region_poly2d_point`.`x`, " +
"`region_poly2d_point`.`z` " +
"FROM `region_poly2d_point` " +
"WHERE `region_poly2d_point`.`region_id` = ? "
"WHERE `region_poly2d_point`.`region_id` = ? " +
"AND `region_poly2d_point`.`world_id` = " + this.worldDbId
);
while (poly2dResultSet.next()) {
@@ -663,7 +698,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement setParentStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`parent` = ? " +
"WHERE `id` = ? "
"WHERE `id` = ? AND `world_id` = " + this.worldDbId
);
setParentStatement.setString(1, entry.getValue().getParent().getId().toLowerCase());
@@ -694,7 +729,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updateFlags(ProtectedRegion region) throws SQLException {
PreparedStatement clearCurrentFlagStatement = this.conn.prepareStatement(
"DELETE FROM `region_flag` " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearCurrentFlagStatement.setString(1, region.getId().toLowerCase());
@@ -709,9 +745,10 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"INSERT INTO `region_flag` ( " +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`flag`, " +
"`value` " +
") VALUES (null, ?, ?, ?)"
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
insertFlagStatement.setString(1, region.getId().toLowerCase());
@@ -734,6 +771,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement deleteUsersForRegion = this.conn.prepareStatement(
"DELETE FROM `region_players` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId + " " +
"AND `owner` = ?"
);
@@ -743,7 +781,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertUsersForRegion = this.conn.prepareStatement(
"INSERT INTO `region_players` " +
"(`region_id`, `user_id`, `owner`) VALUES (?, ?, ?)"
"(`region_id`, `world_id`, `user_id`, `owner`) " +
"VALUES (?, " + this.worldDbId + ", ?, ?)"
);
Map<String,Integer> players = getUserIds(domain.getPlayers().toArray(new String[0]));
@@ -759,6 +798,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement deleteGroupsForRegion = this.conn.prepareStatement(
"DELETE FROM `region_groups` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId + " " +
"AND `owner` = ?"
);
@@ -768,7 +808,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertGroupsForRegion = this.conn.prepareStatement(
"INSERT INTO `region_groups` " +
"(`region_id`, `group_id`, `owner`) VALUES (?, ?, ?)"
"(`region_id`, `world_id`, `group_id`, `owner`) " +
"VALUES (?, " + this.worldDbId + ", ?, ?)"
);
Map<String,Integer> groups = getGroupIds(domain.getGroups().toArray(new String[0]));
@@ -795,12 +836,13 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`type`, " +
"`priority`, " +
"`parent` " +
") VALUES (?, " + this.worldDbId + ", ?, ?, null)"
") VALUES (?, ?, ?, ?, null)"
);
insertRegionStatement.setString(1, region.getId().toLowerCase());
insertRegionStatement.setString(2, type);
insertRegionStatement.setInt(3, region.getPriority());
insertRegionStatement.setInt(2, this.worldDbId);
insertRegionStatement.setString(3, type);
insertRegionStatement.setInt(4, region.getPriority());
insertRegionStatement.execute();
@@ -816,13 +858,14 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertCuboidRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_cuboid` (" +
"`region_id`, " +
"`world_id`, " +
"`min_z`, " +
"`min_y`, " +
"`min_x`, " +
"`max_z`, " +
"`max_y`, " +
"`max_x` " +
") VALUES (?, ?, ?, ?, ?, ?, ?)"
") VALUES (?, " + this.worldDbId + ", ?, ?, ?, ?, ?, ?)"
);
BlockVector min = region.getMinimumPoint();
@@ -845,9 +888,10 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
PreparedStatement insertPoly2dRegionStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d` (" +
"`region_id`, " +
"`world_id`, " +
"`max_y`, " +
"`min_y` " +
") VALUES (?, ?, ?)"
") VALUES (?, " + this.worldDbId + ", ?, ?)"
);
insertPoly2dRegionStatement.setString(1, region.getId().toLowerCase());
@@ -862,7 +906,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updatePoly2dPoints(ProtectedPolygonalRegion region) throws SQLException {
PreparedStatement clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
@@ -873,9 +918,10 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, ?, ?)"
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
for (BlockVector2D point : region.getPoints()) {
@@ -894,7 +940,7 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
private void updateRegion(ProtectedRegion region, String type) throws SQLException {
PreparedStatement updateRegionStatement = this.conn.prepareStatement(
"UPDATE `region` SET " +
"`priority` = ? WHERE `id` = ? "
"`priority` = ? WHERE `id` = ? AND `world_id` = " + this.worldDbId
);
updateRegionStatement.setInt(1, region.getPriority());
@@ -919,7 +965,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"`max_z` = ?, " +
"`max_y` = ?, " +
"`max_x` = ? " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
BlockVector min = region.getMinimumPoint();
@@ -943,7 +990,8 @@ public class MySQLDatabase extends AbstractProtectionDatabase {
"UPDATE `region_poly2d` SET " +
"`max_y` = ?, " +
"`min_y` = ? " +
"WHERE `region_id` = ? "
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
updatePoly2dRegionStatement.setInt(1, region.getMaximumPoint().getBlockY());
@@ -34,39 +34,39 @@ public interface ProtectionDatabase {
* Load the list of regions. The method should not modify the list returned
* by getRegions() unless the load finishes successfully.
*
* @throws ProtectionDatabaseException
* @throws ProtectionDatabaseException when an error occurs
*/
public void load() throws ProtectionDatabaseException;
/**
* Save the list of regions.
*
* @throws ProtectionDatabaseException
* @throws ProtectionDatabaseException when an error occurs
*/
public void save() throws ProtectionDatabaseException;
/**
* Load the list of regions into a region manager.
*
* @param manager
* @throws ProtectionDatabaseException
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
public void load(RegionManager manager) throws ProtectionDatabaseException;
/**
* Save the list of regions from a region manager.
*
* @param manager
* @throws ProtectionDatabaseException
* @param manager The manager to load regions into
* @throws ProtectionDatabaseException when an error occurs
*/
public void save(RegionManager manager) throws ProtectionDatabaseException;
/**
* Get a list of regions.
*
* @return
* @return the regions loaded by this ProtectionDatabase
*/
public Map<String,ProtectedRegion> getRegions();
/**
* Set the list of regions.
*
* @param regions
* @param regions The regions to be applied to this ProtectionDatabase
*/
public void setRegions(Map<String,ProtectedRegion> regions);
}
@@ -32,18 +32,18 @@ import com.sk89q.worldguard.domains.DefaultDomain;
* @author sk89q
*/
public class RegionDBUtil {
private static Pattern groupPattern = Pattern.compile("^[gG]:(.+)$");
private static Pattern groupPattern = Pattern.compile("(?i)^[G]:(.+)$");
private RegionDBUtil() {
}
/**
* Parse a group/player DefaultDomain specification for areas.
* Add the given names to {@code domain}
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain to add to
* @param split The {@link String[]} containing names to add to {@code domain}
* @param startIndex The beginning index in the array
*/
public static void addToDomain(DefaultDomain domain, String[] split,
int startIndex) {
@@ -59,11 +59,11 @@ public class RegionDBUtil {
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* Remove the given names from {@code domain}
*
* @param domain The domain to remove from
* @param split The {@link String[]} containing names to remove from {@code domain}
* @param startIndex The beginning index in the array
*/
public static void removeFromDomain(DefaultDomain domain, String[] split,
int startIndex) {
@@ -81,9 +81,9 @@ public class RegionDBUtil {
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
* @param split The array of names to add
* @param startIndex The beginning index in the array
* @return The resulting DefaultDomain
*/
public static DefaultDomain parseDomainString(String[] split, int startIndex) {
DefaultDomain domain = new DefaultDomain();
@@ -104,8 +104,8 @@ public class RegionDBUtil {
/**
* Creates a comma separated list of PreparedStatement place holders
*
* @param length
* @return
* @param length The number of wildcards to create
* @return A string with {@code length} wildcards for usage in a PreparedStatement
*/
public static String preparePlaceHolders(int length) {
StringBuilder builder = new StringBuilder();
@@ -121,9 +121,9 @@ public class RegionDBUtil {
/**
* Adds all of the parsed values to the PreparedStatement
*
* @param preparedStatement
* @param values
* @throws SQLException
* @param preparedStatement The preparedStanement to add to
* @param values The values to set
* @throws SQLException see {@link PreparedStatement#setString(int, String)}
*/
public static void setValues(PreparedStatement preparedStatement, String... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
@@ -165,6 +165,13 @@ public class YAMLDatabase extends AbstractProtectionDatabase {
if (o != null) {
setFlag(region, flag, o);
}
if (flag.getRegionGroupFlag() != null) {
Object o2 = flagsData.getProperty(flag.getRegionGroupFlag().getName());
if (o2 != null) {
setFlag(region, flag.getRegionGroupFlag(), o2);
}
}
}
}
@@ -0,0 +1,82 @@
// $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.protection.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
/**
* This event is fired when PVP is disallowed between players due to a "pvp deny" flag.
* Cancelling this event allows the PVP in spite of this.
*
* @author Score_Under
*/
public class DisallowedPVPEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private final Player attacker;
private final Player defender;
private final EntityDamageByEntityEvent event;
public DisallowedPVPEvent(final Player attacker, final Player defender, EntityDamageByEntityEvent event) {
this.attacker = attacker;
this.defender = defender;
this.event = event;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* @return the attacking player.
*/
public Player getAttacker() {
return attacker;
}
/**
* @return the defending player.
*/
public Player getDefender() {
return defender;
}
public EntityDamageByEntityEvent getCause() {
return event;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -27,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class BooleanFlag extends Flag<Boolean> {
public BooleanFlag(String name, char legacyCode) {
super(name, legacyCode);
public BooleanFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public BooleanFlag(String name) {
@@ -27,9 +27,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class CommandStringFlag extends Flag<String> {
public CommandStringFlag(String name, char legacyCode) {
super(name, legacyCode);
public CommandStringFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public CommandStringFlag(String name) {
@@ -19,7 +19,8 @@
package com.sk89q.worldguard.protection.flags;
import org.bukkit.entity.CreatureType;
import org.bukkit.GameMode;
import org.bukkit.entity.EntityType;
/**
*
@@ -27,21 +28,22 @@ import org.bukkit.entity.CreatureType;
*/
public final class DefaultFlag {
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", 'z', false);
public static final StateFlag BUILD = new StateFlag("build", 'b', true);
public static final StateFlag PVP = new StateFlag("pvp", 'p', true);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", 'm', true);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true);
public static final StateFlag CREEPER_EXPLOSION = new StateFlag("creeper-explosion", 'c', true);
public static final StateFlag PASSTHROUGH = new StateFlag("passthrough", false, RegionGroup.ALL);
public static final StateFlag BUILD = new StateFlag("build", true, RegionGroup.NON_MEMBERS);
public static final RegionGroupFlag CONSTRUCT = new RegionGroupFlag("construct", RegionGroup.MEMBERS);
public static final StateFlag PVP = new StateFlag("pvp", true, RegionGroup.ALL);
public static final StateFlag MOB_DAMAGE = new StateFlag("mob-damage", true, RegionGroup.ALL);
public static final StateFlag MOB_SPAWNING = new StateFlag("mob-spawning", true, RegionGroup.ALL);
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);
public static final StateFlag GHAST_FIREBALL = new StateFlag("ghast-fireball", true, RegionGroup.ALL);
public static final StateFlag SLEEP = new StateFlag("sleep", true);
public static final StateFlag TNT = new StateFlag("tnt", 't', true);
public static final StateFlag LIGHTER = new StateFlag("lighter", 'l', true);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", 'f', true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", 'F', true);
public static final StateFlag TNT = new StateFlag("tnt", true, RegionGroup.ALL);
public static final StateFlag LIGHTER = new StateFlag("lighter", true, RegionGroup.ALL);
public static final StateFlag FIRE_SPREAD = new StateFlag("fire-spread", true);
public static final StateFlag LAVA_FIRE = new StateFlag("lava-fire", true);
public static final StateFlag LIGHTNING = new StateFlag("lightning", true);
public static final StateFlag CHEST_ACCESS = new StateFlag("chest-access", 'C', false);
public static final StateFlag CHEST_ACCESS = new StateFlag("chest-access", false);
public static final StateFlag WATER_FLOW = new StateFlag("water-flow", true);
public static final StateFlag LAVA_FLOW = new StateFlag("lava-flow", true);
public static final StateFlag USE = new StateFlag("use", true);
@@ -56,54 +58,52 @@ public final class DefaultFlag {
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 ENDER_BUILD = new StateFlag("enderman-grief", true);
public static final StateFlag INVINCIBILITY = new StateFlag("invincible", false);
public static final StateFlag EXP_DROPS = new StateFlag("exp-drops", 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);
public static final StateFlag SEND_CHAT = new StateFlag("send-chat", true);
public static final StateFlag RECEIVE_CHAT = new StateFlag("receive-chat", true);
public static final StateFlag ENTRY = new StateFlag("entry", true);
public static final RegionGroupFlag ENTRY_PERM = new RegionGroupFlag("entry-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StateFlag EXIT = new StateFlag("exit", true);
public static final RegionGroupFlag EXIT_PERM = new RegionGroupFlag("exit-group", RegionGroupFlag.RegionGroup.NON_MEMBERS);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting");
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell");
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter");
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave");
public static final SetFlag<CreatureType> DENY_SPAWN = new SetFlag<CreatureType>("deny-spawn", new CreatureTypeFlag(null));
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay");
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount");
public static final IntegerFlag MIN_HEAL = new IntegerFlag("heal-min-health");
public static final IntegerFlag MAX_HEAL = new IntegerFlag("heal-max-health");
public static final IntegerFlag FEED_DELAY = new IntegerFlag("feed-delay");
public static final IntegerFlag FEED_AMOUNT = new IntegerFlag("feed-amount");
public static final IntegerFlag MIN_FOOD = new IntegerFlag("feed-min-hunger");
public static final IntegerFlag MAX_FOOD = new IntegerFlag("feed-max-hunger");
public static final VectorFlag TELE_LOC = new VectorFlag("teleport");
public static final RegionGroupFlag TELE_PERM = new RegionGroupFlag("teleport-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final VectorFlag SPAWN_LOC = new VectorFlag("spawn");
public static final RegionGroupFlag SPAWN_PERM = new RegionGroupFlag("spawn-group", RegionGroupFlag.RegionGroup.MEMBERS);
public static final StateFlag ITEM_DROP = new StateFlag("item-drop", true);
public static final StateFlag ENTITY_PAINTING_DESTROY = new StateFlag("entity-painting-destroy", true);
public static final StateFlag POTION_SPLASH = new StateFlag("potion-splash", true);
public static final StringFlag GREET_MESSAGE = new StringFlag("greeting", RegionGroup.ALL);
public static final StringFlag FAREWELL_MESSAGE = new StringFlag("farewell", RegionGroup.ALL);
public static final BooleanFlag NOTIFY_ENTER = new BooleanFlag("notify-enter", RegionGroup.ALL);
public static final BooleanFlag NOTIFY_LEAVE = new BooleanFlag("notify-leave", RegionGroup.ALL);
public static final SetFlag<EntityType> DENY_SPAWN = new SetFlag<EntityType>("deny-spawn", RegionGroup.ALL, new EntityTypeFlag(null));
public static final EnumFlag<GameMode> GAME_MODE = new EnumFlag<GameMode>("game-mode", GameMode.class, RegionGroup.ALL);
public static final IntegerFlag HEAL_DELAY = new IntegerFlag("heal-delay", RegionGroup.ALL);
public static final IntegerFlag HEAL_AMOUNT = new IntegerFlag("heal-amount", RegionGroup.ALL);
public static final IntegerFlag MIN_HEAL = new IntegerFlag("heal-min-health", RegionGroup.ALL);
public static final IntegerFlag MAX_HEAL = new IntegerFlag("heal-max-health", RegionGroup.ALL);
public static final IntegerFlag FEED_DELAY = new IntegerFlag("feed-delay", RegionGroup.ALL);
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 LocationFlag TELE_LOC = new LocationFlag("teleport", RegionGroup.MEMBERS);
public static final LocationFlag SPAWN_LOC = new LocationFlag("spawn", RegionGroup.MEMBERS);
public static final BooleanFlag BUYABLE = new BooleanFlag("buyable");
public static final DoubleFlag PRICE = new DoubleFlag("price");
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", new CommandStringFlag(null));
public static final SetFlag<String> BLOCKED_CMDS = new SetFlag<String>("blocked-cmds", RegionGroup.ALL, new CommandStringFlag(null));
public static final SetFlag<String> ALLOWED_CMDS = new SetFlag<String>("allowed-cmds", RegionGroup.ALL, new CommandStringFlag(null));
public static final Flag<?>[] flagsList = new Flag<?>[] {
PASSTHROUGH, BUILD, PVP, CHEST_ACCESS, PISTONS,
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, ENDERDRAGON_BLOCK_DAMAGE, GHAST_FIREBALL, ENDER_BUILD,
GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER, NOTIFY_LEAVE,
EXIT, EXIT_PERM, ENTRY, ENTRY_PERM, LIGHTNING,
EXIT, ENTRY, LIGHTNING, ENTITY_PAINTING_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,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD,
SNOW_FALL, SNOW_MELT, ICE_FORM, ICE_MELT, GAME_MODE,
MUSHROOMS, LEAF_DECAY, GRASS_SPREAD, SEND_CHAT, RECEIVE_CHAT,
FIRE_SPREAD, LAVA_FIRE, LAVA_FLOW, WATER_FLOW,
TELE_LOC, TELE_PERM, SPAWN_LOC, SPAWN_PERM,
TELE_LOC, SPAWN_LOC, POTION_SPLASH,
BLOCKED_CMDS, ALLOWED_CMDS, PRICE, BUYABLE,
};
static {
ENTRY.setGroupFlag(ENTRY_PERM);
EXIT.setGroupFlag(EXIT_PERM);
}
private DefaultFlag() {
}
@@ -111,20 +111,4 @@ public final class DefaultFlag {
public static Flag<?>[] getFlags() {
return flagsList;
}
/**
* Get the legacy flag.
*
* @param flagString
* @return null if not found
*/
public static StateFlag getLegacyFlag(String flagString) {
for (Flag<?> flag : flagsList) {
if (flag instanceof StateFlag && flagString.equals(String.valueOf(flag.getLegacyCode()))) {
return (StateFlag) flag;
}
}
return null;
}
}
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
public class DoubleFlag extends Flag<Double> {
public DoubleFlag(String name, char legacyCode) {
super(name, legacyCode);
public DoubleFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public DoubleFlag(String name) {
@@ -18,28 +18,28 @@
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.EntityType;
/**
* Represents a creature type.
* Represents an entity type.
*
* @author sk89q
*/
public class CreatureTypeFlag extends EnumFlag<CreatureType> {
public class EntityTypeFlag extends EnumFlag<EntityType> {
public CreatureTypeFlag(String name, char legacyCode) {
super(name, legacyCode, CreatureType.class);
public EntityTypeFlag(String name, RegionGroup defaultGroup) {
super(name, EntityType.class, defaultGroup);
}
public CreatureTypeFlag(String name) {
super(name, CreatureType.class);
public EntityTypeFlag(String name) {
super(name, EntityType.class);
}
@Override
public CreatureType detectValue(String input) {
CreatureType lowMatch = null;
public EntityType detectValue(String input) {
EntityType lowMatch = null;
for (CreatureType type : CreatureType.values()) {
for (EntityType type : EntityType.values()) {
if (type.name().equalsIgnoreCase(input.trim())) {
return type;
}
@@ -29,9 +29,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class EnumFlag<T extends Enum<T>> extends Flag<T> {
private Class<T> enumClass;
public EnumFlag(String name, char legacyCode, Class<T> enumClass) {
super(name, legacyCode);
public EnumFlag(String name, Class<T> enumClass, RegionGroup defaultGroup) {
super(name, defaultGroup);
this.enumClass = enumClass;
}
@@ -41,6 +41,10 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
}
private T findValue(String input) throws IllegalArgumentException {
if (input != null) {
input = input.toUpperCase();
}
try {
return Enum.valueOf(enumClass, input);
} catch (IllegalArgumentException e) {
@@ -88,5 +92,5 @@ public class EnumFlag<T extends Enum<T>> extends Flag<T> {
public Object marshal(T o) {
return o.name();
}
}
@@ -30,24 +30,26 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public abstract class Flag<T> {
private String name;
private Character legacyCode;
public Flag(String name, char legacyCode) {
private RegionGroupFlag regionGroup;
public Flag(String name, RegionGroup defaultGroup) {
this.name = name;
this.legacyCode = legacyCode;
if (defaultGroup != null) {
this.regionGroup = new RegionGroupFlag(name + "-group", defaultGroup);
}
}
public Flag(String name) {
this.name = name;
this.legacyCode = null;
this(name, RegionGroup.NON_MEMBERS);
}
public String getName() {
return name;
}
public Character getLegacyCode() {
return legacyCode;
public RegionGroupFlag getRegionGroupFlag() {
return regionGroup;
}
public abstract T parseInput(WorldGuardPlugin plugin, CommandSender sender,
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
public class IntegerFlag extends Flag<Integer> {
public IntegerFlag(String name, char legacyCode) {
super(name, legacyCode);
public IntegerFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public IntegerFlag(String name) {
@@ -0,0 +1,149 @@
// $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.protection.flags;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Location;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
/**
*
* @author sk89q
*/
public class LocationFlag extends Flag<Location> {
public LocationFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public LocationFlag(String name) {
super(name);
}
@Override
public Location parseInput(WorldGuardPlugin plugin, CommandSender sender, String input) throws InvalidFlagFormat {
input = input.trim();
final Player player;
try {
player = plugin.checkPlayer(sender);
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
}
if ("here".equalsIgnoreCase(input)) {
return BukkitUtil.toLocation(player.getLocation());
} else if ("none".equalsIgnoreCase(input)) {
return null;
} else {
String[] split = input.split(",");
if (split.length >= 3) {
try {
final World world = player.getWorld();
final double x = Double.parseDouble(split[0]);
final double y = Double.parseDouble(split[1]);
final double z = Double.parseDouble(split[2]);
final float yaw = split.length < 4 ? 0 : Float.parseFloat(split[3]);
final float pitch = split.length < 5 ? 0 : Float.parseFloat(split[4]);
return new Location(
BukkitUtil.getLocalWorld(world),
new Vector(
x,
y,
z
),
yaw, pitch
);
} catch (NumberFormatException e) {
}
}
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
}
@Override
public Location unmarshal(Object o) {
if (o instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) o;
Object rawWorld = map.get("world");
if (rawWorld == null) return null;
Object rawX = map.get("x");
if (rawX == null) return null;
Object rawY = map.get("y");
if (rawY == null) return null;
Object rawZ = map.get("z");
if (rawZ == null) return null;
Object rawYaw = map.get("yaw");
if (rawYaw == null) return null;
Object rawPitch = map.get("pitch");
if (rawPitch == null) return null;
World bukkitWorld = Bukkit.getServer().getWorld((String) rawWorld);
LocalWorld world = BukkitUtil.getLocalWorld(bukkitWorld);
Vector position = new Vector(toNumber(rawX), toNumber(rawY), toNumber(rawZ));
float yaw = (float) toNumber(rawYaw);
float pitch = (float) toNumber(rawPitch);
return new Location(world, position, yaw, pitch);
}
return null;
}
@Override
public Object marshal(Location o) {
Vector position = o.getPosition();
Map<String, Object> vec = new HashMap<String, Object>();
vec.put("world", o.getWorld().getName());
vec.put("x", position.getX());
vec.put("y", position.getY());
vec.put("z", position.getZ());
vec.put("yaw", o.getYaw());
vec.put("pitch", o.getPitch());
return vec;
}
private double toNumber(Object o) {
if (o instanceof Number) {
return ((Number) o).doubleValue();
} else {
return 0;
}
}
}
@@ -1,35 +1,31 @@
// $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;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class TickSyncDelayLoggerFilter implements Filter {
public boolean isLoggable(LogRecord record) {
if (record.getLevel() == Level.WARNING
&& record.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) {
return false;
}
return true;
}
}
/*
* WorldGuard
* Copyright (C) 2012 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.protection.flags;
/**
* A grouping of region membership types
*/
public enum RegionGroup {
MEMBERS,
OWNERS,
NON_MEMBERS,
NON_OWNERS,
ALL,
NONE
}
@@ -18,10 +18,7 @@
*/
package com.sk89q.worldguard.protection.flags;
import org.bukkit.command.CommandSender;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -29,24 +26,12 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
*
* @author sk89q
*/
public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static enum RegionGroup {
MEMBERS,
OWNERS,
NON_MEMBERS,
NON_OWNERS
}
public class RegionGroupFlag extends EnumFlag<RegionGroup> {
private RegionGroup def;
public RegionGroupFlag(String name, char legacyCode, RegionGroup def) {
super(name, legacyCode);
this.def = def;
}
public RegionGroupFlag(String name, RegionGroup def) {
super(name);
super(name, RegionGroup.class, null);
this.def = def;
}
@@ -55,8 +40,7 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
}
@Override
public RegionGroup parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
public RegionGroup detectValue(String input) {
input = input.trim();
if (input.equalsIgnoreCase("members") || input.equalsIgnoreCase("member")) {
@@ -67,58 +51,31 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
return RegionGroup.NON_OWNERS;
} else if (input.equalsIgnoreCase("nonmembers") || input.equalsIgnoreCase("nonmember")) {
return RegionGroup.NON_MEMBERS;
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone")) {
return null;
} else {
throw new InvalidFlagFormat("Expected [non]member/[non]owner/anyone but got '" + input + "'");
}
}
@Override
public RegionGroup unmarshal(Object o) {
String str = o.toString();
if (str.equalsIgnoreCase("members")) {
return RegionGroup.MEMBERS;
} else if (str.equalsIgnoreCase("owners")) {
return RegionGroup.OWNERS;
} else if (str.equalsIgnoreCase("nonmembers")) {
return RegionGroup.NON_MEMBERS;
} else if (str.equalsIgnoreCase("nonowners")) {
return RegionGroup.NON_OWNERS;
} else {
return null;
}
}
@Override
public Object marshal(RegionGroup o) {
if (o == RegionGroup.MEMBERS) {
return "members";
} else if (o == RegionGroup.OWNERS) {
return "owners";
} else if (o == RegionGroup.NON_MEMBERS) {
return "nonmembers";
} else if (o == RegionGroup.NON_OWNERS) {
return "nonowners";
} else if (input.equalsIgnoreCase("everyone") || input.equalsIgnoreCase("anyone") || input.equalsIgnoreCase("all")) {
return RegionGroup.ALL;
} else if (input.equalsIgnoreCase("none") || input.equalsIgnoreCase("noone") || input.equalsIgnoreCase("deny")) {
return RegionGroup.NONE;
} else {
return null;
}
}
public static boolean isMember(ProtectedRegion region, RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (group == null || group == RegionGroup.ALL) {
return true;
} else if (group == RegionGroup.OWNERS) {
if (region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
} else if (group == RegionGroup.MEMBERS) {
if (region.isMember(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
} else if (group == RegionGroup.NON_OWNERS) {
if (!region.isOwner(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
} else if (group == RegionGroup.NON_MEMBERS) {
if (!region.isMember(player)) {
return true;
}
@@ -129,19 +86,21 @@ public class RegionGroupFlag extends Flag<RegionGroupFlag.RegionGroup> {
public static boolean isMember(ApplicableRegionSet set,
RegionGroup group, LocalPlayer player) {
if (group == RegionGroupFlag.RegionGroup.OWNERS) {
if (group == null || group == RegionGroup.ALL) {
return true;
} else if (group == RegionGroup.OWNERS) {
if (set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.MEMBERS) {
} else if (group == RegionGroup.MEMBERS) {
if (set.isMemberOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_OWNERS) {
} else if (group == RegionGroup.NON_OWNERS) {
if (!set.isOwnerOfAll(player)) {
return true;
}
} else if (group == RegionGroupFlag.RegionGroup.NON_MEMBERS) {
} else if (group == RegionGroup.NON_MEMBERS) {
if (!set.isMemberOfAll(player)) {
return true;
}
@@ -36,9 +36,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class SetFlag<T> extends Flag<Set<T>> {
private Flag<T> subFlag;
public SetFlag(String name, char legacyCode, Flag<T> subFlag) {
super(name, legacyCode);
public SetFlag(String name, RegionGroup defaultGroup, Flag<T> subFlag) {
super(name, defaultGroup);
this.subFlag = subFlag;
}
@@ -34,10 +34,9 @@ public class StateFlag extends Flag<StateFlag.State> {
}
private boolean def;
private RegionGroupFlag groupFlag;
public StateFlag(String name, char legacyCode, boolean def) {
super(name, legacyCode);
public StateFlag(String name, boolean def, RegionGroup defaultGroup) {
super(name, defaultGroup);
this.def = def;
}
@@ -50,14 +49,6 @@ public class StateFlag extends Flag<StateFlag.State> {
return def;
}
public RegionGroupFlag getGroupFlag() {
return groupFlag;
}
public void setGroupFlag(RegionGroupFlag groupFlag) {
this.groupFlag = groupFlag;
}
@Override
public State parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
@@ -28,8 +28,8 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
*/
public class StringFlag extends Flag<String> {
public StringFlag(String name, char legacyCode) {
super(name, legacyCode);
public StringFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public StringFlag(String name) {
@@ -39,7 +39,7 @@ public class StringFlag extends Flag<String> {
@Override
public String parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
return input;
return input.replaceAll("(?!\\\\)\\\\n", "\n").replaceAll("\\\\\\\\n", "\\n");
}
@Override
@@ -33,9 +33,9 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
* @author sk89q
*/
public class VectorFlag extends Flag<Vector> {
public VectorFlag(String name, char legacyCode) {
super(name, legacyCode);
public VectorFlag(String name, RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public VectorFlag(String name) {
@@ -43,14 +43,29 @@ public class VectorFlag extends Flag<Vector> {
}
@Override
public Vector parseInput(WorldGuardPlugin plugin, CommandSender sender,
String input) throws InvalidFlagFormat {
public Vector parseInput(WorldGuardPlugin plugin, CommandSender sender, String input) throws InvalidFlagFormat {
input = input.trim();
try {
return BukkitUtil.toVector(plugin.checkPlayer(sender).getLocation());
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
if ("here".equalsIgnoreCase(input)) {
try {
return BukkitUtil.toVector(plugin.checkPlayer(sender).getLocation());
} catch (CommandException e) {
throw new InvalidFlagFormat(e.getMessage());
}
} else {
String[] split = input.split(",");
if (split.length == 3) {
try {
return new Vector(
Double.parseDouble(split[0]),
Double.parseDouble(split[1]),
Double.parseDouble(split[2])
);
} catch (NumberFormatException e) {
}
}
throw new InvalidFlagFormat("Expected 'here' or x,y,z.");
}
}
@@ -49,46 +49,28 @@ public class FlatRegionManager extends RegionManager {
/**
* Construct the manager.
*
* @param regionloader
* @param regionLoader The loader for regions
*/
public FlatRegionManager(ProtectionDatabase regionloader) {
super(regionloader);
public FlatRegionManager(ProtectionDatabase regionLoader) {
super(regionLoader);
regions = new TreeMap<String, ProtectedRegion>();
}
/**
* Get a list of protected regions.
*
* @return
*/
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*/
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = new TreeMap<String, ProtectedRegion>(regions);
}
/**
* Adds a region.
*
* @param region
*/
@Override
public void addRegion(ProtectedRegion region) {
regions.put(region.getId().toLowerCase(), region);
}
/**
* Removes a region and its children.
*
* @param id
*/
@Override
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id.toLowerCase());
@@ -110,33 +92,11 @@ public class FlatRegionManager extends RegionManager {
}
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
@Override
public boolean hasRegion(String id) {
return regions.containsKey(id.toLowerCase());
}
/**
* Get a region by its ID.
*
* @param id
*/
@Override
public ProtectedRegion getRegion(String id) {
return regions.get(id.toLowerCase());
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(Vector pt) {
TreeSet<ProtectedRegion> appRegions =
@@ -182,12 +142,6 @@ public class FlatRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}*/
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
@Override
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
@@ -201,11 +155,6 @@ public class FlatRegionManager extends RegionManager {
return applicable;
}
/**
* Get an object for a region for rules to be applied with.
*
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(ProtectedRegion checkRegion) {
@@ -223,13 +172,6 @@ public class FlatRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param player
* @return
*/
@Override
public boolean overlapsUnownedRegion(ProtectedRegion checkRegion, LocalPlayer player) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
@@ -252,11 +194,6 @@ public class FlatRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -18,10 +18,8 @@
*/
package com.sk89q.worldguard.protection.managers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -56,29 +54,21 @@ public class PRTreeRegionManager extends RegionManager {
/**
* Construct the manager.
*
* @param regionloader
* @throws IOException
* @param regionLoader The region loader to use
* @throws ProtectionDatabaseException when an error occurs while loading
*/
public PRTreeRegionManager(ProtectionDatabase regionloader) throws ProtectionDatabaseException {
super(regionloader);
public PRTreeRegionManager(ProtectionDatabase regionLoader) throws ProtectionDatabaseException {
super(regionLoader);
regions = new TreeMap<String, ProtectedRegion>();
tree = new PRTree<ProtectedRegion>(converter, BRANCH_FACTOR);
this.load();
}
/**
* Get a list of protected regions.
*
* @return
*/
@Override
public Map<String, ProtectedRegion> getRegions() {
return regions;
}
/**
* Set a list of protected regions.
*/
@Override
public void setRegions(Map<String, ProtectedRegion> regions) {
this.regions = new TreeMap<String, ProtectedRegion>(regions);
@@ -86,11 +76,6 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Adds a region.
*
* @param region
*/
@Override
public void addRegion(ProtectedRegion region) {
regions.put(region.getId().toLowerCase(), region);
@@ -98,32 +83,11 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Return whether a region exists by an ID.
*
* @param id
* @return
*/
@Override
public boolean hasRegion(String id) {
return regions.containsKey(id.toLowerCase());
}
/**
* Get a region by its ID.
*
* @param id
*/
@Override
public ProtectedRegion getRegion(String id) {
return regions.get(id.toLowerCase());
}
/**
* Removes a region and its children.
*
* @param id
*/
@Override
public void removeRegion(String id) {
ProtectedRegion region = regions.get(id.toLowerCase());
@@ -132,9 +96,7 @@ public class PRTreeRegionManager extends RegionManager {
if (region != null) {
List<String> removeRegions = new ArrayList<String>();
Iterator<ProtectedRegion> iter = regions.values().iterator();
while (iter.hasNext()) {
ProtectedRegion curRegion = iter.next();
for (ProtectedRegion curRegion : regions.values()) {
if (curRegion.getParent() == region) {
removeRegions.add(curRegion.getId().toLowerCase());
}
@@ -149,12 +111,6 @@ public class PRTreeRegionManager extends RegionManager {
tree.load(regions.values());
}
/**
* Get an object for a point for rules to be applied with.
*
* @param pt
* @return
*/
@Override
public ApplicableRegionSet getApplicableRegions(Vector pt) {
List<ProtectedRegion> appRegions =
@@ -189,12 +145,6 @@ public class PRTreeRegionManager extends RegionManager {
return new ApplicableRegionSet(intersectRegions, regions.get("__global__"));
}
/**
* Get a list of region IDs that contain a point.
*
* @param pt
* @return
*/
@Override
public List<String> getApplicableRegionsIDs(Vector pt) {
List<String> applicable = new ArrayList<String>();
@@ -211,13 +161,6 @@ public class PRTreeRegionManager extends RegionManager {
return applicable;
}
/**
* Returns true if the provided region overlaps with any other region that
* is not owned by the player.
*
* @param player
* @return
*/
@Override
public boolean overlapsUnownedRegion(ProtectedRegion checkRegion, LocalPlayer player) {
List<ProtectedRegion> appRegions = new ArrayList<ProtectedRegion>();
@@ -240,11 +183,6 @@ public class PRTreeRegionManager extends RegionManager {
return intersectRegions.size() > 0;
}
/**
* Get the number of regions.
*
* @return
*/
@Override
public int size() {
return regions.size();
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.protection.managers;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@@ -45,7 +44,7 @@ public abstract class RegionManager {
/**
* Construct the object.
*
* @param loader
* @param loader The loader for this region
*/
public RegionManager(ProtectionDatabase loader) {
this.loader = loader;
@@ -55,7 +54,7 @@ public abstract class RegionManager {
* Load the list of regions. If the regions do not load properly, then
* the existing list should be used (as stored previously).
*
* @throws IOException thrown on load error
* @throws ProtectionDatabaseException when an error occurs
*/
public void load() throws ProtectionDatabaseException {
loader.load(this);
@@ -64,7 +63,7 @@ public abstract class RegionManager {
/**
* Save the list of regions.
*
* @throws IOException thrown on save eIf checking multiple flags for a single locationror
* @throws ProtectionDatabaseException when an error occurs while saving
*/
public void save() throws ProtectionDatabaseException {
loader.save(this);
@@ -102,13 +101,41 @@ public abstract class RegionManager {
*/
public abstract boolean hasRegion(String id);
/**
* Get a region by its ID. Includes symbolic names like #&lt;index&gt;
*
* @param id id of the region, can be mixed-case
* @return region or null if it doesn't exist
*/
public ProtectedRegion getRegion(String id) {
if (id.startsWith("#")) {
int index;
try {
index = Integer.parseInt(id.substring(1)) - 1;
} catch (NumberFormatException e) {
return null;
}
for (ProtectedRegion region : getRegions().values()) {
if (index == 0) {
return region;
}
--index;
}
return null;
}
return getRegionExact(id);
}
/**
* Get a region by its ID.
*
* @param id id of the region, can be mixed-case
* @return region or null if it doesn't exist
*/
public abstract ProtectedRegion getRegion(String id);
public ProtectedRegion getRegionExact(String id) {
return getRegions().get(id.toLowerCase());
}
/**
* Removes a region, including inheriting children.
@@ -36,9 +36,9 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Construct a new instance of this cuboid region.
*
* @param id
* @param pt1
* @param pt2
* @param id The region id
* @param pt1 The first point of this region
* @param pt2 The second point of this region
*/
public ProtectedCuboidRegion(String id, BlockVector pt1, BlockVector pt2) {
super(id);
@@ -48,8 +48,8 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Given any two points, sets the minimum and maximum points
*
* @param pt1
* @param pt2
* @param pt1 The first point of this region
* @param pt2 The second point of this region
*/
private void setMinMaxPoints(BlockVector pt1, BlockVector pt2) {
List<Vector> points = new ArrayList<Vector>();
@@ -61,7 +61,7 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Set the lower point of the cuboid.
*
* @param pt
* @param pt The point to set as the minimum point
*/
public void setMinimumPoint(BlockVector pt) {
setMinMaxPoints(pt, max);
@@ -70,7 +70,7 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
/**
* Set the upper point of the cuboid.
*
* @param pt
* @param pt The point to set as the maximum point
*/
public void setMaximumPoint(BlockVector pt) {
setMinMaxPoints(min, pt);
@@ -91,9 +91,6 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
return pts;
}
/**
* Checks to see if a point is inside this region.
*/
@Override
public boolean contains(Vector pt) {
final double x = pt.getX();
@@ -157,29 +154,17 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
return intersectingRegions;
}
/**
* Return the type of region as a user-friendly name.
*
* @return type of region
*/
@Override
public String getTypeName() {
return "cuboid";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int xLength = max.getBlockX() - min.getBlockX() + 1;
int yLength = max.getBlockY() - min.getBlockY() + 1;
int zLength = max.getBlockZ() - min.getBlockZ() + 1;
int volume = xLength * yLength * zLength;
return volume;
return xLength * yLength * zLength;
}
}
@@ -42,9 +42,9 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
/**
* Sets the min and max points from all the 2d points and the min/max Y values
*
* @param points2D
* @param minY
* @param maxY
* @param points2D A {@link List} of points that this region should contain
* @param minY The minimum y coordinate
* @param maxY The maximum y coordinate
*/
private void setMinMaxPoints(List<BlockVector2D> points2D, int minY, int maxY) {
List<Vector> points = new ArrayList<Vector>();
@@ -156,11 +156,6 @@ public class ProtectedPolygonalRegion extends ProtectedRegion {
return "polygon";
}
/**
* Get the number of Blocks in this region
*
* @return
*/
@Override
public int volume() {
int volume = 0;
@@ -78,7 +78,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Construct a new instance of this region.
*
* @param id
* @param id The id (name) of this region.
*/
public ProtectedRegion(String id) {
this.id = id;
@@ -87,7 +87,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Sets the minimum and maximum points of the bounding box for a region
*
* @param points
* @param points The points to set. Must have at least one element.
*/
protected void setMinMaxPoints(List<Vector> points) {
int minX = points.get(0).getBlockX();
@@ -116,6 +116,8 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
}
/**
* Gets the id of this region
*
* @return the id
*/
public String getId() {
@@ -166,7 +168,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* in circular inheritance.
*
* @param parent the curParent to setFlag
* @throws CircularInheritanceException
* @throws CircularInheritanceException when circular inheritance is detected
*/
public void setParent(ProtectedRegion parent) throws CircularInheritanceException {
if (parent == null) {
@@ -251,6 +253,29 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
return false;
}
/**
* Checks whether a player is an owner of region or any of its parents.
*
* @param playerName player name to check
* @return whether an owner
*/
public boolean isOwner(String playerName) {
if (owners.contains(playerName)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(playerName)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is a member OR OWNER of the region
* or any of its parents.
@@ -259,14 +284,45 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* @return whether an owner or member
*/
public boolean isMember(LocalPlayer player) {
if (owners.contains(player) || members.contains(player)) {
if (isOwner(player)) {
return true;
}
if (members.contains(player)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getOwners().contains(player)
|| curParent.getMembers().contains(player)) {
if (curParent.getMembers().contains(player)) {
return true;
}
curParent = curParent.getParent();
}
return false;
}
/**
* Checks whether a player is a member OR OWNER of the region
* or any of its parents.
*
* @param playerName player name to check
* @return whether an owner or member
*/
public boolean isMember(String playerName) {
if (isOwner(playerName)) {
return true;
}
if (members.contains(playerName)) {
return true;
}
ProtectedRegion curParent = getParent();
while (curParent != null) {
if (curParent.getMembers().contains(playerName)) {
return true;
}
@@ -303,9 +359,9 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get a flag's value.
*
* @param <T>
* @param <V>
* @param flag
* @param <T> The flag type
* @param <V> The type of the flag's value
* @param flag The flag to check
* @return value or null if isn't defined
*/
@SuppressWarnings("unchecked")
@@ -323,10 +379,10 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Set a flag's value.
*
* @param <T>
* @param <V>
* @param flag
* @param val
* @param <T> The flag type
* @param <V> The type of the flag's value
* @param flag The flag to check
* @param val The value to set
*/
public <T extends Flag<V>, V> void setFlag(T flag, V val) {
if (val == null) {
@@ -339,7 +395,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get the map of flags.
*
* @return
* @return The map of flags currently used for this region
*/
public Map<Flag<?>, Object> getFlags() {
return flags;
@@ -348,7 +404,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get the map of flags.
*
* @param flags
* @param flags The flags to set
*/
public void setFlags(Map<Flag<?>, Object> flags) {
this.flags = flags;
@@ -357,30 +413,30 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Gets the 2D points for this region
*
* @return
* @return The points for this region as (x, z) coordinates
*/
public abstract List<BlockVector2D> getPoints();
/**
* Get the number of blocks in this region
*
* @return
* @return the volume of this region in blocks
*/
public abstract int volume();
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
* @param pt The point to check
* @return Whether {@code pt} is in this region
*/
public abstract boolean contains(Vector pt);
/**
* Check to see if a point is inside this region.
*
* @param pt
* @return
* @param pt The point to check
* @return Whether {@code pt} is in this region
*/
public boolean contains(BlockVector2D pt) {
return contains(new Vector(pt.getBlockX(), min.getBlockY(), pt.getBlockZ()));
@@ -389,10 +445,10 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Check to see if a point is inside this region.
*
* @param x
* @param y
* @param z
* @return
* @param x The x coordinate to check
* @param y The y coordinate to check
* @param z The z coordinate to check
* @return Whether this region contains the points at the given coordinate
*/
public boolean contains(int x, int y, int z) {
return contains(new Vector(x, y, z));
@@ -419,8 +475,7 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* Orders primarily by the priority, descending<br>
* Orders secondarily by the id, ascending
*
* @param other
* @return
* @param other The region to compare to
*/
public int compareTo(ProtectedRegion other) {
if (priority > other.priority) {
@@ -442,9 +497,9 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Get a list of intersecting regions.
*
* @param regions
* @return
* @throws UnsupportedIntersectionException
* @param regions The list of regions to source from
* @return The elements of {@code regions} that intersect with this region
* @throws UnsupportedIntersectionException if an invalid intersection is detected
*/
public abstract List<ProtectedRegion> getIntersectingRegions(
List<ProtectedRegion> regions)
@@ -454,7 +509,8 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
* Checks if the bounding box of a region intersects with with the bounding
* box of this region
*
* @param region
* @param region The region to check
* @return whether the given region intersects
*/
protected boolean intersectsBoundingBox(ProtectedRegion region) {
BlockVector rMaxPoint = region.getMaximumPoint();
@@ -477,8 +533,8 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Compares all edges of two regions to see if any of them intersect
*
* @param region
* @return
* @param region The region to check
* @return whether any edges of a region intersect
*/
protected boolean intersectsEdges(ProtectedRegion region) {
List<BlockVector2D> pts1 = getPoints();
@@ -511,16 +567,14 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Checks to see if the given ID is accurate.
*
* @param id
* @return
* @param id The id to check
* @see #idPattern
* @return Whether the region id given is valid
*/
public static boolean isValidId(String id) {
return idPattern.matcher(id).matches();
}
/**
* Returns the hash code.
*/
@Override
public int hashCode(){
return id.hashCode();
@@ -542,7 +596,6 @@ public abstract class ProtectedRegion implements Comparable<ProtectedRegion> {
/**
* Thrown when setting a curParent would create a circular inheritance
* situation.
*
*/
public static class CircularInheritanceException extends Exception {
private static final long serialVersionUID = 7479613488496776022L;
@@ -25,17 +25,24 @@ public class ArrayReader<T> {
public ArrayReader(T[] arr) {
this.arr = arr;
}
/**
* Gets an element from the array
* @param index The index to get an element at
* @return The element at {@code index} if the index is within bounds, otherwise null
*/
public T get(int index) {
if (arr.length > index) {
return arr[index];
} else {
return null;
}
return get(index, null);
}
/**
* Gets an element from the array
* @param index The index to get an element at
* @param def the default value, used when the given index is out of bounds
* @return The element at {@code index} if the index is within bounds, otherwise the default value
*/
public T get(int index, T def) {
if (arr.length > index) {
if (index >= 0 && arr.length > index) {
return arr[index];
} else {
return def;
@@ -0,0 +1,6 @@
package com.sk89q.worldguard.util;
public class FatalConfigurationLoadingException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
@@ -1,41 +0,0 @@
/*
* WorldGuard
* Copyright (C) 2011 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.util;
import java.lang.reflect.Field;
/**
* @author zml2008
*/
public class ReflectionUtil {
@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
Class<?> checkClass = from.getClass();
do {
try {
Field field = checkClass.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(from);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
return null;
}
}
@@ -19,83 +19,58 @@
package com.sk89q.worldguard.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.databases.RegionDBUtil;
/**
* Various utility functions for regions.
*
* @author sk89q
*/
@Deprecated
public class RegionUtil {
private static Pattern groupPattern = Pattern.compile("^[gG]:(.+)$");
private RegionUtil() {
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#addToDomain(com.sk89q.worldguard.domains.DefaultDomain, String[], int)}
*/
@Deprecated
public static void addToDomain(DefaultDomain domain, String[] split,
int startIndex) {
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.addGroup(m.group(1));
} else {
domain.addPlayer(s);
}
}
RegionDBUtil.addToDomain(domain, split, startIndex);
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param domain
* @param split
* @param startIndex
* @param domain The domain to add to
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#removeFromDomain(com.sk89q.worldguard.domains.DefaultDomain, String[], int)}
*/
@Deprecated
public static void removeFromDomain(DefaultDomain domain, String[] split,
int startIndex) {
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.removeGroup(m.group(1));
} else {
domain.removePlayer(s);
}
}
RegionDBUtil.removeFromDomain(domain, split, startIndex);
}
/**
* Parse a group/player DefaultDomain specification for areas.
*
* @param split
* @param startIndex
* @return
*
* @param split The arguments
* @param startIndex The index to start at
* @deprecated see {@link RegionDBUtil#parseDomainString(String[], int)}
* @return the parsed domain
*/
@Deprecated
public static DefaultDomain parseDomainString(String[] split, int startIndex) {
DefaultDomain domain = new DefaultDomain();
for (int i = startIndex; i < split.length; i++) {
String s = split[i];
Matcher m = groupPattern.matcher(s);
if (m.matches()) {
domain.addGroup(m.group(1));
} else {
domain.addPlayer(s);
}
}
return domain;
return RegionDBUtil.parseDomainString(split, startIndex);
}
}
@@ -24,6 +24,7 @@ import java.util.HashSet;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.LocalPlayer;
@org.junit.Ignore
public class TestPlayer extends LocalPlayer {
private String name;
private Set<String> groups = new HashSet<String>();