From 6ff998ac3b479f0c4550c184784e985eb1b6213d Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Sun, 7 Feb 2021 03:37:25 +0100 Subject: [PATCH] Restructures the plugin and starts work on cleaning and commenting the code --- README.md | 14 +- pom.xml | 37 +- .../net/knarcraft/stargate/BlockLocation.java | 199 +++ .../net/knarcraft/stargate/BloxPopulator.java | 48 + .../stargate/BungeeCoordListener.java | 58 + .../knarcraft/stargate/CommonFunctions.java | 43 + .../knarcraft/stargate/EconomyHandler.java | 106 ++ .../java/net/knarcraft/stargate/Gate.java | 516 ++++++ .../knarcraft/stargate/LanguageLoader.java | 311 ++++ .../java/net/knarcraft/stargate/Portal.java | 1503 +++++++++++++++++ .../stargate}/RelativeBlockVector.java | 93 +- .../knarcraft/stargate/StarGateThread.java | 34 + .../java/net/knarcraft/stargate/Stargate.java | 1280 ++++++++++++++ .../stargate}/event/StargateAccessEvent.java | 130 +- .../stargate/event/StargateActivateEvent.java | 72 + .../stargate}/event/StargateCloseEvent.java | 103 +- .../stargate/event/StargateCreateEvent.java | 85 + .../event/StargateDeactivateEvent.java | 80 +- .../stargate/event/StargateDestroyEvent.java | 79 + .../stargate}/event/StargateEvent.java | 102 +- .../stargate/event/StargateOpenEvent.java | 65 + .../stargate/event/StargatePortalEvent.java | 85 + src/{ => main/resources}/config.yml | 106 +- .../resources => main/resources/lang}/de.txt | 54 +- .../resources => main/resources/lang}/en.txt | 64 +- .../resources => main/resources/lang}/es.txt | 0 .../resources => main/resources/lang}/fr.txt | 0 .../resources => main/resources/lang}/hu.txt | 0 .../resources => main/resources/lang}/it.txt | 0 .../resources => main/resources/lang}/nl.txt | 2 +- .../resources/lang}/pt-br.txt | 0 .../resources => main/resources/lang}/ru.txt | 0 src/{ => main/resources}/plugin.yml | 58 +- src/net/TheDgtl/Stargate/Blox.java | 173 -- src/net/TheDgtl/Stargate/BloxPopulator.java | 47 - src/net/TheDgtl/Stargate/EconomyHandler.java | 106 -- src/net/TheDgtl/Stargate/Gate.java | 513 ------ src/net/TheDgtl/Stargate/LangLoader.java | 226 --- src/net/TheDgtl/Stargate/Portal.java | 1495 ---------------- src/net/TheDgtl/Stargate/Stargate.java | 1294 -------------- .../Stargate/event/StargateActivateEvent.java | 69 - .../Stargate/event/StargateCreateEvent.java | 83 - .../Stargate/event/StargateDestroyEvent.java | 77 - .../Stargate/event/StargateOpenEvent.java | 61 - .../Stargate/event/StargatePortalEvent.java | 80 - src/net/TheDgtl/Stargate/pmListener.java | 57 - 46 files changed, 4918 insertions(+), 4690 deletions(-) create mode 100644 src/main/java/net/knarcraft/stargate/BlockLocation.java create mode 100644 src/main/java/net/knarcraft/stargate/BloxPopulator.java create mode 100644 src/main/java/net/knarcraft/stargate/BungeeCoordListener.java create mode 100644 src/main/java/net/knarcraft/stargate/CommonFunctions.java create mode 100644 src/main/java/net/knarcraft/stargate/EconomyHandler.java create mode 100644 src/main/java/net/knarcraft/stargate/Gate.java create mode 100644 src/main/java/net/knarcraft/stargate/LanguageLoader.java create mode 100644 src/main/java/net/knarcraft/stargate/Portal.java rename src/{net/TheDgtl/Stargate => main/java/net/knarcraft/stargate}/RelativeBlockVector.java (60%) create mode 100644 src/main/java/net/knarcraft/stargate/StarGateThread.java create mode 100644 src/main/java/net/knarcraft/stargate/Stargate.java rename src/{net/TheDgtl/Stargate => main/java/net/knarcraft/stargate}/event/StargateAccessEvent.java (76%) create mode 100644 src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java rename src/{net/TheDgtl/Stargate => main/java/net/knarcraft/stargate}/event/StargateCloseEvent.java (54%) create mode 100644 src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java rename src/{net/TheDgtl/Stargate => main/java/net/knarcraft/stargate}/event/StargateDeactivateEvent.java (62%) create mode 100644 src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java rename src/{net/TheDgtl/Stargate => main/java/net/knarcraft/stargate}/event/StargateEvent.java (55%) create mode 100644 src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java create mode 100644 src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java rename src/{ => main/resources}/config.yml (89%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/de.txt (89%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/en.txt (96%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/es.txt (100%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/fr.txt (100%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/hu.txt (100%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/it.txt (100%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/nl.txt (90%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/pt-br.txt (100%) rename src/{net/TheDgtl/Stargate/resources => main/resources/lang}/ru.txt (100%) rename src/{ => main/resources}/plugin.yml (82%) delete mode 100644 src/net/TheDgtl/Stargate/Blox.java delete mode 100644 src/net/TheDgtl/Stargate/BloxPopulator.java delete mode 100644 src/net/TheDgtl/Stargate/EconomyHandler.java delete mode 100644 src/net/TheDgtl/Stargate/Gate.java delete mode 100644 src/net/TheDgtl/Stargate/LangLoader.java delete mode 100644 src/net/TheDgtl/Stargate/Portal.java delete mode 100644 src/net/TheDgtl/Stargate/Stargate.java delete mode 100644 src/net/TheDgtl/Stargate/event/StargateActivateEvent.java delete mode 100644 src/net/TheDgtl/Stargate/event/StargateCreateEvent.java delete mode 100644 src/net/TheDgtl/Stargate/event/StargateDestroyEvent.java delete mode 100644 src/net/TheDgtl/Stargate/event/StargateOpenEvent.java delete mode 100644 src/net/TheDgtl/Stargate/event/StargatePortalEvent.java delete mode 100644 src/net/TheDgtl/Stargate/pmListener.java diff --git a/README.md b/README.md index 19ed669..0d68aad 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ chargefreedestination - Enable to allow free travel from any gate to a free gate freegatesgreen - Enable to make gates that won't cost the player money show up as green toowner - Whether the money from gate-use goes to the owner or nobody maxgates - If non-zero, will define the maximum amount of gates allowed on any network. -lang - The language to use (Included languages: en, de) +chosenLanguage - The language to use (Included languages: en, de) destMemory - Whether to set the first destination as the last used destination for all gates ignoreEntrance - Set this option to true to not check the entrance of a gate on startup. This is a workaround for snowmen breaking gates. handleVehicles - Whether or not to handle vehicles going through gates. Set to false to disallow vehicles (Manned or not) going through gates. @@ -170,7 +170,7 @@ permdebug: Whether to show massive permission debug output ``` # Message Customization -It is possible to customize all of the messages Stargate displays, including the [Stargate] prefix. You can find the strings in plugins/Stargate/lang/en.txt. +It is possible to customize all of the messages Stargate displays, including the [Stargate] prefix. You can find the strings in plugins/Stargate/chosenLanguage/en.txt. If a string is removed, or left blank, it will not be shown when the user does the action associated with it. There are three special cases when it comes to messages, these are: @@ -211,7 +211,7 @@ createConflict=Gate conflicts with existing gate - Add custom buttons #### [Version 0.8.0.2] PseudoKnight fork - Fix player relative yaw when exiting portal - - Add color code support in lang files + - Add color code support in chosenLanguage files #### [Version 0.8.0.1] PseudoKnight fork - Fix slab check for portal exits - Improve material checks for gate configuration @@ -377,14 +377,14 @@ createConflict=Gate conflicts with existing gate #### [Version 0.6.10] - Added Register support as opposed to iConomy #### [Version 0.6.9] - - Added UTF8 support for lang files (With or without BOM) + - Added UTF8 support for chosenLanguage files (With or without BOM) #### [Version 0.6.8] - Fixed unmanned carts losing velocity through gates - /sg reload now properly switches languages #### [Version 0.6.7] - - Added lang option + - Added chosenLanguage option - Removed language debug output - - Added German language (lang=de) -- Thanks EduardBaer + - Added German language (chosenLanguage=de) -- Thanks EduardBaer #### [Version 0.6.6] - Added %cost% and %portal% to all eco* messages - Fixed an issue when creating a gate on a network you don't have access to @@ -560,6 +560,6 @@ createConflict=Gate conflicts with existing gate #### [Version 0.04] - Updated to multi-world Bukkit #### [Version 0.03] - - Changed package to net.TheDgtl.* + - Changed package to net.knarcraft.* - Everything now uses Blox instead of Block objects - Started on vehicle code, but it's still buggy diff --git a/pom.xml b/pom.xml index 7d02c5f..36dff1a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,11 +1,23 @@ 4.0.0 - org.TheDgtl + + net.knarcraft Stargate - 0.8.0.3 + 0.8.0.0 + + + + GNU Lesser General Public License + https://www.gnu.org/licenses/lgpl-3.0.en.html + + + UTF-8 + 1.8 + 1.8 + spigot-repo @@ -16,11 +28,12 @@ http://nexus.hc.to/content/repositories/pub_releases + org.spigotmc spigot-api - 1.16.2-R0.1-SNAPSHOT + 1.16.5-R0.1-SNAPSHOT net.milkbowl.vault @@ -28,23 +41,9 @@ 1.7 + - src - - - net/TheDgtl/Stargate/resources - src/net/TheDgtl/Stargate/resources - - *.txt - - - - src - - *.yml - - - + src/main/java org.apache.maven.plugins diff --git a/src/main/java/net/knarcraft/stargate/BlockLocation.java b/src/main/java/net/knarcraft/stargate/BlockLocation.java new file mode 100644 index 0000000..f607666 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/BlockLocation.java @@ -0,0 +1,199 @@ +package net.knarcraft.stargate; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Sign; +import org.bukkit.block.data.type.WallSign; + +/* + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011 Shaun (sturmeh) + * Copyright (C) 2011 Dinnerbone + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * This class represents a block location + */ +public class BlockLocation { + + private final int x; + private final int y; + private final int z; + private final World world; + private BlockLocation parent = null; + + /** + * Creates a new block + * @param world

The world the block exists in

+ * @param x

The x coordinate of the block

+ * @param y

The y coordinate of the block

+ * @param z

The z coordinate of the block

+ */ + public BlockLocation(World world, int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + this.world = world; + } + + /** + * Copies a craftbukkit block + * @param block

The block to

+ */ + public BlockLocation(Block block) { + this.x = block.getX(); + this.y = block.getY(); + this.z = block.getZ(); + this.world = block.getWorld(); + } + + /** + * Creates a new block from a location + * @param location

The location the block exists in

+ */ + public BlockLocation(Location location) { + this.x = location.getBlockX(); + this.y = location.getBlockY(); + this.z = location.getBlockZ(); + this.world = location.getWorld(); + } + + /** + * Gets a block from a string + * @param world

The world the block exists in

+ * @param string

A comma separated list of z, y and z coordinates as integers

+ */ + public BlockLocation(World world, String string) { + String[] split = string.split(","); + this.x = Integer.parseInt(split[0]); + this.y = Integer.parseInt(split[1]); + this.z = Integer.parseInt(split[2]); + this.world = world; + } + + /** + * Makes a new block in a relative position to this block + * @param x

The x position relative to this block's position

+ * @param y

The y position relative to this block's position

+ * @param z

The z position relative to this block's position

+ * @return

A new block

+ */ + public BlockLocation makeRelative(int x, int y, int z) { + return new BlockLocation(this.world, this.x + x, this.y + y, this.z + z); + } + + public Location makeRelativeLoc(double x, double y, double z, float rotX, float rotY) { + return new Location(this.world, (double) this.x + x, (double) this.y + y, (double) this.z + z, rotX, rotY); + } + + public BlockLocation modRelative(int right, int depth, int distance, int modX, int modY, int modZ) { + return makeRelative(-right * modX + distance * modZ, -depth * modY, -right * modZ + -distance * modX); + } + + public Location modRelativeLoc(double right, double depth, double distance, float rotX, float rotY, int modX, int modY, int modZ) { + return makeRelativeLoc(0.5 + -right * modX + distance * modZ, depth, 0.5 + -right * modZ + -distance * modX, rotX, 0); + } + + public void setType(Material type) { + world.getBlockAt(x, y, z).setType(type); + } + + public Material getType() { + return world.getBlockAt(x, y, z).getType(); + } + + public Block getBlock() { + return world.getBlockAt(x, y, z); + } + + public Location getLocation() { + return new Location(world, x, y, z); + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + + public World getWorld() { + return world; + } + + public Block getParent() { + if (parent == null) findParent(); + if (parent == null) return null; + return parent.getBlock(); + } + + private void findParent() { + int offsetX = 0; + int offsetY = 0; + int offsetZ = 0; + + BlockData blk = getBlock().getBlockData(); + if (blk instanceof WallSign) { + BlockFace facing = ((WallSign) blk).getFacing().getOppositeFace(); + offsetX = facing.getModX(); + offsetZ = facing.getModZ(); + } else if (blk instanceof Sign) { + offsetY = -1; + } else { + return; + } + parent = new BlockLocation(world, getX() + offsetX, getY() + offsetY, getZ() + offsetZ); + } + + @Override + public String toString() { + return String.valueOf(x) + ',' + y + ',' + z; + } + + @Override + public int hashCode() { + int result = 18; + + result = result * 27 + x; + result = result * 27 + y; + result = result * 27 + z; + result = result * 27 + world.getName().hashCode(); + + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + + BlockLocation blockLocation = (BlockLocation) obj; + return (x == blockLocation.x) && (y == blockLocation.y) && (z == blockLocation.z) && (world.getName().equals(blockLocation.world.getName())); + } + +} \ No newline at end of file diff --git a/src/main/java/net/knarcraft/stargate/BloxPopulator.java b/src/main/java/net/knarcraft/stargate/BloxPopulator.java new file mode 100644 index 0000000..87bedb8 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/BloxPopulator.java @@ -0,0 +1,48 @@ +package net.knarcraft.stargate; + +import org.bukkit.Axis; +import org.bukkit.Material; + +public class BloxPopulator { + + private BlockLocation blockLocation; + private Material nextMat; + private Axis nextAxis; + + public BloxPopulator(BlockLocation b, Material m) { + blockLocation = b; + nextMat = m; + nextAxis = null; + } + + public BloxPopulator(BlockLocation b, Material m, Axis a) { + blockLocation = b; + nextMat = m; + nextAxis = a; + } + + public void setBlockLocation(BlockLocation b) { + blockLocation = b; + } + + public void setMat(Material m) { + nextMat = m; + } + + public void setAxis(Axis a) { + nextAxis = a; + } + + public BlockLocation getBlockLocation() { + return blockLocation; + } + + public Material getMat() { + return nextMat; + } + + public Axis getAxis() { + return nextAxis; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/BungeeCoordListener.java b/src/main/java/net/knarcraft/stargate/BungeeCoordListener.java new file mode 100644 index 0000000..57fe488 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/BungeeCoordListener.java @@ -0,0 +1,58 @@ +package net.knarcraft.stargate; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.messaging.PluginMessageListener; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; + +public class BungeeCoordListener implements PluginMessageListener { + + @Override + public void onPluginMessageReceived(String channel, Player unused, byte[] message) { + if (!Stargate.enableBungee || !channel.equals("BungeeCord")) return; + + // Get data from message + String inChannel; + byte[] data; + try { + DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); + inChannel = in.readUTF(); + short len = in.readShort(); + data = new byte[len]; + in.readFully(data); + } catch (IOException ex) { + Stargate.log.severe("[stargate] Error receiving BungeeCord message"); + ex.printStackTrace(); + return; + } + + // Verify that it's an SGBungee packet + if (!inChannel.equals("SGBungee")) { + return; + } + + // Data should be player name, and destination gate name + String msg = new String(data); + String[] parts = msg.split("#@#"); + + String playerName = parts[0]; + String destination = parts[1]; + + // Check if the player is online, if so, teleport, otherwise, queue + Player player = Stargate.server.getPlayer(playerName); + if (player == null) { + Stargate.bungeeQueue.put(playerName.toLowerCase(), destination); + } else { + Portal dest = Portal.getBungeeGate(destination); + // Specified an invalid gate. For now we'll just let them connect at their current location + if (dest == null) { + Stargate.log.info("[stargate] Bungee gate " + destination + " does not exist"); + return; + } + dest.teleport(player, dest, null); + } + } + +} diff --git a/src/main/java/net/knarcraft/stargate/CommonFunctions.java b/src/main/java/net/knarcraft/stargate/CommonFunctions.java new file mode 100644 index 0000000..7c374fe --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/CommonFunctions.java @@ -0,0 +1,43 @@ +package net.knarcraft.stargate; + +import java.io.InputStream; + +/* + * stargate - A portal plugin for Bukkit + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * A holding class for methods shared between classes + * + * @author Kristian Knarvik + */ +public final class CommonFunctions { + + private CommonFunctions() {} + + /** + * Gets a resource as an InputStream + * + * @param resourceName

The name of the resource you want to readFromServer

+ * @return

An input stream which can be used to access the resource

+ */ + public static InputStream getResourceAsStream(String resourceName) { + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + return classloader.getResourceAsStream(resourceName); + } + +} diff --git a/src/main/java/net/knarcraft/stargate/EconomyHandler.java b/src/main/java/net/knarcraft/stargate/EconomyHandler.java new file mode 100644 index 0000000..0d4c94f --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/EconomyHandler.java @@ -0,0 +1,106 @@ +package net.knarcraft.stargate; + +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; + +import java.util.UUID; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class EconomyHandler { + public static boolean economyEnabled = false; + public static Economy economy = null; + public static Plugin vault = null; + + public static int useCost = 0; + public static int createCost = 0; + public static int destroyCost = 0; + public static boolean toOwner = false; + public static boolean chargeFreeDestination = true; + public static boolean freeGatesGreen = false; + + public static double getBalance(Player player) { + if (!economyEnabled) return 0; + return economy.getBalance(player); + } + + public static boolean chargePlayer(Player player, String target, double amount) { + if (!economyEnabled) return true; + if (player.getName().equals(target)) return true; + if (economy != null) { + if (!economy.has(player, amount)) return false; + economy.withdrawPlayer(player, amount); + economy.depositPlayer(target, amount); + } + return true; + } + + public static boolean chargePlayer(Player player, UUID target, double amount) { + if (!economyEnabled) return true; + if (player.getUniqueId().compareTo(target) == 0) return true; + if (economy != null) { + if (!economy.has(player, amount)) return false; + economy.withdrawPlayer(player, amount); + economy.depositPlayer(Bukkit.getOfflinePlayer(target), amount); + } + return true; + } + + public static boolean chargePlayer(Player player, double amount) { + if (!economyEnabled) return true; + if (economy != null) { + if (!economy.has(player, amount)) return false; + economy.withdrawPlayer(player, amount); + } + return true; + } + + public static String format(int amt) { + if (economyEnabled) { + return economy.format(amt); + } + return ""; + } + + public static boolean setupEconomy(PluginManager pm) { + if (!economyEnabled) return false; + // Check for Vault + Plugin p = pm.getPlugin("Vault"); + if (p != null && p.isEnabled()) { + RegisteredServiceProvider economyProvider = Stargate.server.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + vault = p; + return true; + } + } + economyEnabled = false; + return false; + } + + public static boolean useEconomy() { + return economyEnabled && economy != null; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/Gate.java b/src/main/java/net/knarcraft/stargate/Gate.java new file mode 100644 index 0000000..30b4812 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/Gate.java @@ -0,0 +1,516 @@ +package net.knarcraft.stargate; + +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.block.Block; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Scanner; +import java.util.logging.Level; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011 Shaun (sturmeh) + * Copyright (C) 2011 Dinnerbone + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class Gate { + + private static final Character ANYTHING = ' '; + private static final Character ENTRANCE = '.'; + private static final Character EXIT = '*'; + private static final HashMap gates = new HashMap<>(); + private static final HashMap> controlBlocks = new HashMap<>(); + private static final HashSet frameBlocks = new HashSet<>(); + + private final String filename; + private final Character[][] layout; + private final HashMap types; + private RelativeBlockVector[] entrances = new RelativeBlockVector[0]; + private RelativeBlockVector[] border = new RelativeBlockVector[0]; + private RelativeBlockVector[] controls = new RelativeBlockVector[0]; + private RelativeBlockVector exitBlock = null; + private final HashMap exits = new HashMap<>(); + private Material portalBlockOpen = Material.NETHER_PORTAL; + private Material portalBlockClosed = Material.AIR; + private Material button = Material.STONE_BUTTON; + + // Economy information + private int useCost = -1; + private int createCost = -1; + private int destroyCost = -1; + private boolean toOwner = false; + + public Gate(String filename, Character[][] layout, HashMap types) { + this.filename = filename; + this.layout = layout; + this.types = types; + + populateCoordinates(); + } + + private void populateCoordinates() { + ArrayList entranceList = new ArrayList<>(); + ArrayList borderList = new ArrayList<>(); + ArrayList controlList = new ArrayList<>(); + RelativeBlockVector[] relativeExits = new RelativeBlockVector[layout[0].length]; + int[] exitDepths = new int[layout[0].length]; + RelativeBlockVector lastExit = null; + + for (int y = 0; y < layout.length; y++) { + for (int x = 0; x < layout[y].length; x++) { + Character key = layout[y][x]; + if (key.equals('-')) { + controlList.add(new RelativeBlockVector(x, y, 0)); + } + + if (key.equals(ENTRANCE) || key.equals(EXIT)) { + entranceList.add(new RelativeBlockVector(x, y, 0)); + exitDepths[x] = y; + if (key.equals(EXIT)) { + this.exitBlock = new RelativeBlockVector(x, y, 0); + } + } else if (!key.equals(ANYTHING)) { + borderList.add(new RelativeBlockVector(x, y, 0)); + } + } + } + + for (int x = 0; x < exitDepths.length; x++) { + relativeExits[x] = new RelativeBlockVector(x, exitDepths[x], 0); + } + + for (int x = relativeExits.length - 1; x >= 0; x--) { + if (relativeExits[x] != null) { + lastExit = relativeExits[x]; + } else { + relativeExits[x] = lastExit; + } + + if (exitDepths[x] > 0) this.exits.put(relativeExits[x], x); + } + + this.entrances = entranceList.toArray(this.entrances); + this.border = borderList.toArray(this.border); + this.controls = controlList.toArray(this.controls); + } + + public void save(String gateFolder) { + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(gateFolder + filename)); + + writeConfig(bw, "portal-open", portalBlockOpen.name()); + writeConfig(bw, "portal-closed", portalBlockClosed.name()); + writeConfig(bw, "button", button.name()); + if (useCost != -1) + writeConfig(bw, "usecost", useCost); + if (createCost != -1) + writeConfig(bw, "createcost", createCost); + if (destroyCost != -1) + writeConfig(bw, "destroycost", destroyCost); + writeConfig(bw, "toowner", toOwner); + + for (Map.Entry entry : types.entrySet()) { + Character type = entry.getKey(); + Material value = entry.getValue(); + // Skip control values + if (type.equals(ANYTHING) || type.equals(ENTRANCE) || type.equals(EXIT)) { + continue; + } + + bw.append(type); + bw.append('='); + if (value != null) { + bw.append(value.toString()); + } + bw.newLine(); + } + + bw.newLine(); + + for (Character[] aLayout : layout) { + for (Character symbol : aLayout) { + bw.append(symbol); + } + bw.newLine(); + } + + bw.close(); + } catch (IOException ex) { + Stargate.log.log(Level.SEVERE, "Could not save Gate " + filename + " - " + ex.getMessage()); + } + } + + private void writeConfig(BufferedWriter bw, String key, int value) throws IOException { + bw.append(String.format("%s=%d", key, value)); + bw.newLine(); + } + + private void writeConfig(BufferedWriter bw, String key, boolean value) throws IOException { + bw.append(String.format("%s=%b", key, value)); + bw.newLine(); + } + + private void writeConfig(BufferedWriter bw, String key, String value) throws IOException { + bw.append(String.format("%s=%s", key, value)); + bw.newLine(); + } + + public Character[][] getLayout() { + return layout; + } + + public HashMap getTypes() { + return types; + } + + public RelativeBlockVector[] getEntrances() { + return entrances; + } + + public RelativeBlockVector[] getBorder() { + return border; + } + + public RelativeBlockVector[] getControls() { + return controls; + } + + public HashMap getExits() { + return exits; + } + + public RelativeBlockVector getExit() { + return exitBlock; + } + + public Material getControlBlock() { + return types.get('-'); + } + + public String getFilename() { + return filename; + } + + public Material getPortalBlockOpen() { + return portalBlockOpen; + } + + public void setPortalBlockOpen(Material type) { + portalBlockOpen = type; + } + + public Material getPortalBlockClosed() { + return portalBlockClosed; + } + + public void setPortalBlockClosed(Material type) { + portalBlockClosed = type; + } + + public Material getButton() { + return button; + } + + public int getUseCost() { + if (useCost < 0) return EconomyHandler.useCost; + return useCost; + } + + public Integer getCreateCost() { + if (createCost < 0) return EconomyHandler.createCost; + return createCost; + } + + public Integer getDestroyCost() { + if (destroyCost < 0) return EconomyHandler.destroyCost; + return destroyCost; + } + + public Boolean getToOwner() { + return toOwner; + } + + public boolean matches(BlockLocation topleft, int modX, int modZ) { + return matches(topleft, modX, modZ, false); + } + + public boolean matches(BlockLocation topleft, int modX, int modZ, boolean onCreate) { + HashMap portalTypes = new HashMap<>(types); + for (int y = 0; y < layout.length; y++) { + for (int x = 0; x < layout[y].length; x++) { + Character key = layout[y][x]; + + if (key.equals(ENTRANCE) || key.equals(EXIT)) { + if (Stargate.ignoreEntrance) continue; + + Material type = topleft.modRelative(x, y, 0, modX, 1, modZ).getType(); + + // Ignore entrance if it's air and we're creating a new gate + if (onCreate && type == Material.AIR) continue; + + if (type != portalBlockClosed && type != portalBlockOpen) { + Stargate.debug("Gate::Matches", "Entrance/Exit Material Mismatch: " + type); + return false; + } + } else if (!key.equals(ANYTHING)) { + Material id = portalTypes.get(key); + if (id == null) { + portalTypes.put(key, topleft.modRelative(x, y, 0, modX, 1, modZ).getType()); + } else if (topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != id) { + Stargate.debug("Gate::Matches", "Block Type Mismatch: " + topleft.modRelative(x, y, 0, modX, 1, modZ).getType() + " != " + id); + return false; + } + } + } + } + + return true; + } + + public static void registerGate(Gate gate) { + gates.put(gate.getFilename(), gate); + + Material blockID = gate.getControlBlock(); + + if (!controlBlocks.containsKey(blockID)) { + controlBlocks.put(blockID, new ArrayList<>()); + } + + controlBlocks.get(blockID).add(gate); + } + + public static Gate loadGate(File file) { + Scanner scanner = null; + boolean designing = false; + ArrayList> design = new ArrayList<>(); + HashMap types = new HashMap<>(); + HashMap config = new HashMap<>(); + HashSet frameTypes = new HashSet<>(); + int cols = 0; + + // Init types map + types.put(ENTRANCE, Material.AIR); + types.put(EXIT, Material.AIR); + types.put(ANYTHING, Material.AIR); + + try { + scanner = new Scanner(file); + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + + if (designing) { + ArrayList row = new ArrayList<>(); + + if (line.length() > cols) { + cols = line.length(); + } + + for (Character symbol : line.toCharArray()) { + if ((symbol.equals('?')) || (!types.containsKey(symbol))) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram"); + return null; + } + row.add(symbol); + } + + design.add(row); + } else { + if ((line.isEmpty()) || (!line.contains("="))) { + designing = true; + } else { + String[] split = line.split("="); + String key = split[0].trim(); + String value = split[1].trim(); + + if (key.length() == 1) { + Character symbol = key.charAt(0); + Material id = Material.getMaterial(value); + if (id == null) { + throw new Exception("Invalid material in line: " + line); + } + types.put(symbol, id); + frameTypes.add(id); + } else { + config.put(key, value); + } + } + } + } + } catch (Exception ex) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - " + ex.getMessage()); + return null; + } finally { + if (scanner != null) scanner.close(); + } + + Character[][] layout = new Character[design.size()][cols]; + + for (int y = 0; y < design.size(); y++) { + ArrayList row = design.get(y); + Character[] result = new Character[cols]; + + for (int x = 0; x < cols; x++) { + if (x < row.size()) { + result[x] = row.get(x); + } else { + result[x] = ' '; + } + } + + layout[y] = result; + } + + Gate gate = new Gate(file.getName(), layout, types); + + gate.portalBlockOpen = readConfig(config, gate, file, "portal-open", gate.portalBlockOpen); + gate.portalBlockClosed = readConfig(config, gate, file, "portal-closed", gate.portalBlockClosed); + gate.button = readConfig(config, gate, file, "button", gate.button); + gate.useCost = readConfig(config, gate, file, "usecost", -1); + gate.destroyCost = readConfig(config, gate, file, "destroycost", -1); + gate.createCost = readConfig(config, gate, file, "createcost", -1); + gate.toOwner = (config.containsKey("toowner") ? Boolean.valueOf(config.get("toowner")) : EconomyHandler.toOwner); + + if (gate.getControls().length != 2) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points."); + return null; + } + + if (!Tag.BUTTONS.isTagged(gate.button)) { + Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gate button must be a type of button."); + return null; + } + + // Merge frame types, add open mat to list + frameBlocks.addAll(frameTypes); + + gate.save(file.getParent() + "/"); // Updates format for version changes + return gate; + } + + private static int readConfig(HashMap config, Gate gate, File file, String key, int def) { + if (config.containsKey(key)) { + try { + return Integer.parseInt(config.get(key)); + } catch (NumberFormatException ex) { + Stargate.log.log(Level.WARNING, String.format("%s reading %s: %s is not numeric", ex.getClass().getName(), file, key)); + } + } + + return def; + } + + private static Material readConfig(HashMap config, Gate gate, File file, String key, Material def) { + if (config.containsKey(key)) { + Material mat = Material.getMaterial(config.get(key)); + if (mat != null) { + return mat; + } + Stargate.log.log(Level.WARNING, String.format("Error reading %s: %s is not a material", file, key)); + } + return def; + } + + public static void loadGates(String gateFolder) { + File dir = new File(gateFolder); + File[] files; + + if (dir.exists()) { + files = dir.listFiles(new StargateFilenameFilter()); + } else { + files = new File[0]; + } + + if (files == null || files.length == 0) { + if (dir.mkdir()) { + populateDefaults(gateFolder); + } + } else { + for (File file : files) { + Gate gate = loadGate(file); + if (gate != null) registerGate(gate); + } + } + } + + public static void populateDefaults(String gateFolder) { + Character[][] layout = new Character[][]{ + {' ', 'X', 'X', ' '}, + {'X', '.', '.', 'X'}, + {'-', '.', '.', '-'}, + {'X', '*', '.', 'X'}, + {' ', 'X', 'X', ' '}, + }; + HashMap types = new HashMap<>(); + types.put(ENTRANCE, Material.AIR); + types.put(EXIT, Material.AIR); + types.put(ANYTHING, Material.AIR); + types.put('X', Material.OBSIDIAN); + types.put('-', Material.OBSIDIAN); + + Gate gate = new Gate("nethergate.gate", layout, types); + gate.save(gateFolder); + registerGate(gate); + } + + public static Gate[] getGatesByControlBlock(Block block) { + return getGatesByControlBlock(block.getType()); + } + + public static Gate[] getGatesByControlBlock(Material type) { + Gate[] result = new Gate[0]; + ArrayList lookup = controlBlocks.get(type); + + if (lookup != null) result = lookup.toArray(result); + + return result; + } + + public static Gate getGateByName(String name) { + return gates.get(name); + } + + public static int getGateCount() { + return gates.size(); + } + + public static boolean isGateBlock(Material type) { + return frameBlocks.contains(type); + } + + static class StargateFilenameFilter implements FilenameFilter { + public boolean accept(File dir, String name) { + return name.endsWith(".gate"); + } + } + + public static void clearGates() { + gates.clear(); + controlBlocks.clear(); + frameBlocks.clear(); + } +} diff --git a/src/main/java/net/knarcraft/stargate/LanguageLoader.java b/src/main/java/net/knarcraft/stargate/LanguageLoader.java new file mode 100644 index 0000000..326ca3a --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/LanguageLoader.java @@ -0,0 +1,311 @@ +package net.knarcraft.stargate; + +import org.bukkit.ChatColor; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/* + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * This class is responsible for loading all strings which are translated into several languages + */ +public class LanguageLoader { + + // Variables + private final String languageFolder; + private String chosenLanguage; + private Map loadedStringTranslations; + private final Map loadedBackupStrings; + + /** + * Instantiates a new language loader + * @param languageFolder

The folder containing the language files

+ * @param chosenLanguage

The chosen plugin language

+ */ + public LanguageLoader(String languageFolder, String chosenLanguage) { + this.chosenLanguage = chosenLanguage; + this.languageFolder = languageFolder; + + File tmp = new File(languageFolder, chosenLanguage + ".txt"); + if (!tmp.exists()) { + tmp.getParentFile().mkdirs(); + } + updateLanguage(chosenLanguage); + + loadedStringTranslations = load(chosenLanguage); + // We have a default hashMap used for when new text is added. + InputStream inputStream = getClass().getResourceAsStream("/lang/" + chosenLanguage + ".txt"); + if (inputStream != null) { + loadedBackupStrings = load("en", inputStream); + } else { + loadedBackupStrings = null; + Stargate.log.severe("[stargate] Error loading backup language. There may be missing text in-game"); + } + } + + /** + * Reloads languages from the files on disk + */ + public void reload() { + // This extracts/updates the language as needed + updateLanguage(chosenLanguage); + loadedStringTranslations = load(chosenLanguage); + } + + /** + * Gets the string to display given its name/key + * @param name

The name/key of the string to display

+ * @return

The string in the user's preferred language

+ */ + public String getString(String name) { + String val = loadedStringTranslations.get(name); + if (val == null && loadedBackupStrings != null) val = loadedBackupStrings.get(name); + if (val == null) return ""; + return val; + } + + /** + * Sets the chosen plugin language + * @param chosenLanguage

The new plugin language

+ */ + public void setChosenLanguage(String chosenLanguage) { + this.chosenLanguage = chosenLanguage; + } + + /** + * Updates files in the plugin directory with contents from the compiled .jar + * @param language

The language to update

+ */ + private void updateLanguage(String language) { + // Load the current language file + ArrayList keyList = new ArrayList<>(); + ArrayList valueList = new ArrayList<>(); + + Map currentLanguageValues = load(language); + + InputStream inputStream = getClass().getResourceAsStream("/lang/" + language + ".txt"); + if (inputStream == null) return; + + boolean updated = false; + FileOutputStream fileOutputStream = null; + try { + if (readChangedLanguageStrings(inputStream, keyList, valueList, currentLanguageValues)) { + updated = true; + } + + // Save file + fileOutputStream = new FileOutputStream(languageFolder + language + ".txt"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8); + BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); + + // Output normal Language data + for (int i = 0; i < keyList.size(); i++) { + bufferedWriter.write(keyList.get(i) + valueList.get(i)); + bufferedWriter.newLine(); + } + bufferedWriter.newLine(); + // Output any custom language strings the user had + if (currentLanguageValues != null) { + for (String key : currentLanguageValues.keySet()) { + bufferedWriter.write(key + "=" + currentLanguageValues.get(key)); + bufferedWriter.newLine(); + } + } + + bufferedWriter.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (fileOutputStream != null) { + try { + fileOutputStream.close(); + } catch (Exception e) { + //Ignored + } + } + } + if (updated) { + Stargate.log.info("[stargate] Your language file (" + language + ".txt) has been updated"); + } + } + + /** + * Reads language strings + * @param inputStream

The input stream to read from

+ * @param keyList

The key list to add keys to

+ * @param valueList

The value list to add values to

+ * @param currentLanguageValues

The current values of the loaded/processed language

+ * @return

True if at least one line was updated

+ * @throws IOException

if unable to read a language file

+ */ + private boolean readChangedLanguageStrings(InputStream inputStream, List keyList, List valueList, + Map currentLanguageValues) throws IOException { + boolean updated = false; + // Input stuff + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + + String line = bufferedReader.readLine(); + boolean firstLine = true; + while (line != null) { + // Strip UTF BOM + if (firstLine) { + line = removeUTF8BOM(line); + firstLine = false; + } + // Split at first "=" + int equalSignIndex = line.indexOf('='); + if (equalSignIndex == -1) { + keyList.add(""); + valueList.add(""); + line = bufferedReader.readLine(); + continue; + } + String key = line.substring(0, equalSignIndex); + String value = line.substring(equalSignIndex); + + if (currentLanguageValues == null || currentLanguageValues.get(key) == null) { + keyList.add(key); + valueList.add(value); + updated = true; + } else { + keyList.add(key); + valueList.add("=" + currentLanguageValues.get(key).replace('\u00A7', '&')); + currentLanguageValues.remove(key); + } + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return updated; + } + + /** + * Loads the given language + * @param lang

The language to load

+ * @return

A mapping between loaded string indexes and the strings to display

+ */ + private Map load(String lang) { + return load(lang, null); + } + + /** + * Loads the given language + * @param lang

The language to load

+ * @param inputStream

An optional input stream to use. Defaults to using a file input stream

+ * @return

A mapping between loaded string indexes and the strings to display

+ */ + private Map load(String lang, InputStream inputStream) { + Map strings = new HashMap<>(); + FileInputStream fileInputStream = null; + InputStreamReader inputStreamReader; + try { + if (inputStream == null) { + fileInputStream = new FileInputStream(languageFolder + lang + ".txt"); + inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8); + } else { + inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + } + readLanguageFile(inputStreamReader, strings); + } catch (Exception e) { + return null; + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + //Ignored + } + } + } + return strings; + } + + /** + * Reads a language file given its input stream + * @param inputStreamReader

The input stream reader to read from

+ * @param strings

The loaded string pairs

+ * @throws IOException

If unable to read the file

+ */ + private void readLanguageFile(InputStreamReader inputStreamReader, Map strings) throws IOException { + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String line = bufferedReader.readLine(); + boolean firstLine = true; + while (line != null) { + // Strip UTF BOM + if (firstLine) { + line = removeUTF8BOM(line); + firstLine = false; + } + // Split at first "=" + int equalSignIndex = line.indexOf('='); + if (equalSignIndex == -1) { + line = bufferedReader.readLine(); + continue; + } + String key = line.substring(0, equalSignIndex); + String val = ChatColor.translateAlternateColorCodes('&', line.substring(equalSignIndex + 1)); + strings.put(key, val); + line = bufferedReader.readLine(); + } + } + + /** + * Prints debug output to the console for checking of loading language strings/translations + */ + public void debug() { + Set keys = loadedStringTranslations.keySet(); + for (String key : keys) { + Stargate.debug("LanguageLoader::Debug::loadedStringTranslations", key + " => " + loadedStringTranslations.get(key)); + } + if (loadedBackupStrings == null) return; + keys = loadedBackupStrings.keySet(); + for (String key : keys) { + Stargate.debug("LanguageLoader::Debug::loadedBackupStrings", key + " => " + loadedBackupStrings.get(key)); + } + } + + /** + * Removes the UTF-8 Byte Order Mark if present + * @param string

The string to remove the BOM from

+ * @return

A string guaranteed without a BOM

+ */ + private String removeUTF8BOM(String string) { + String UTF8_BOM = "\uFEFF"; + if (string.startsWith(UTF8_BOM)) { + string = string.substring(1); + } + return string; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/Portal.java b/src/main/java/net/knarcraft/stargate/Portal.java new file mode 100644 index 0000000..dca3bd0 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/Portal.java @@ -0,0 +1,1503 @@ +package net.knarcraft.stargate; + +import net.knarcraft.stargate.event.StargateActivateEvent; +import net.knarcraft.stargate.event.StargateCloseEvent; +import net.knarcraft.stargate.event.StargateCreateEvent; +import net.knarcraft.stargate.event.StargateDeactivateEvent; +import net.knarcraft.stargate.event.StargateOpenEvent; +import net.knarcraft.stargate.event.StargatePortalEvent; +import org.bukkit.Axis; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.Powerable; +import org.bukkit.block.data.type.WallSign; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Vehicle; +import org.bukkit.entity.minecart.StorageMinecart; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.util.Vector; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.Scanner; +import java.util.UUID; +import java.util.logging.Level; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011 Shaun (sturmeh) + * Copyright (C) 2011 Dinnerbone + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class Portal { + + // Static variables used to store portal lists + private static final HashMap lookupBlocks = new HashMap<>(); + private static final HashMap lookupEntrances = new HashMap<>(); + private static final HashMap lookupControls = new HashMap<>(); + private static final ArrayList allPortals = new ArrayList<>(); + private static final HashMap> allPortalsNet = new HashMap<>(); + private static final HashMap> lookupNamesNet = new HashMap<>(); + + // A list of Bungee gates + private static final HashMap bungeePortals = new HashMap<>(); + + // Gate location block info + private final BlockLocation topLeft; + private final int modX; + private final int modZ; + private final float rotX; + private final Axis rot; + + // Block references + private final BlockLocation id; + private BlockLocation button; + private BlockLocation[] frame; + private BlockLocation[] entrances; + + // Gate information + private String name; + private String destination; + private String lastDest = ""; + private String network; + private final Gate gate; + private String ownerName = ""; + private UUID ownerUUID = null; + private final World world; + private boolean verified; + private boolean fixed; + + // Options + private boolean hidden = false; + private boolean alwaysOn = false; + private boolean priv = false; + private boolean free = false; + private boolean backwards = false; + private boolean show = false; + private boolean noNetwork = false; + private boolean random = false; + private boolean bungee = false; + + // In-use information + private Player player; + private Player activePlayer; + private ArrayList destinations = new ArrayList<>(); + private boolean isOpen = false; + private long openTime; + + private Portal(BlockLocation topLeft, int modX, int modZ, + float rotX, BlockLocation id, BlockLocation button, + String dest, String name, + boolean verified, String network, Gate gate, UUID ownerUUID, String ownerName, + boolean hidden, boolean alwaysOn, boolean priv, boolean free, boolean backwards, boolean show, boolean noNetwork, boolean random, boolean bungee) { + this.topLeft = topLeft; + this.modX = modX; + this.modZ = modZ; + this.rotX = rotX; + this.rot = rotX == 0.0F || rotX == 180.0F ? Axis.X : Axis.Z; + this.id = id; + this.destination = dest; + this.button = button; + this.verified = verified; + this.network = network; + this.name = name; + this.gate = gate; + this.ownerUUID = ownerUUID; + this.ownerName = ownerName; + this.hidden = hidden; + this.alwaysOn = alwaysOn; + this.priv = priv; + this.free = free; + this.backwards = backwards; + this.show = show; + this.noNetwork = noNetwork; + this.random = random; + this.bungee = bungee; + this.world = topLeft.getWorld(); + this.fixed = dest.length() > 0 || this.random || this.bungee; + + if (this.isAlwaysOn() && !this.isFixed()) { + this.alwaysOn = false; + Stargate.debug("Portal", "Can not create a non-fixed always-on gate. Setting AlwaysOn = false"); + } + + if (this.random && !this.isAlwaysOn()) { + this.alwaysOn = true; + Stargate.debug("Portal", "Gate marked as random, set to always-on"); + } + + if (verified) { + this.drawSign(); + } + } + + /** + * Option Check Functions + */ + public boolean isOpen() { + return isOpen || isAlwaysOn(); + } + + public boolean isAlwaysOn() { + return alwaysOn; + } + + public boolean isHidden() { + return hidden; + } + + public boolean isPrivate() { + return priv; + } + + public boolean isFree() { + return free; + } + + public boolean isBackwards() { + return backwards; + } + + public boolean isShown() { + return show; + } + + public boolean isNoNetwork() { + return noNetwork; + } + + public boolean isRandom() { + return random; + } + + public boolean isBungee() { + return bungee; + } + + public void setAlwaysOn(boolean alwaysOn) { + this.alwaysOn = alwaysOn; + } + + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + public void setPrivate(boolean priv) { + this.priv = priv; + } + + public void setFree(boolean free) { + this.free = free; + } + + public void setBackwards(boolean backwards) { + this.backwards = backwards; + } + + public void setShown(boolean show) { + this.show = show; + } + + public void setNoNetwork(boolean noNetwork) { + this.noNetwork = noNetwork; + } + + public void setRandom(boolean random) { + this.random = random; + } + + /** + * Getters and Setters + */ + + public float getRotation() { + return rotX; + } + + public Axis getAxis() { + return rot; + } + + public Player getActivePlayer() { + return activePlayer; + } + + public String getNetwork() { + return network; + } + + public void setNetwork(String network) { + this.network = network; + } + + public long getOpenTime() { + return openTime; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = filterName(name); + drawSign(); + } + + public Portal getDestination(Player player) { + if (isRandom()) { + destinations = getDestinations(player, getNetwork()); + if (destinations.size() == 0) { + return null; + } + String dest = destinations.get((new Random()).nextInt(destinations.size())); + destinations.clear(); + return Portal.getByName(dest, getNetwork()); + } + return Portal.getByName(destination, getNetwork()); + } + + public Portal getDestination() { + return getDestination(null); + } + + public void setDestination(Portal destination) { + setDestination(destination.getName()); + } + + public void setDestination(String destination) { + this.destination = destination; + } + + public String getDestinationName() { + return destination; + } + + public Gate getGate() { + return gate; + } + + public String getOwnerName() { + return ownerName; + } + + public UUID getOwnerUUID() { + return ownerUUID; + } + + public void setOwner(UUID owner) { + this.ownerUUID = owner; + } + + public boolean isOwner(Player player) { + if (this.ownerUUID != null) { + return player.getUniqueId().compareTo(this.ownerUUID) == 0; + } else { + return player.getName().equalsIgnoreCase(this.ownerName); + } + } + + public BlockLocation[] getEntrances() { + if (entrances == null) { + RelativeBlockVector[] space = gate.getEntrances(); + entrances = new BlockLocation[space.length]; + int i = 0; + + for (RelativeBlockVector vector : space) { + entrances[i++] = getBlockAt(vector); + } + } + return entrances; + } + + public BlockLocation[] getFrame() { + if (frame == null) { + RelativeBlockVector[] border = gate.getBorder(); + frame = new BlockLocation[border.length]; + int i = 0; + + for (RelativeBlockVector vector : border) { + frame[i++] = getBlockAt(vector); + } + } + + return frame; + } + + public BlockLocation getSign() { + return id; + } + + public World getWorld() { + return world; + } + + public BlockLocation getButton() { + return button; + } + + public void setButton(BlockLocation button) { + this.button = button; + } + + public static ArrayList getNetwork(String network) { + return allPortalsNet.get(network.toLowerCase()); + } + + public boolean open(boolean force) { + return open(null, force); + } + + public boolean open(Player openFor, boolean force) { + // Call the StargateOpenEvent + StargateOpenEvent event = new StargateOpenEvent(openFor, this, force); + Stargate.server.getPluginManager().callEvent(event); + if (event.isCancelled()) return false; + force = event.getForce(); + + if (isOpen() && !force) return false; + + Material openType = gate.getPortalBlockOpen(); + Axis ax = openType == Material.NETHER_PORTAL ? rot : null; + for (BlockLocation inside : getEntrances()) { + Stargate.blockPopulatorQueue.add(new BloxPopulator(inside, openType, ax)); + } + + isOpen = true; + openTime = System.currentTimeMillis() / 1000; + Stargate.openList.add(this); + Stargate.activeList.remove(this); + + // Open remote gate + if (!isAlwaysOn()) { + player = openFor; + + Portal end = getDestination(); + // Only open dest if it's not-fixed or points at this gate + if (!random && end != null && (!end.isFixed() || end.getDestinationName().equalsIgnoreCase(getName())) && !end.isOpen()) { + end.open(openFor, false); + end.setDestination(this); + if (end.isVerified()) end.drawSign(); + } + } + + return true; + } + + public void close(boolean force) { + if (!isOpen) return; + // Call the StargateCloseEvent + StargateCloseEvent event = new StargateCloseEvent(this, force); + Stargate.server.getPluginManager().callEvent(event); + if (event.isCancelled()) return; + force = event.getForce(); + + if (isAlwaysOn() && !force) return; // Only close always-open if forced + + // Close this gate, then the dest gate. + Material closedType = gate.getPortalBlockClosed(); + for (BlockLocation inside : getEntrances()) { + Stargate.blockPopulatorQueue.add(new BloxPopulator(inside, closedType)); + } + + player = null; + isOpen = false; + Stargate.openList.remove(this); + Stargate.activeList.remove(this); + + if (!isAlwaysOn()) { + Portal end = getDestination(); + + if (end != null && end.isOpen()) { + end.deactivate(); // Clear it's destination first. + end.close(false); + } + } + + deactivate(); + } + + public boolean isOpenFor(Player player) { + if (!isOpen) { + return false; + } + if ((isAlwaysOn()) || (this.player == null)) { + return true; + } + return (player != null) && (player.getName().equalsIgnoreCase(this.player.getName())); + } + + public boolean isFixed() { + return fixed; + } + + public boolean isPowered() { + RelativeBlockVector[] controls = gate.getControls(); + + for (RelativeBlockVector vector : controls) { + BlockData data = getBlockAt(vector).getBlock().getBlockData(); + + if (data instanceof Powerable && ((Powerable) data).isPowered()) { + return true; + } + } + + return false; + } + + public void teleport(Player player, Portal origin, PlayerMoveEvent event) { + Location traveller = player.getLocation(); + Location exit = getExit(traveller); + + // Handle backwards gates + int adjust = 180; + if (isBackwards() != origin.isBackwards()) + adjust = 0; + exit.setYaw(traveller.getYaw() - origin.getRotation() + this.getRotation() + adjust); + + // Call the StargatePortalEvent to allow plugins to change destination + if (!origin.equals(this)) { + StargatePortalEvent pEvent = new StargatePortalEvent(player, origin, this, exit); + Stargate.server.getPluginManager().callEvent(pEvent); + // Teleport is cancelled + if (pEvent.isCancelled()) { + origin.teleport(player, origin, event); + return; + } + // Update exit if needed + exit = pEvent.getExit(); + } + + // If no event is passed in, assume it's a teleport, and act as such + if (event == null) { + exit.setYaw(this.getRotation()); + player.teleport(exit); + } else { + // The new method to teleport in a move event is set the "to" field. + event.setTo(exit); + } + } + + public void teleport(final Vehicle vehicle) { + Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), vehicle.getLocation().getZ()); + Location exit = getExit(traveller); + + double velocity = vehicle.getVelocity().length(); + + // Stop and teleport + vehicle.setVelocity(new Vector()); + + // Get new velocity + final Vector newVelocity = new Vector(modX, 0.0F, modZ); + newVelocity.multiply(velocity); + + List passengers = vehicle.getPassengers(); + if (!passengers.isEmpty()) { + final Vehicle v = exit.getWorld().spawn(exit, vehicle.getClass()); + final Entity passenger = passengers.get(0); + vehicle.eject(); + vehicle.remove(); + passenger.eject(); + passenger.teleport(exit); + Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, () -> { + v.addPassenger(passenger); + v.setVelocity(newVelocity); + }, 1); + } else { + Vehicle mc = exit.getWorld().spawn(exit, vehicle.getClass()); + if (mc instanceof StorageMinecart) { + StorageMinecart smc = (StorageMinecart) mc; + smc.getInventory().setContents(((StorageMinecart) vehicle).getInventory().getContents()); + } + mc.setVelocity(newVelocity); + vehicle.remove(); + } + } + + public Location getExit(Location traveller) { + Location loc = null; + // Check if the gate has an exit block + if (gate.getExit() != null) { + BlockLocation exit = getBlockAt(gate.getExit()); + int back = (isBackwards()) ? -1 : 1; + loc = exit.modRelativeLoc(0D, 0D, 1D, traveller.getYaw(), traveller.getPitch(), modX * back, 1, modZ * back); + } else { + Stargate.log.log(Level.WARNING, "[stargate] Missing destination point in .gate file " + gate.getFilename()); + } + + if (loc != null) { + BlockData bd = getWorld().getBlockAt(loc).getBlockData(); + if (bd instanceof Bisected && ((Bisected) bd).getHalf() == Bisected.Half.BOTTOM) { + loc.add(0, 0.5, 0); + } + + loc.setPitch(traveller.getPitch()); + return loc; + } + return traveller; + } + + public boolean isChunkLoaded() { + return getWorld().isChunkLoaded(topLeft.getBlock().getChunk()); + } + + public boolean isVerified() { + verified = true; + if (!Stargate.verifyPortals) { + return true; + } + for (RelativeBlockVector control : gate.getControls()) { + verified = verified && getBlockAt(control).getBlock().getType().equals(gate.getControlBlock()); + } + return verified; + } + + public boolean wasVerified() { + if (!Stargate.verifyPortals) { + return true; + } + return verified; + } + + public boolean checkIntegrity() { + if (!Stargate.verifyPortals) { + return true; + } + return gate.matches(topLeft, modX, modZ); + } + + public ArrayList getDestinations(Player player, String network) { + ArrayList destinations = new ArrayList<>(); + for (String dest : allPortalsNet.get(network.toLowerCase())) { + Portal portal = getByName(dest, network); + if (portal == null) continue; + // Check if dest is a random gate + if (portal.isRandom()) continue; + // Check if dest is always open (Don't show if so) + if (portal.isAlwaysOn() && !portal.isShown()) continue; + // Check if dest is this portal + if (dest.equalsIgnoreCase(getName())) continue; + // Check if dest is a fixed gate not pointing to this gate + if (portal.isFixed() && !portal.getDestinationName().equalsIgnoreCase(getName())) continue; + // Allow random use by non-players (Minecarts) + if (player == null) { + destinations.add(portal.getName()); + continue; + } + // Check if this player can access the dest world + if (!Stargate.canAccessWorld(player, portal.getWorld().getName())) continue; + // Visible to this player. + if (Stargate.canSee(player, portal)) { + destinations.add(portal.getName()); + } + } + return destinations; + } + + public boolean activate(Player player) { + destinations.clear(); + destination = ""; + Stargate.activeList.add(this); + activePlayer = player; + String network = getNetwork(); + destinations = getDestinations(player, network); + if (Stargate.sortLists) { + Collections.sort(destinations); + } + if (Stargate.destMemory && !lastDest.isEmpty() && destinations.contains(lastDest)) { + destination = lastDest; + } + + StargateActivateEvent event = new StargateActivateEvent(this, player, destinations, destination); + Stargate.server.getPluginManager().callEvent(event); + if (event.isCancelled()) { + Stargate.activeList.remove(this); + return false; + } + destination = event.getDestination(); + destinations = event.getDestinations(); + drawSign(); + return true; + } + + public void deactivate() { + StargateDeactivateEvent event = new StargateDeactivateEvent(this); + Stargate.server.getPluginManager().callEvent(event); + if (event.isCancelled()) return; + + Stargate.activeList.remove(this); + if (isFixed()) { + return; + } + destinations.clear(); + destination = ""; + activePlayer = null; + drawSign(); + } + + public boolean isActive() { + return isFixed() || (destinations.size() > 0); + } + + public void cycleDestination(Player player) { + cycleDestination(player, 1); + } + + public void cycleDestination(Player player, int dir) { + boolean activate = false; + if (!isActive() || getActivePlayer() != player) { + // If the event is cancelled, return + if (!activate(player)) { + return; + } + Stargate.debug("cycleDestination", "Network Size: " + allPortalsNet.get(network.toLowerCase()).size()); + Stargate.debug("cycleDestination", "Player has access to: " + destinations.size()); + activate = true; + } + + if (destinations.size() == 0) { + Stargate.sendMessage(player, Stargate.getString("destEmpty")); + return; + } + + if (!Stargate.destMemory || !activate || lastDest.isEmpty()) { + int index = destinations.indexOf(destination); + index += dir; + if (index >= destinations.size()) + index = 0; + else if (index < 0) + index = destinations.size() - 1; + destination = destinations.get(index); + lastDest = destination; + } + openTime = System.currentTimeMillis() / 1000; + drawSign(); + } + + public final void drawSign() { + BlockState state = id.getBlock().getState(); + if (!(state instanceof Sign)) { + Stargate.log.warning("[stargate] Sign block is not a Sign object"); + Stargate.debug("Portal::drawSign", "Block: " + id.getBlock().getType() + " @ " + id.getBlock().getLocation()); + return; + } + Sign sign = (Sign) state; + Stargate.setLine(sign, 0, "-" + name + "-"); + int max = destinations.size() - 1; + int done = 0; + + if (!isActive()) { + Stargate.setLine(sign, ++done, Stargate.getString("signRightClick")); + Stargate.setLine(sign, ++done, Stargate.getString("signToUse")); + if (!noNetwork) { + Stargate.setLine(sign, ++done, "(" + network + ")"); + } + } else { + // Awesome new logic for Bungee gates + if (isBungee()) { + Stargate.setLine(sign, ++done, Stargate.getString("bungeeSign")); + Stargate.setLine(sign, ++done, ">" + destination + "<"); + Stargate.setLine(sign, ++done, "[" + network + "]"); + } else if (isFixed()) { + if (isRandom()) { + Stargate.setLine(sign, ++done, "> " + Stargate.getString("signRandom") + " <"); + } else { + Stargate.setLine(sign, ++done, ">" + destination + "<"); + } + if (noNetwork) { + Stargate.setLine(sign, ++done, ""); + } else { + Stargate.setLine(sign, ++done, "(" + network + ")"); + } + Portal dest = Portal.getByName(destination, network); + if (dest == null && !isRandom()) { + Stargate.setLine(sign, ++done, Stargate.getString("signDisconnected")); + } else { + Stargate.setLine(sign, ++done, ""); + } + } else { + int index = destinations.indexOf(destination); + if ((index == max) && (max > 1) && (++done <= 3)) { + if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { + Portal dest = Portal.getByName(destinations.get(index - 2), network); + boolean green = Stargate.isFree(activePlayer, this, dest); + Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 2)); + } else { + Stargate.setLine(sign, done, destinations.get(index - 2)); + } + } + if ((index > 0) && (++done <= 3)) { + if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { + Portal dest = Portal.getByName(destinations.get(index - 1), network); + boolean green = Stargate.isFree(activePlayer, this, dest); + Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 1)); + } else { + Stargate.setLine(sign, done, destinations.get(index - 1)); + } + } + if (++done <= 3) { + if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { + Portal dest = Portal.getByName(destination, network); + boolean green = Stargate.isFree(activePlayer, this, dest); + Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + ">" + destination + "<"); + } else { + Stargate.setLine(sign, done, " >" + destination + "< "); + } + } + if ((max >= index + 1) && (++done <= 3)) { + if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { + Portal dest = Portal.getByName(destinations.get(index + 1), network); + boolean green = Stargate.isFree(activePlayer, this, dest); + Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 1)); + } else { + Stargate.setLine(sign, done, destinations.get(index + 1)); + } + } + if ((max >= index + 2) && (++done <= 3)) { + if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { + Portal dest = Portal.getByName(destinations.get(index + 2), network); + boolean green = Stargate.isFree(activePlayer, this, dest); + Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 2)); + } else { + Stargate.setLine(sign, done, destinations.get(index + 2)); + } + } + } + } + + for (done++; done <= 3; done++) { + sign.setLine(done, ""); + } + + sign.update(); + } + + public void unregister(boolean removeAll) { + Stargate.debug("Unregister", "Unregistering gate " + getName()); + close(true); + + for (BlockLocation block : getFrame()) { + lookupBlocks.remove(block); + } + // Include the sign and button + lookupBlocks.remove(id); + if (button != null) { + lookupBlocks.remove(button); + } + + lookupControls.remove(id); + if (button != null) + lookupControls.remove(button); + + for (BlockLocation entrance : getEntrances()) { + lookupEntrances.remove(entrance); + } + + if (removeAll) + allPortals.remove(this); + + if (bungee) { + bungeePortals.remove(getName().toLowerCase()); + } else { + lookupNamesNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); + allPortalsNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); + + for (String originName : allPortalsNet.get(getNetwork().toLowerCase())) { + Portal origin = Portal.getByName(originName, getNetwork()); + if (origin == null) continue; + if (!origin.getDestinationName().equalsIgnoreCase(getName())) continue; + if (!origin.isVerified()) continue; + if (origin.isFixed()) origin.drawSign(); + if (origin.isAlwaysOn()) origin.close(true); + } + } + + if (id.getBlock().getBlockData() instanceof WallSign) { + Sign sign = (Sign) id.getBlock().getState(); + sign.setLine(0, getName()); + sign.setLine(1, ""); + sign.setLine(2, ""); + sign.setLine(3, ""); + sign.update(); + } + + saveAllGates(getWorld()); + } + + private BlockLocation getBlockAt(RelativeBlockVector vector) { + return topLeft.modRelative(vector.getRight(), vector.getDepth(), vector.getDistance(), modX, 1, modZ); + } + + private void register() { + fixed = destination.length() > 0 || random || bungee; + + // Bungee gates are stored in their own list + if (isBungee()) { + bungeePortals.put(getName().toLowerCase(), this); + } else { + // Check if network exists in our network list + if (!lookupNamesNet.containsKey(getNetwork().toLowerCase())) { + Stargate.debug("register", "Network " + getNetwork() + " not in lookupNamesNet, adding"); + lookupNamesNet.put(getNetwork().toLowerCase(), new HashMap<>()); + } + lookupNamesNet.get(getNetwork().toLowerCase()).put(getName().toLowerCase(), this); + + // Check if this network exists + if (!allPortalsNet.containsKey(getNetwork().toLowerCase())) { + Stargate.debug("register", "Network " + getNetwork() + " not in allPortalsNet, adding"); + allPortalsNet.put(getNetwork().toLowerCase(), new ArrayList<>()); + } + allPortalsNet.get(getNetwork().toLowerCase()).add(getName().toLowerCase()); + } + + for (BlockLocation block : getFrame()) { + lookupBlocks.put(block, this); + } + // Include the sign and button + lookupBlocks.put(id, this); + if (button != null) { + lookupBlocks.put(button, this); + } + + lookupControls.put(id, this); + if (button != null) + lookupControls.put(button, this); + + for (BlockLocation entrance : getEntrances()) { + lookupEntrances.put(entrance, this); + } + + allPortals.add(this); + } + + public static Portal createPortal(SignChangeEvent event, Player player) { + BlockLocation id = new BlockLocation(event.getBlock()); + Block idParent = id.getParent(); + if (idParent == null) { + return null; + } + + if (Gate.getGatesByControlBlock(idParent).length == 0) return null; + + if (Portal.getByBlock(idParent) != null) { + Stargate.debug("createPortal", "idParent belongs to existing gate"); + return null; + } + + BlockLocation parent = new BlockLocation(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); + BlockLocation topleft = null; + String name = filterName(event.getLine(0)); + String destName = filterName(event.getLine(1)); + String network = filterName(event.getLine(2)); + String options = filterName(event.getLine(3)).toLowerCase(); + boolean hidden = (options.indexOf('h') != -1); + boolean alwaysOn = (options.indexOf('a') != -1); + boolean priv = (options.indexOf('p') != -1); + boolean free = (options.indexOf('f') != -1); + boolean backwards = (options.indexOf('b') != -1); + boolean show = (options.indexOf('s') != -1); + boolean noNetwork = (options.indexOf('n') != -1); + boolean random = (options.indexOf('r') != -1); + boolean bungee = (options.indexOf('u') != -1); + + // Check permissions for options. + if (hidden && !Stargate.canOption(player, "hidden")) hidden = false; + if (alwaysOn && !Stargate.canOption(player, "alwayson")) alwaysOn = false; + if (priv && !Stargate.canOption(player, "private")) priv = false; + if (free && !Stargate.canOption(player, "free")) free = false; + if (backwards && !Stargate.canOption(player, "backwards")) backwards = false; + if (show && !Stargate.canOption(player, "show")) show = false; + if (noNetwork && !Stargate.canOption(player, "nonetwork")) noNetwork = false; + if (random && !Stargate.canOption(player, "random")) random = false; + + // Can not create a non-fixed always-on gate. + if (alwaysOn && destName.length() == 0) { + alwaysOn = false; + } + + // Show isn't useful if A is false + if (show && !alwaysOn) { + show = false; + } + + // Random gates are always on and can't be shown + if (random) { + alwaysOn = true; + show = false; + } + + // Bungee gates are always on and don't support Random + if (bungee) { + alwaysOn = true; + random = false; + } + + // Moved the layout check so as to avoid invalid messages when not making a gate + int modX = 0; + int modZ = 0; + float rotX = 0f; + BlockFace buttonfacing = BlockFace.DOWN; + + if (idParent.getX() > id.getBlock().getX()) { + modZ -= 1; + rotX = 90f; + buttonfacing = BlockFace.WEST; + } else if (idParent.getX() < id.getBlock().getX()) { + modZ += 1; + rotX = 270f; + buttonfacing = BlockFace.EAST; + } else if (idParent.getZ() > id.getBlock().getZ()) { + modX += 1; + rotX = 180f; + buttonfacing = BlockFace.NORTH; + } else if (idParent.getZ() < id.getBlock().getZ()) { + modX -= 1; + rotX = 0f; + buttonfacing = BlockFace.SOUTH; + } + + Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); + Gate gate = null; + RelativeBlockVector buttonVector = null; + + for (Gate possibility : possibleGates) { + if ((gate == null) && (buttonVector == null)) { + RelativeBlockVector[] vectors = possibility.getControls(); + RelativeBlockVector otherControl = null; + + for (RelativeBlockVector vector : vectors) { + BlockLocation tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); + + if (gate == null) { + if (possibility.matches(tl, modX, modZ, true)) { + gate = possibility; + topleft = tl; + + if (otherControl != null) { + buttonVector = otherControl; + } + } + } else if (otherControl != null) { + buttonVector = vector; + } + + otherControl = vector; + } + } + } + + if ((gate == null) || (buttonVector == null)) { + Stargate.debug("createPortal", "Could not find matching gate layout"); + return null; + } + + // If the player is trying to create a Bungee gate without permissions, drop out here + // Do this after the gate layout check, in the least + if (bungee) { + if (!Stargate.enableBungee) { + Stargate.sendMessage(player, Stargate.getString("bungeeDisabled")); + return null; + } else if (!Stargate.hasPerm(player, "stargate.admin.bungee")) { + Stargate.sendMessage(player, Stargate.getString("bungeeDeny")); + return null; + } else if (destName.isEmpty() || network.isEmpty()) { + Stargate.sendMessage(player, Stargate.getString("bungeeEmpty")); + return null; + } + } + + // Debug + Stargate.debug("createPortal", "h = " + hidden + " a = " + alwaysOn + " p = " + priv + " f = " + free + " b = " + backwards + " s = " + show + " n = " + noNetwork + " r = " + random + " u = " + bungee); + + if (!bungee && (network.length() < 1 || network.length() > 11)) { + network = Stargate.getDefaultNetwork(); + } + + boolean deny = false; + String denyMsg = ""; + + // Check if the player can create gates on this network + if (!bungee && !Stargate.canCreate(player, network)) { + Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal"); + if (Stargate.canCreatePersonal(player)) { + network = player.getName(); + if (network.length() > 11) network = network.substring(0, 11); + Stargate.debug("createPortal", "Creating personal portal"); + Stargate.sendMessage(player, Stargate.getString("createPersonal")); + } else { + Stargate.debug("createPortal", "Player does not have access to network"); + deny = true; + denyMsg = Stargate.getString("createNetDeny"); + //return null; + } + } + + // Check if the player can create this gate layout + String gateName = gate.getFilename(); + gateName = gateName.substring(0, gateName.indexOf('.')); + if (!deny && !Stargate.canCreateGate(player, gateName)) { + Stargate.debug("createPortal", "Player does not have access to gate layout"); + deny = true; + denyMsg = Stargate.getString("createGateDeny"); + } + + // Check if the user can create gates to this world. + if (!bungee && !deny && destName.length() > 0) { + Portal p = Portal.getByName(destName, network); + if (p != null) { + String world = p.getWorld().getName(); + if (!Stargate.canAccessWorld(player, world)) { + Stargate.debug("canCreate", "Player does not have access to destination world"); + deny = true; + denyMsg = Stargate.getString("createWorldDeny"); + } + } + } + + // Bleh, gotta check to make sure none of this gate belongs to another gate. Boo slow. + for (RelativeBlockVector v : gate.getBorder()) { + BlockLocation b = topleft.modRelative(v.getRight(), v.getDepth(), v.getDistance(), modX, 1, modZ); + if (Portal.getByBlock(b.getBlock()) != null) { + Stargate.debug("createPortal", "Gate conflicts with existing gate"); + Stargate.sendMessage(player, Stargate.getString("createConflict")); + return null; + } + } + + BlockLocation button = null; + Portal portal; + portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, false, network, gate, player.getUniqueId(), player.getName(), hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); + + int cost = Stargate.getCreateCost(player, gate); + + // Call StargateCreateEvent + StargateCreateEvent cEvent = new StargateCreateEvent(player, portal, event.getLines(), deny, denyMsg, cost); + Stargate.server.getPluginManager().callEvent(cEvent); + if (cEvent.isCancelled()) { + return null; + } + if (cEvent.getDeny()) { + Stargate.sendMessage(player, cEvent.getDenyReason()); + return null; + } + + cost = cEvent.getCost(); + + // Name & Network can be changed in the event, so do these checks here. + if (portal.getName().length() < 1 || portal.getName().length() > 11) { + Stargate.debug("createPortal", "Name length error"); + Stargate.sendMessage(player, Stargate.getString("createNameLength")); + return null; + } + + // Don't do network checks for bungee gates + if (portal.isBungee()) { + if (bungeePortals.get(portal.getName().toLowerCase()) != null) { + Stargate.debug("createPortal::Bungee", "Gate Exists"); + Stargate.sendMessage(player, Stargate.getString("createExists")); + return null; + } + } else { + if (getByName(portal.getName(), portal.getNetwork()) != null) { + Stargate.debug("createPortal", "Name Error"); + Stargate.sendMessage(player, Stargate.getString("createExists")); + return null; + } + + // Check if there are too many gates in this network + ArrayList netList = allPortalsNet.get(portal.getNetwork().toLowerCase()); + if (Stargate.maxGates > 0 && netList != null && netList.size() >= Stargate.maxGates) { + Stargate.sendMessage(player, Stargate.getString("createFull")); + return null; + } + } + + if (cost > 0) { + if (!Stargate.chargePlayer(player, cost)) { + String inFundMsg = Stargate.getString("ecoInFunds"); + inFundMsg = Stargate.replaceVars(inFundMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), name}); + Stargate.sendMessage(player, inFundMsg); + Stargate.debug("createPortal", "Insufficient Funds"); + return null; + } + String deductMsg = Stargate.getString("ecoDeduct"); + deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), name}); + Stargate.sendMessage(player, deductMsg, false); + } + + // No button on an always-open gate. + if (!alwaysOn) { + button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); + Directional buttondata = (Directional) Bukkit.createBlockData(gate.getButton()); + buttondata.setFacing(buttonfacing); + button.getBlock().setBlockData(buttondata); + portal.setButton(button); + } + + portal.register(); + portal.drawSign(); + // Open always on gate + if (portal.isRandom() || portal.isBungee()) { + portal.open(true); + } else if (portal.isAlwaysOn()) { + Portal dest = Portal.getByName(destName, portal.getNetwork()); + if (dest != null) { + portal.open(true); + dest.drawSign(); + } + // Set the inside of the gate to its closed material + } else { + for (BlockLocation inside : portal.getEntrances()) { + inside.setType(portal.getGate().getPortalBlockClosed()); + } + } + + // Don't do network stuff for bungee gates + if (!portal.isBungee()) { + // Open any always on gate pointing at this gate + for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { + Portal origin = Portal.getByName(originName, portal.getNetwork()); + if (origin == null) continue; + if (!origin.getDestinationName().equalsIgnoreCase(portal.getName())) continue; + if (!origin.isVerified()) continue; + if (origin.isFixed()) origin.drawSign(); + if (origin.isAlwaysOn()) origin.open(true); + } + } + + saveAllGates(portal.getWorld()); + + return portal; + } + + public static Portal getByName(String name, String network) { + if (!lookupNamesNet.containsKey(network.toLowerCase())) return null; + return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); + + } + + public static Portal getByEntrance(Location location) { + return lookupEntrances.get(new BlockLocation(location)); + } + + public static Portal getByEntrance(Block block) { + return lookupEntrances.get(new BlockLocation(block)); + } + + public static Portal getByAdjacentEntrance(Location loc) { + int centerX = loc.getBlockX(); + int centerY = loc.getBlockY(); + int centerZ = loc.getBlockZ(); + World world = loc.getWorld(); + Portal portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX + 1, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX - 1, centerY, centerZ)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ + 1)); + if (portal != null) { + return portal; + } + portal = lookupEntrances.get(new BlockLocation(world, centerX, centerY, centerZ - 1)); + if (portal != null) { + return portal; + } + return null; + } + + public static Portal getByControl(Block block) { + return lookupControls.get(new BlockLocation(block)); + } + + public static Portal getByBlock(Block block) { + return lookupBlocks.get(new BlockLocation(block)); + } + + public static Portal getBungeeGate(String name) { + return bungeePortals.get(name.toLowerCase()); + } + + public static void saveAllGates(World world) { + Stargate.managedWorlds.add(world.getName()); + String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; + + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); + + for (Portal portal : allPortals) { + String wName = portal.world.getName(); + if (!wName.equalsIgnoreCase(world.getName())) continue; + StringBuilder builder = new StringBuilder(); + BlockLocation sign = portal.id; + BlockLocation button = portal.button; + + builder.append(portal.name); + builder.append(':'); + builder.append(sign.toString()); + builder.append(':'); + builder.append((button != null) ? button.toString() : ""); + builder.append(':'); + builder.append(portal.modX); + builder.append(':'); + builder.append(portal.modZ); + builder.append(':'); + builder.append(portal.rotX); + builder.append(':'); + builder.append(portal.topLeft.toString()); + builder.append(':'); + builder.append(portal.gate.getFilename()); + builder.append(':'); + builder.append(portal.isFixed() ? portal.getDestinationName() : ""); + builder.append(':'); + builder.append(portal.getNetwork()); + builder.append(':'); + UUID owner = portal.getOwnerUUID(); + if (owner != null) { + builder.append(portal.getOwnerUUID().toString()); + } else { + builder.append(portal.getOwnerName()); + } + builder.append(':'); + builder.append(portal.isHidden()); + builder.append(':'); + builder.append(portal.isAlwaysOn()); + builder.append(':'); + builder.append(portal.isPrivate()); + builder.append(':'); + builder.append(portal.world.getName()); + builder.append(':'); + builder.append(portal.isFree()); + builder.append(':'); + builder.append(portal.isBackwards()); + builder.append(':'); + builder.append(portal.isShown()); + builder.append(':'); + builder.append(portal.isNoNetwork()); + builder.append(':'); + builder.append(portal.isRandom()); + builder.append(':'); + builder.append(portal.isBungee()); + + bw.append(builder.toString()); + bw.newLine(); + } + + bw.close(); + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); + } + } + + public static void clearGates() { + lookupBlocks.clear(); + lookupNamesNet.clear(); + lookupEntrances.clear(); + lookupControls.clear(); + allPortals.clear(); + allPortalsNet.clear(); + } + + public static boolean loadAllGates(World world) { + String location = Stargate.getSaveLocation(); + + File db = new File(location, world.getName() + ".db"); + + if (db.exists()) { + int l = 0; + int portalCount = 0; + try { + Scanner scanner = new Scanner(db); + while (scanner.hasNextLine()) { + l++; + String line = scanner.nextLine().trim(); + if (line.startsWith("#") || line.isEmpty()) { + continue; + } + String[] split = line.split(":"); + if (split.length < 8) { + Stargate.log.info("[stargate] Invalid line - " + l); + continue; + } + String name = split[0]; + BlockLocation sign = new BlockLocation(world, split[1]); + BlockLocation button = (split[2].length() > 0) ? new BlockLocation(world, split[2]) : null; + int modX = Integer.parseInt(split[3]); + int modZ = Integer.parseInt(split[4]); + float rotX = Float.parseFloat(split[5]); + BlockLocation topLeft = new BlockLocation(world, split[6]); + Gate gate = Gate.getGateByName(split[7]); + if (gate == null) { + Stargate.log.info("[stargate] Gate layout on line " + l + " does not exist [" + split[7] + "]"); + continue; + } + + String dest = (split.length > 8) ? split[8] : ""; + String network = (split.length > 9) ? split[9] : Stargate.getDefaultNetwork(); + if (network.isEmpty()) network = Stargate.getDefaultNetwork(); + String ownerString = (split.length > 10) ? split[10] : ""; + boolean hidden = (split.length > 11) && split[11].equalsIgnoreCase("true"); + boolean alwaysOn = (split.length > 12) && split[12].equalsIgnoreCase("true"); + boolean priv = (split.length > 13) && split[13].equalsIgnoreCase("true"); + boolean free = (split.length > 15) && split[15].equalsIgnoreCase("true"); + boolean backwards = (split.length > 16) && split[16].equalsIgnoreCase("true"); + boolean show = (split.length > 17) && split[17].equalsIgnoreCase("true"); + boolean noNetwork = (split.length > 18) && split[18].equalsIgnoreCase("true"); + boolean random = (split.length > 19) && split[19].equalsIgnoreCase("true"); + boolean bungee = (split.length > 20) && split[20].equalsIgnoreCase("true"); + + // Attempt to get owner as UUID + UUID ownerUUID = null; + String ownerName; + if (ownerString.length() > 16) { + try { + ownerUUID = UUID.fromString(ownerString); + OfflinePlayer offlineOwner = Bukkit.getServer().getOfflinePlayer(ownerUUID); + ownerName = offlineOwner.getName(); + } catch (IllegalArgumentException ex) { + // neither name nor UUID, so keep it as-is + ownerName = ownerString; + Stargate.debug("loadAllGates", "Invalid stargate owner string: " + ownerString); + } + } else { + ownerName = ownerString; + } + + Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, dest, name, false, network, gate, ownerUUID, ownerName, hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); + portal.register(); + portal.close(true); + } + scanner.close(); + + // Open any always-on gates. Do this here as it should be more efficient than in the loop. + int OpenCount = 0; + for (Iterator iter = allPortals.iterator(); iter.hasNext(); ) { + Portal portal = iter.next(); + if (portal == null) continue; + + // Verify portal integrity/register portal + if (!portal.wasVerified()) { + if (!portal.isVerified() || !portal.checkIntegrity()) { + // DEBUG + for (RelativeBlockVector control : portal.getGate().getControls()) { + if (!portal.getBlockAt(control).getBlock().getType().equals(portal.getGate().getControlBlock())) { + Stargate.debug("loadAllGates", "Control Block Type == " + portal.getBlockAt(control).getBlock().getType().name()); + } + } + portal.unregister(false); + iter.remove(); + Stargate.log.info("[stargate] Destroying stargate at " + portal.toString()); + continue; + } + } + portalCount++; + + if (portal.isFixed() && (Stargate.enableBungee && portal.isBungee() + || portal.getDestination() != null && portal.isAlwaysOn())) { + portal.open(true); + OpenCount++; + } + } + Stargate.log.info("[stargate] {" + world.getName() + "} Loaded " + portalCount + " stargates with " + OpenCount + " set as always-on"); + return true; + } catch (Exception e) { + Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + db.getName() + ": " + l); + e.printStackTrace(); + } + } else { + Stargate.log.info("[stargate] {" + world.getName() + "} No stargates for world "); + } + return false; + } + + public static void closeAllGates() { + Stargate.log.info("Closing all stargates."); + for (Portal p : allPortals) { + if (p == null) continue; + p.close(true); + } + } + + public static String filterName(String input) { + if (input == null) { + return ""; + } + return input.replaceAll("[\\|:#]", "").trim(); + } + + @Override + public String toString() { + return String.format("Portal [id=%s, network=%s name=%s, type=%s]", id, network, name, gate.getFilename()); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((network == null) ? 0 : network.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Portal other = (Portal) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equalsIgnoreCase(other.name)) + return false; + if (network == null) { + if (other.network != null) + return false; + } else if (!network.equalsIgnoreCase(other.network)) + return false; + return true; + } +} diff --git a/src/net/TheDgtl/Stargate/RelativeBlockVector.java b/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java similarity index 60% rename from src/net/TheDgtl/Stargate/RelativeBlockVector.java rename to src/main/java/net/knarcraft/stargate/RelativeBlockVector.java index 60876a5..c3e40f3 100644 --- a/src/net/TheDgtl/Stargate/RelativeBlockVector.java +++ b/src/main/java/net/knarcraft/stargate/RelativeBlockVector.java @@ -1,45 +1,48 @@ -package net.TheDgtl.Stargate; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class RelativeBlockVector { - private int right = 0; - private int depth = 0; - private int distance = 0; - - public RelativeBlockVector(int right, int depth, int distance) { - this.right = right; - this.depth = depth; - this.distance = distance; - } - - public int getRight() { - return right; - } - - public int getDepth() { - return depth; - } - - public int getDistance() { - return distance; - } -} +package net.knarcraft.stargate; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011 Shaun (sturmeh) + * Copyright (C) 2011 Dinnerbone + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class RelativeBlockVector { + + private int right = 0; + private int depth = 0; + private int distance = 0; + + public RelativeBlockVector(int right, int depth, int distance) { + this.right = right; + this.depth = depth; + this.distance = distance; + } + + public int getRight() { + return right; + } + + public int getDepth() { + return depth; + } + + public int getDistance() { + return distance; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/StarGateThread.java b/src/main/java/net/knarcraft/stargate/StarGateThread.java new file mode 100644 index 0000000..516b326 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/StarGateThread.java @@ -0,0 +1,34 @@ +package net.knarcraft.stargate; + +import java.util.Iterator; + +/** + * This class contains the function used to close servers which should no longer be open/active + */ +public class StarGateThread implements Runnable { + + public void run() { + long time = System.currentTimeMillis() / 1000; + // Close open portals + for (Iterator iterator = Stargate.openList.iterator(); iterator.hasNext(); ) { + Portal p = iterator.next(); + // Skip always open gates + if (p.isAlwaysOn()) continue; + if (!p.isOpen()) continue; + if (time > p.getOpenTime() + Stargate.getOpenTime()) { + p.close(false); + iterator.remove(); + } + } + // Deactivate active portals + for (Iterator iterator = Stargate.activeList.iterator(); iterator.hasNext(); ) { + Portal p = iterator.next(); + if (!p.isActive()) continue; + if (time > p.getOpenTime() + Stargate.getActiveTime()) { + p.deactivate(); + iterator.remove(); + } + } + } + +} diff --git a/src/main/java/net/knarcraft/stargate/Stargate.java b/src/main/java/net/knarcraft/stargate/Stargate.java new file mode 100644 index 0000000..269e541 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/Stargate.java @@ -0,0 +1,1280 @@ +package net.knarcraft.stargate; + +import net.knarcraft.stargate.event.StargateAccessEvent; +import net.knarcraft.stargate.event.StargateDestroyEvent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.Tag; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.EndGateway; +import org.bukkit.block.Sign; +import org.bukkit.block.data.Orientable; +import org.bukkit.block.data.type.WallSign; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Event.Result; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.event.vehicle.VehicleMoveEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011 Shaun (sturmeh) + * Copyright (C) 2011 Dinnerbone + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +@SuppressWarnings("unused") +public class Stargate extends JavaPlugin { + + public static Logger log; + private FileConfiguration newConfig; + private PluginManager pm; + public static Server server; + public static Stargate stargate; + private static LanguageLoader languageLoader; + + private static String portalFolder; + private static String gateFolder; + private static String langFolder; + private static String defNetwork = "central"; + private static boolean destroyExplosion = false; + public static int maxGates = 0; + private static String langName = "en"; + private static final int activeTime = 10; + private static final int openTime = 10; + public static boolean destMemory = false; + public static boolean handleVehicles = true; + public static boolean sortLists = false; + public static boolean protectEntrance = false; + public static boolean enableBungee = true; + public static boolean verifyPortals = true; + public static ChatColor signColor; + + // Temp workaround for snowmen, don't check gate entrance + public static boolean ignoreEntrance = false; + + // Used for debug + public static boolean debug = false; + public static boolean permDebug = false; + + public static ConcurrentLinkedQueue openList = new ConcurrentLinkedQueue<>(); + public static ConcurrentLinkedQueue activeList = new ConcurrentLinkedQueue<>(); + + // Used for populating gate open/closed material. + public static Queue blockPopulatorQueue = new LinkedList<>(); + + // HashMap of player names for Bungee support + public static Map bungeeQueue = new HashMap<>(); + + // World names that contain stargates + public static HashSet managedWorlds = new HashSet<>(); + + @Override + public void onDisable() { + Portal.closeAllGates(); + Portal.clearGates(); + managedWorlds.clear(); + getServer().getScheduler().cancelTasks(this); + } + + @Override + public void onEnable() { + PluginDescriptionFile pdfFile = this.getDescription(); + pm = getServer().getPluginManager(); + newConfig = this.getConfig(); + log = Logger.getLogger("Minecraft"); + Stargate.server = getServer(); + Stargate.stargate = this; + + // Set portalFile and gateFolder to the plugin folder as defaults. + String dataFolderPath = getDataFolder().getPath().replaceAll("\\\\", "/"); + portalFolder = dataFolderPath + "/portals/"; + gateFolder = dataFolderPath + "/gates/"; + langFolder = dataFolderPath + "/lang/"; + + log.info(pdfFile.getName() + " v." + pdfFile.getVersion() + " is enabled."); + + // Register events before loading gates to stop weird things happening. + pm.registerEvents(new pListener(), this); + pm.registerEvents(new bListener(), this); + + pm.registerEvents(new vListener(), this); + pm.registerEvents(new eListener(), this); + pm.registerEvents(new wListener(), this); + pm.registerEvents(new sListener(), this); + + this.loadConfig(); + + // Enable the required channels for Bungee support + if (enableBungee) { + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCoordListener()); + } + + // It is important to load languages here, as they are used during reloadGates() + languageLoader = new LanguageLoader(langFolder, Stargate.langName); + + this.migrate(); + this.loadGates(); + this.loadAllPortals(); + + // Check to see if Economy is loaded yet. + if (EconomyHandler.setupEconomy(pm)) { + if (EconomyHandler.economy != null) + log.info("[stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); + } + + getServer().getScheduler().scheduleSyncRepeatingTask(this, new StarGateThread(), 0L, 100L); + getServer().getScheduler().scheduleSyncRepeatingTask(this, new BlockPopulatorThread(), 0L, 1L); + } + + public static int getOpenTime() { + return openTime; + } + + public static int getActiveTime() { + return activeTime; + } + + public void loadConfig() { + reloadConfig(); + newConfig = this.getConfig(); + // Copy default values if required + newConfig.options().copyDefaults(true); + + // Load values into variables + portalFolder = newConfig.getString("portal-folder"); + gateFolder = newConfig.getString("gate-folder"); + defNetwork = newConfig.getString("default-gate-network").trim(); + destroyExplosion = newConfig.getBoolean("destroyexplosion"); + maxGates = newConfig.getInt("maxgates"); + langName = newConfig.getString("lang"); + destMemory = newConfig.getBoolean("destMemory"); + ignoreEntrance = newConfig.getBoolean("ignoreEntrance"); + handleVehicles = newConfig.getBoolean("handleVehicles"); + sortLists = newConfig.getBoolean("sortLists"); + protectEntrance = newConfig.getBoolean("protectEntrance"); + enableBungee = newConfig.getBoolean("enableBungee"); + verifyPortals = newConfig.getBoolean("verifyPortals"); + // Sign color + String sc = newConfig.getString("signColor"); + try { + signColor = ChatColor.valueOf(sc.toUpperCase()); + } catch (Exception ignore) { + log.warning("[stargate] You have specified an invalid color in your config.yml. Defaulting to BLACK"); + signColor = ChatColor.BLACK; + } + // Debug + debug = newConfig.getBoolean("debug"); + permDebug = newConfig.getBoolean("permdebug"); + // Economy + EconomyHandler.economyEnabled = newConfig.getBoolean("useeconomy"); + EconomyHandler.createCost = newConfig.getInt("createcost"); + EconomyHandler.destroyCost = newConfig.getInt("destroycost"); + EconomyHandler.useCost = newConfig.getInt("usecost"); + EconomyHandler.toOwner = newConfig.getBoolean("toowner"); + EconomyHandler.chargeFreeDestination = newConfig.getBoolean("chargefreedestination"); + EconomyHandler.freeGatesGreen = newConfig.getBoolean("freegatesgreen"); + + this.saveConfig(); + } + + public void closeAllPortals() { + // Close all gates prior to reloading + for (Portal p : openList) { + p.close(true); + } + } + + public void loadGates() { + Gate.loadGates(gateFolder); + log.info("[stargate] Loaded " + Gate.getGateCount() + " gate layouts"); + } + + public void loadAllPortals() { + for (World world : getServer().getWorlds()) { + if (!managedWorlds.contains(world.getName())) { + Portal.loadAllGates(world); + managedWorlds.add(world.getName()); + } + } + } + + private void migrate() { + // Only migrate if new file doesn't exist. + File newPortalDir = new File(portalFolder); + if (!newPortalDir.exists()) { + newPortalDir.mkdirs(); + } + File newFile = new File(portalFolder, getServer().getWorlds().get(0).getName() + ".db"); + if (!newFile.exists()) { + newFile.getParentFile().mkdirs(); + } + } + + public static void debug(String rout, String msg) { + if (Stargate.debug) { + log.info("[stargate::" + rout + "] " + msg); + } else { + log.log(Level.FINEST, "[stargate::" + rout + "] " + msg); + } + } + + public static void sendMessage(CommandSender player, String message) { + sendMessage(player, message, true); + } + + public static void sendMessage(CommandSender player, String message, boolean error) { + if (message.isEmpty()) return; + message = message.replaceAll("(&([a-f0-9]))", "\u00A7$2"); + if (error) + player.sendMessage(ChatColor.RED + Stargate.getString("prefix") + ChatColor.WHITE + message); + else + player.sendMessage(ChatColor.GREEN + Stargate.getString("prefix") + ChatColor.WHITE + message); + } + + public static void setLine(Sign sign, int index, String text) { + sign.setLine(index, Stargate.signColor + text); + } + + public static String getSaveLocation() { + return portalFolder; + } + + public static String getGateFolder() { + return gateFolder; + } + + public static String getDefaultNetwork() { + return defNetwork; + } + + public static String getString(String name) { + return languageLoader.getString(name); + } + + public static void openPortal(Player player, Portal portal) { + Portal destination = portal.getDestination(); + + // Always-open gate -- Do nothing + if (portal.isAlwaysOn()) { + return; + } + + // Random gate -- Do nothing + if (portal.isRandom()) + return; + + // Invalid destination + if ((destination == null) || (destination == portal)) { + Stargate.sendMessage(player, Stargate.getString("invalidMsg")); + return; + } + + // Gate is already open + if (portal.isOpen()) { + // Close if this player opened the gate + if (portal.getActivePlayer() == player) { + portal.close(false); + } + return; + } + + // Gate that someone else is using -- Deny access + if ((!portal.isFixed()) && portal.isActive() && (portal.getActivePlayer() != player)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + // Check if the player can use the private gate + if (portal.isPrivate() && !Stargate.canPrivate(player, portal)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + // Destination blocked + if ((destination.isOpen()) && (!destination.isAlwaysOn())) { + Stargate.sendMessage(player, Stargate.getString("blockMsg")); + return; + } + + // Open gate + portal.open(player, false); + } + + /* + * Check whether the player has the given permissions. + */ + public static boolean hasPerm(Player player, String perm) { + if (permDebug) + Stargate.debug("hasPerm::SuperPerm(" + player.getName() + ")", perm + " => " + player.hasPermission(perm)); + return player.hasPermission(perm); + } + + /* + * Check a deep permission, this will check to see if the permissions is defined for this use + * If using Permissions it will return the same as hasPerm + * If using SuperPerms will return true if the node isn't defined + * Or the value of the node if it is + */ + public static boolean hasPermDeep(Player player, String perm) { + if (!player.isPermissionSet(perm)) { + if (permDebug) + Stargate.debug("hasPermDeep::SuperPerm", perm + " => true"); + return true; + } + if (permDebug) + Stargate.debug("hasPermDeep::SuperPerms", perm + " => " + player.hasPermission(perm)); + return player.hasPermission(perm); + } + + /* + * Check whether player can teleport to dest world + */ + public static boolean canAccessWorld(Player player, String world) { + // Can use all stargate player features or access all worlds + if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.world")) { + // Do a deep check to see if the player lacks this specific world node + return hasPermDeep(player, "stargate.world." + world); + } + // Can access dest world + return hasPerm(player, "stargate.world." + world); + } + + /* + * Check whether player can use network + */ + public static boolean canAccessNetwork(Player player, String network) { + // Can user all stargate player features, or access all networks + if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.network")) { + // Do a deep check to see if the player lacks this specific network node + return hasPermDeep(player, "stargate.network." + network); + } + // Can access this network + if (hasPerm(player, "stargate.network." + network)) return true; + // Is able to create personal gates (Assumption is made they can also access them) + String playerName = player.getName(); + if (playerName.length() > 11) playerName = playerName.substring(0, 11); + return network.equals(playerName) && hasPerm(player, "stargate.create.personal"); + } + + /* + * Check whether the player can access this server + */ + public static boolean canAccessServer(Player player, String server) { + // Can user all stargate player features, or access all servers + if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.servers")) { + // Do a deep check to see if the player lacks this specific server node + return hasPermDeep(player, "stargate.server." + server); + } + // Can access this server + return hasPerm(player, "stargate.server." + server); + } + + /* + * Call the StargateAccessPortal event, used for other plugins to bypass Permissions checks + */ + public static boolean canAccessPortal(Player player, Portal portal, boolean deny) { + StargateAccessEvent event = new StargateAccessEvent(player, portal, deny); + Stargate.server.getPluginManager().callEvent(event); + return !event.getDeny(); + } + + /* + * Return true if the portal is free for the player + */ + public static boolean isFree(Player player, Portal src, Portal dest) { + // This gate is free + if (src.isFree()) return true; + // Player gets free use + if (hasPerm(player, "stargate.free") || Stargate.hasPerm(player, "stargate.free.use")) return true; + // Don't charge for free destination gates + return dest != null && !EconomyHandler.chargeFreeDestination && dest.isFree(); + } + + /* + * Check whether the player can see this gate (Hidden property check) + */ + public static boolean canSee(Player player, Portal portal) { + // The gate is not hidden + if (!portal.isHidden()) return true; + // The player is an admin with the ability to see hidden gates + if (hasPerm(player, "stargate.admin") || hasPerm(player, "stargate.admin.hidden")) return true; + // The player is the owner of the gate + return portal.isOwner(player); + } + + /* + * Check if the player can use this private gate + */ + public static boolean canPrivate(Player player, Portal portal) { + // Check if the player is the owner of the gate + if (portal.isOwner(player)) return true; + // The player is an admin with the ability to use private gates + return hasPerm(player, "stargate.admin") || hasPerm(player, "stargate.admin.private"); + } + + /* + * Check if the player has access to {option} + */ + public static boolean canOption(Player player, String option) { + // Check if the player can use all options + if (hasPerm(player, "stargate.option")) return true; + // Check if they can use this specific option + return hasPerm(player, "stargate.option." + option); + } + + /* + * Check if the player can create gates on {network} + */ + public static boolean canCreate(Player player, String network) { + // Check for general create + if (hasPerm(player, "stargate.create")) return true; + // Check for all network create permission + if (hasPerm(player, "stargate.create.network")) { + // Do a deep check to see if the player lacks this specific network node + return hasPermDeep(player, "stargate.create.network." + network); + } + // Check for this specific network + return hasPerm(player, "stargate.create.network." + network); + + } + + /* + * Check if the player can create a personal gate + */ + public static boolean canCreatePersonal(Player player) { + // Check for general create + if (hasPerm(player, "stargate.create")) return true; + // Check for personal + return hasPerm(player, "stargate.create.personal"); + } + + /* + * Check if the player can create this gate layout + */ + public static boolean canCreateGate(Player player, String gate) { + // Check for general create + if (hasPerm(player, "stargate.create")) return true; + // Check for all gate create permissions + if (hasPerm(player, "stargate.create.gate")) { + // Do a deep check to see if the player lacks this specific gate node + return hasPermDeep(player, "stargate.create.gate." + gate); + } + // Check for this specific gate + return hasPerm(player, "stargate.create.gate." + gate); + } + + /* + * Check if the player can destroy this gate + */ + public static boolean canDestroy(Player player, Portal portal) { + String network = portal.getNetwork(); + // Check for general destroy + if (hasPerm(player, "stargate.destroy")) return true; + // Check for all network destroy permission + if (hasPerm(player, "stargate.destroy.network")) { + // Do a deep check to see if the player lacks permission for this network node + return hasPermDeep(player, "stargate.destroy.network." + network); + } + // Check for this specific network + if (hasPerm(player, "stargate.destroy.network." + network)) return true; + // Check for personal gate + return portal.isOwner(player) && hasPerm(player, "stargate.destroy.personal"); + } + + /* + * Charge player for {action} if required, true on success, false if can't afford + */ + public static boolean chargePlayer(Player player, String target, int cost) { + // If cost is 0 + if (cost == 0) return true; + // Economy is disabled + if (!EconomyHandler.useEconomy()) return true; + // Charge player + return EconomyHandler.chargePlayer(player, target, cost); + } + + /* + * Charge player for {action} if required, true on success, false if can't afford + */ + public static boolean chargePlayer(Player player, UUID target, int cost) { + // If cost is 0 + if (cost == 0) return true; + // Economy is disabled + if (!EconomyHandler.useEconomy()) return true; + // Charge player + return EconomyHandler.chargePlayer(player, target, cost); + } + + /* + * Charge player for {action} if required, true on success, false if can't afford + */ + public static boolean chargePlayer(Player player, int cost) { + // If cost is 0 + if (cost == 0) return true; + // Economy is disabled + if (!EconomyHandler.useEconomy()) return true; + // Charge player + return EconomyHandler.chargePlayer(player, cost); + } + + /* + * Determine the cost of a gate + */ + public static int getUseCost(Player player, Portal src, Portal dest) { + // Not using Economy + if (!EconomyHandler.useEconomy()) return 0; + // Portal is free + if (src.isFree()) return 0; + // Not charging for free destinations + if (dest != null && !EconomyHandler.chargeFreeDestination && dest.isFree()) return 0; + // Cost is 0 if the player owns this gate and funds go to the owner + if (src.getGate().getToOwner() && src.isOwner(player)) return 0; + // Player gets free gate use + if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.use")) return 0; + + return src.getGate().getUseCost(); + } + + /* + * Determine the cost to create the gate + */ + public static int getCreateCost(Player player, Gate gate) { + // Not using Economy + if (!EconomyHandler.useEconomy()) return 0; + // Player gets free gate destruction + if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.create")) return 0; + + return gate.getCreateCost(); + } + + /* + * Determine the cost to destroy the gate + */ + public static int getDestroyCost(Player player, Gate gate) { + // Not using Economy + if (!EconomyHandler.useEconomy()) return 0; + // Player gets free gate destruction + if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.destroy")) return 0; + + return gate.getDestroyCost(); + } + + /* + * Check if a plugin is loaded/enabled already. Returns the plugin if so, null otherwise + */ + private Plugin checkPlugin(String p) { + Plugin plugin = pm.getPlugin(p); + return checkPlugin(plugin); + } + + private Plugin checkPlugin(Plugin plugin) { + if (plugin != null && plugin.isEnabled()) { + log.info("[stargate] Found " + plugin.getDescription().getName() + " (v" + plugin.getDescription().getVersion() + ")"); + return plugin; + } + return null; + } + + /* + * Parse a given text string and replace the variables + */ + public static String replaceVars(String format, String[] search, String[] replace) { + if (search.length != replace.length) return ""; + for (int i = 0; i < search.length; i++) { + format = format.replace(search[i], replace[i]); + } + return format; + } + + private class vListener implements Listener { + @EventHandler + public void onVehicleMove(VehicleMoveEvent event) { + if (!handleVehicles) return; + List passengers = event.getVehicle().getPassengers(); + Vehicle vehicle = event.getVehicle(); + + Portal portal = Portal.getByEntrance(event.getTo()); + if (portal == null || !portal.isOpen()) return; + + // We don't support vehicles in Bungee portals + if (portal.isBungee()) return; + + if (!passengers.isEmpty() && passengers.get(0) instanceof Player) { + /* + Player player = (Player) passengers.get(0); + if (!portal.isOpenFor(player)) { + stargate.sendMessage(player, stargate.getString("denyMsg")); + return; + } + + Portal dest = portal.getDestination(player); + if (dest == null) return; + boolean deny = false; + // Check if player has access to this network + if (!canAccessNetwork(player, portal.getNetwork())) { + deny = true; + } + + // Check if player has access to destination world + if (!canAccessWorld(player, dest.getWorld().getName())) { + deny = true; + } + + if (!canAccessPortal(player, portal, deny)) { + stargate.sendMessage(player, stargate.getString("denyMsg")); + portal.close(false); + return; + } + + int cost = stargate.getUseCost(player, portal, dest); + if (cost > 0) { + boolean success; + if(portal.getGate().getToOwner()) { + if(portal.getOwnerUUID() == null) { + success = stargate.chargePlayer(player, portal.getOwnerUUID(), cost); + } else { + success = stargate.chargePlayer(player, portal.getOwnerName(), cost); + } + } else { + success = stargate.chargePlayer(player, cost); + } + if(!success) { + // Insufficient Funds + stargate.sendMessage(player, stargate.getString("inFunds")); + portal.close(false); + return; + } + String deductMsg = stargate.getString("ecoDeduct"); + deductMsg = stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); + sendMessage(player, deductMsg, false); + if (portal.getGate().getToOwner()) { + Player p; + if(portal.getOwnerUUID() != null) { + p = server.getPlayer(portal.getOwnerUUID()); + } else { + p = server.getPlayer(portal.getOwnerName()); + } + if (p != null) { + String obtainedMsg = stargate.getString("ecoObtain"); + obtainedMsg = stargate.replaceVars(obtainedMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); + stargate.sendMessage(p, obtainedMsg, false); + } + } + } + + stargate.sendMessage(player, stargate.getString("teleportMsg"), false); + dest.teleport(vehicle); + portal.close(false); + */ + } else { + Portal dest = portal.getDestination(); + if (dest == null) return; + dest.teleport(vehicle); + } + } + } + + private class pListener implements Listener { + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + if (!enableBungee) return; + + Player player = event.getPlayer(); + String destination = bungeeQueue.remove(player.getName().toLowerCase()); + if (destination == null) return; + + Portal portal = Portal.getBungeeGate(destination); + if (portal == null) { + Stargate.debug("PlayerJoin", "Error fetching destination portal: " + destination); + return; + } + portal.teleport(player, portal, null); + } + + @EventHandler + public void onPlayerTeleport(PlayerTeleportEvent event) { + // cancel portal and endgateway teleportation if it's from a stargate entrance + PlayerTeleportEvent.TeleportCause cause = event.getCause(); + if (!event.isCancelled() + && (cause == PlayerTeleportEvent.TeleportCause.NETHER_PORTAL + || cause == PlayerTeleportEvent.TeleportCause.END_GATEWAY && World.Environment.THE_END == event.getFrom().getWorld().getEnvironment()) + && Portal.getByAdjacentEntrance(event.getFrom()) != null) { + event.setCancelled(true); + } + } + + @EventHandler + public void onPlayerMove(PlayerMoveEvent event) { + if (event.isCancelled()) return; + + // Check to see if the player actually moved + if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockY() == event.getTo().getBlockY() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) { + return; + } + + Player player = event.getPlayer(); + Portal portal = Portal.getByEntrance(event.getTo()); + // No portal or not open + if (portal == null || !portal.isOpen()) return; + + // Not open for this player + if (!portal.isOpenFor(player)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + portal.teleport(player, portal, event); + return; + } + + Portal destination = portal.getDestination(player); + if (!portal.isBungee() && destination == null) return; + + boolean deny = false; + // Check if player has access to this server for Bungee gates + if (portal.isBungee()) { + if (!canAccessServer(player, portal.getNetwork())) { + deny = true; + } + } else { + // Check if player has access to this network + if (!canAccessNetwork(player, portal.getNetwork())) { + deny = true; + } + + // Check if player has access to destination world + if (!canAccessWorld(player, destination.getWorld().getName())) { + deny = true; + } + } + + if (!canAccessPortal(player, portal, deny)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + portal.teleport(player, portal, event); + portal.close(false); + return; + } + + int cost = Stargate.getUseCost(player, portal, destination); + if (cost > 0) { + boolean success; + if (portal.getGate().getToOwner()) { + if (portal.getOwnerUUID() == null) { + success = Stargate.chargePlayer(player, portal.getOwnerUUID(), cost); + } else { + success = Stargate.chargePlayer(player, portal.getOwnerName(), cost); + } + } else { + success = Stargate.chargePlayer(player, cost); + } + if (!success) { + // Insufficient Funds + Stargate.sendMessage(player, Stargate.getString("inFunds")); + portal.close(false); + return; + } + String deductMsg = Stargate.getString("ecoDeduct"); + deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); + sendMessage(player, deductMsg, false); + if (portal.getGate().getToOwner() && portal.getOwnerUUID() != null) { + Player p; + if (portal.getOwnerUUID() != null) { + p = server.getPlayer(portal.getOwnerUUID()); + } else { + p = server.getPlayer(portal.getOwnerName()); + } + if (p != null) { + String obtainedMsg = Stargate.getString("ecoObtain"); + obtainedMsg = Stargate.replaceVars(obtainedMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); + Stargate.sendMessage(p, obtainedMsg, false); + } + } + } + + Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false); + + // BungeeCord Support + if (portal.isBungee()) { + if (!enableBungee) { + player.sendMessage(Stargate.getString("bungeeDisabled")); + portal.close(false); + return; + } + + // Teleport the player back to this gate, for sanity's sake + portal.teleport(player, portal, event); + + // Send the SGBungee packet first, it will be queued by BC if required + try { + // Build the message, format is #@# + String msg = event.getPlayer().getName() + "#@#" + portal.getDestinationName(); + // Build the message data, sent over the SGBungee bungeecord channel + ByteArrayOutputStream bao = new ByteArrayOutputStream(); + DataOutputStream msgData = new DataOutputStream(bao); + msgData.writeUTF("Forward"); + msgData.writeUTF(portal.getNetwork()); // Server + msgData.writeUTF("SGBungee"); // Channel + msgData.writeShort(msg.length()); // Data Length + msgData.writeBytes(msg); // Data + player.sendPluginMessage(stargate, "BungeeCord", bao.toByteArray()); + } catch (IOException ex) { + Stargate.log.severe("[stargate] Error sending BungeeCord teleport packet"); + ex.printStackTrace(); + return; + } + + // Connect player to new server + try { + ByteArrayOutputStream bao = new ByteArrayOutputStream(); + DataOutputStream msgData = new DataOutputStream(bao); + msgData.writeUTF("Connect"); + msgData.writeUTF(portal.getNetwork()); + + player.sendPluginMessage(stargate, "BungeeCord", bao.toByteArray()); + bao.reset(); + } catch (IOException ex) { + Stargate.log.severe("[stargate] Error sending BungeeCord connect packet"); + ex.printStackTrace(); + return; + } + + // Close portal if required (Should never be) + portal.close(false); + return; + } + + destination.teleport(player, portal, event); + portal.close(false); + } + + @EventHandler + public void onPlayerInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + + if (block == null) return; + + // Right click + if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { + if (block.getBlockData() instanceof WallSign) { + Portal portal = Portal.getByBlock(block); + if (portal == null) return; + // Cancel item use + event.setUseItemInHand(Result.DENY); + event.setUseInteractedBlock(Result.DENY); + + boolean deny = false; + if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { + deny = true; + } + + if (!Stargate.canAccessPortal(player, portal, deny)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + if ((!portal.isOpen()) && (!portal.isFixed())) { + portal.cycleDestination(player); + } + return; + } + + // Implement right-click to toggle a stargate, gets around spawn protection problem. + if (Tag.BUTTONS.isTagged(block.getType())) { + Portal portal = Portal.getByBlock(block); + if (portal == null) return; + + // Cancel item use + event.setUseItemInHand(Result.DENY); + event.setUseInteractedBlock(Result.DENY); + + boolean deny = false; + if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { + deny = true; + } + + if (!Stargate.canAccessPortal(player, portal, deny)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + openPortal(player, portal); + if (portal.isOpenFor(player)) { + event.setUseInteractedBlock(Result.ALLOW); + } + } + return; + } + + // Left click + if (event.getAction() == Action.LEFT_CLICK_BLOCK) { + // Check if we're scrolling a sign + if (block.getBlockData() instanceof WallSign) { + Portal portal = Portal.getByBlock(block); + if (portal == null) return; + + event.setUseInteractedBlock(Result.DENY); + // Only cancel event in creative mode + if (player.getGameMode().equals(GameMode.CREATIVE)) { + event.setCancelled(true); + } + + boolean deny = false; + if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { + deny = true; + } + + if (!Stargate.canAccessPortal(player, portal, deny)) { + Stargate.sendMessage(player, Stargate.getString("denyMsg")); + return; + } + + if ((!portal.isOpen()) && (!portal.isFixed())) { + portal.cycleDestination(player, -1); + } + } + } + } + } + + private class bListener implements Listener { + @EventHandler + public void onSignChange(SignChangeEvent event) { + if (event.isCancelled()) return; + Player player = event.getPlayer(); + Block block = event.getBlock(); + if (!(block.getBlockData() instanceof WallSign)) return; + + final Portal portal = Portal.createPortal(event, player); + // Not creating a gate, just placing a sign + if (portal == null) return; + + Stargate.sendMessage(player, Stargate.getString("createMsg"), false); + Stargate.debug("onSignChange", "Initialized stargate: " + portal.getName()); + Stargate.server.getScheduler().scheduleSyncDelayedTask(stargate, new Runnable() { + public void run() { + portal.drawSign(); + } + }, 1); + } + + // Switch to HIGHEST priority so as to come after block protection plugins (Hopefully) + @EventHandler(priority = EventPriority.HIGHEST) + public void onBlockBreak(BlockBreakEvent event) { + if (event.isCancelled()) return; + Block block = event.getBlock(); + Player player = event.getPlayer(); + + Portal portal = Portal.getByBlock(block); + if (portal == null && protectEntrance) + portal = Portal.getByEntrance(block); + if (portal == null) return; + + boolean deny = false; + String denyMsg = ""; + + if (!Stargate.canDestroy(player, portal)) { + denyMsg = "Permission Denied"; // TODO: Change to stargate.getString() + deny = true; + Stargate.log.info("[stargate] " + player.getName() + " tried to destroy gate"); + } + + int cost = Stargate.getDestroyCost(player, portal.getGate()); + + StargateDestroyEvent dEvent = new StargateDestroyEvent(portal, player, deny, denyMsg, cost); + Stargate.server.getPluginManager().callEvent(dEvent); + if (dEvent.isCancelled()) { + event.setCancelled(true); + return; + } + if (dEvent.getDeny()) { + Stargate.sendMessage(player, dEvent.getDenyReason()); + event.setCancelled(true); + return; + } + + cost = dEvent.getCost(); + + if (cost != 0) { + if (!Stargate.chargePlayer(player, cost)) { + Stargate.debug("onBlockBreak", "Insufficient Funds"); + Stargate.sendMessage(player, Stargate.getString("inFunds")); + event.setCancelled(true); + return; + } + + if (cost > 0) { + String deductMsg = Stargate.getString("ecoDeduct"); + deductMsg = Stargate.replaceVars(deductMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(cost), portal.getName()}); + sendMessage(player, deductMsg, false); + } else if (cost < 0) { + String refundMsg = Stargate.getString("ecoRefund"); + refundMsg = Stargate.replaceVars(refundMsg, new String[]{"%cost%", "%portal%"}, new String[]{EconomyHandler.format(-cost), portal.getName()}); + sendMessage(player, refundMsg, false); + } + } + + portal.unregister(true); + Stargate.sendMessage(player, Stargate.getString("destroyMsg"), false); + } + + @EventHandler + public void onBlockPhysics(BlockPhysicsEvent event) { + Block block = event.getBlock(); + Portal portal = null; + + // Handle keeping portal material and buttons around + if (block.getType() == Material.NETHER_PORTAL) { + portal = Portal.getByEntrance(block); + } else if (Tag.BUTTONS.isTagged(block.getType())) { + portal = Portal.getByControl(block); + } + if (portal != null) event.setCancelled(true); + } + + @EventHandler + public void onBlockFromTo(BlockFromToEvent event) { + Portal portal = Portal.getByEntrance(event.getBlock()); + + if (portal != null) { + event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); + } + } + + @EventHandler + public void onPistonExtend(BlockPistonExtendEvent event) { + for (Block block : event.getBlocks()) { + Portal portal = Portal.getByBlock(block); + if (portal != null) { + event.setCancelled(true); + return; + } + } + } + + @EventHandler + public void onPistonRetract(BlockPistonRetractEvent event) { + if (!event.isSticky()) return; + for (Block block : event.getBlocks()) { + Portal portal = Portal.getByBlock(block); + if (portal != null) { + event.setCancelled(true); + return; + } + } + } + } + + private class wListener implements Listener { + @EventHandler + public void onWorldLoad(WorldLoadEvent event) { + if (!managedWorlds.contains(event.getWorld().getName()) + && Portal.loadAllGates(event.getWorld())) { + managedWorlds.add(event.getWorld().getName()); + } + } + + // We need to reload all gates on world unload, boo + @EventHandler + public void onWorldUnload(WorldUnloadEvent event) { + Stargate.debug("onWorldUnload", "Reloading all Stargates"); + World w = event.getWorld(); + if (managedWorlds.contains(w.getName())) { + managedWorlds.remove(w.getName()); + Portal.clearGates(); + for (World world : server.getWorlds()) { + if (managedWorlds.contains(world.getName())) { + Portal.loadAllGates(world); + } + } + } + } + } + + private class eListener implements Listener { + @EventHandler + public void onEntityExplode(EntityExplodeEvent event) { + if (event.isCancelled()) return; + for (Block b : event.blockList()) { + Portal portal = Portal.getByBlock(b); + if (portal == null) continue; + if (destroyExplosion) { + portal.unregister(true); + } else { + event.setCancelled(true); + break; + } + } + } + } + + private class sListener implements Listener { + @EventHandler + public void onPluginEnable(PluginEnableEvent event) { + if (EconomyHandler.setupEconomy(getServer().getPluginManager())) { + log.info("[stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); + } + } + + @EventHandler + public void onPluginDisable(PluginDisableEvent event) { + if (event.getPlugin().equals(EconomyHandler.vault)) { + log.info("[stargate] Vault plugin lost."); + } + } + } + + private class BlockPopulatorThread implements Runnable { + public void run() { + long sTime = System.nanoTime(); + while (System.nanoTime() - sTime < 25000000) { + BloxPopulator b = Stargate.blockPopulatorQueue.poll(); + if (b == null) return; + Block blk = b.getBlockLocation().getBlock(); + blk.setType(b.getMat(), false); + if (b.getMat() == Material.END_GATEWAY && blk.getWorld().getEnvironment() == World.Environment.THE_END) { + // force a location to prevent exit gateway generation + EndGateway gateway = (EndGateway) blk.getState(); + gateway.setExitLocation(blk.getWorld().getSpawnLocation()); + gateway.setExactTeleport(true); + gateway.update(false, false); + } else if (b.getAxis() != null) { + Orientable orientable = (Orientable) blk.getBlockData(); + orientable.setAxis(b.getAxis()); + blk.setBlockData(orientable); + } + } + } + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + String cmd = command.getName(); + if (cmd.equalsIgnoreCase("sg")) { + if (args.length != 1) return false; + if (args[0].equalsIgnoreCase("about")) { + sender.sendMessage("stargate Plugin created by Drakia"); + if (!languageLoader.getString("author").isEmpty()) + sender.sendMessage("Language created by " + languageLoader.getString("author")); + return true; + } + if (sender instanceof Player) { + Player p = (Player) sender; + if (!hasPerm(p, "stargate.admin") && !hasPerm(p, "stargate.admin.reload")) { + sendMessage(sender, "Permission Denied"); + return true; + } + } + if (args[0].equalsIgnoreCase("reload")) { + // Deactivate portals + for (Portal p : activeList) { + p.deactivate(); + } + // Close portals + closeAllPortals(); + // Clear all lists + activeList.clear(); + openList.clear(); + managedWorlds.clear(); + Portal.clearGates(); + Gate.clearGates(); + + // Store the old Bungee enabled value + boolean oldEnableBungee = enableBungee; + // Reload data + loadConfig(); + loadGates(); + loadAllPortals(); + languageLoader.setChosenLanguage(langName); + languageLoader.reload(); + + // Load Economy support if enabled/clear if disabled + if (EconomyHandler.economyEnabled && EconomyHandler.economy == null) { + if (EconomyHandler.setupEconomy(pm)) { + if (EconomyHandler.economy != null) + log.info("[stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); + } + } + if (!EconomyHandler.economyEnabled) { + EconomyHandler.vault = null; + EconomyHandler.economy = null; + } + + // Enable the required channels for Bungee support + if (oldEnableBungee != enableBungee) { + if (enableBungee) { + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCoordListener()); + } else { + Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "BungeeCord"); + } + } + + sendMessage(sender, "stargate reloaded"); + return true; + } + return false; + } + return false; + } + +} diff --git a/src/net/TheDgtl/Stargate/event/StargateAccessEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java similarity index 76% rename from src/net/TheDgtl/Stargate/event/StargateAccessEvent.java rename to src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java index 6dc1585..07d58a3 100644 --- a/src/net/TheDgtl/Stargate/event/StargateAccessEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateAccessEvent.java @@ -1,59 +1,71 @@ -package net.TheDgtl.Stargate.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -import net.TheDgtl.Stargate.Portal; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateAccessEvent extends StargateEvent { - private final Player player; - private boolean deny; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public StargateAccessEvent(Player player, Portal portal, boolean deny) { - super("StargateAccessEvent", portal); - - this.player = player; - this.deny = deny; - } - - public boolean getDeny() { - return this.deny; - } - - public void setDeny(boolean deny) { - this.deny = deny; - } - - public Player getPlayer() { - return this.player; - } - -} +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/* + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + + +@SuppressWarnings("unused") +public class StargateAccessEvent extends StargateEvent { + + private final Player player; + private boolean deny; + + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateAccessEvent(Player player, Portal portal, boolean deny) { + super("StargateAccessEvent", portal); + + this.player = player; + this.deny = deny; + } + + /** + * Gets whether the player should be denied access + * @return

Whether the player should be denied access

+ */ + public boolean getDeny() { + return this.deny; + } + + /** + * Sets whether to deny the player + * @param deny

Whether to deny the player

+ */ + public void setDeny(boolean deny) { + this.deny = deny; + } + + public Player getPlayer() { + return this.player; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java new file mode 100644 index 0000000..c66a65f --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/event/StargateActivateEvent.java @@ -0,0 +1,72 @@ +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateActivateEvent extends StargateEvent { + + private final Player player; + private ArrayList destinations; + private String destination; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateActivateEvent(Portal portal, Player player, ArrayList destinations, String destination) { + super("StargatActivateEvent", portal); + + this.player = player; + this.destinations = destinations; + this.destination = destination; + } + + public Player getPlayer() { + return player; + } + + public ArrayList getDestinations() { + return destinations; + } + + public void setDestinations(ArrayList destinations) { + this.destinations = destinations; + } + + public String getDestination() { + return destination; + } + + public void setDestination(String destination) { + this.destination = destination; + } + +} diff --git a/src/net/TheDgtl/Stargate/event/StargateCloseEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java similarity index 54% rename from src/net/TheDgtl/Stargate/event/StargateCloseEvent.java rename to src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java index add60c0..89d586e 100644 --- a/src/net/TheDgtl/Stargate/event/StargateCloseEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateCloseEvent.java @@ -1,50 +1,53 @@ -package net.TheDgtl.Stargate.event; - -import org.bukkit.event.HandlerList; - -import net.TheDgtl.Stargate.Portal; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateCloseEvent extends StargateEvent { - private boolean force; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - public StargateCloseEvent(Portal portal, boolean force) { - super("StargateCloseEvent", portal); - - this.force = force; - } - - public boolean getForce() { - return force; - } - - public void setForce(boolean force) { - this.force = force; - } -} +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateCloseEvent extends StargateEvent { + + private boolean force; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateCloseEvent(Portal portal, boolean force) { + super("StargateCloseEvent", portal); + + this.force = force; + } + + public boolean getForce() { + return force; + } + + public void setForce(boolean force) { + this.force = force; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java new file mode 100644 index 0000000..eed8d74 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/event/StargateCreateEvent.java @@ -0,0 +1,85 @@ +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateCreateEvent extends StargateEvent { + + private final Player player; + private boolean deny; + private String denyReason; + private final String[] lines; + private int cost; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateCreateEvent(Player player, Portal portal, String[] lines, boolean deny, String denyReason, int cost) { + super("StargateCreateEvent", portal); + this.player = player; + this.lines = lines; + this.deny = deny; + this.denyReason = denyReason; + this.cost = cost; + } + + public Player getPlayer() { + return player; + } + + public String getLine(int index) throws IndexOutOfBoundsException { + return lines[index]; + } + + public boolean getDeny() { + return deny; + } + + public void setDeny(boolean deny) { + this.deny = deny; + } + + public String getDenyReason() { + return denyReason; + } + + public void setDenyReason(String denyReason) { + this.denyReason = denyReason; + } + + public int getCost() { + return cost; + } + + public void setCost(int cost) { + this.cost = cost; + } + +} diff --git a/src/net/TheDgtl/Stargate/event/StargateDeactivateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java similarity index 62% rename from src/net/TheDgtl/Stargate/event/StargateDeactivateEvent.java rename to src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java index b193139..41b061e 100644 --- a/src/net/TheDgtl/Stargate/event/StargateDeactivateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateDeactivateEvent.java @@ -1,39 +1,41 @@ -package net.TheDgtl.Stargate.event; - -import org.bukkit.event.HandlerList; - -import net.TheDgtl.Stargate.Portal; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateDeactivateEvent extends StargateEvent { - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - public StargateDeactivateEvent(Portal portal) { - super("StargatDeactivateEvent", portal); - - } -} +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateDeactivateEvent extends StargateEvent { + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateDeactivateEvent(Portal portal) { + super("StargatDeactivateEvent", portal); + + } +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java new file mode 100644 index 0000000..227e0c5 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/event/StargateDestroyEvent.java @@ -0,0 +1,79 @@ +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateDestroyEvent extends StargateEvent { + + private final Player player; + private boolean deny; + private String denyReason; + private int cost; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateDestroyEvent(Portal portal, Player player, boolean deny, String denyMsg, int cost) { + super("StargateDestroyEvent", portal); + this.player = player; + this.deny = deny; + this.denyReason = denyMsg; + this.cost = cost; + } + + public Player getPlayer() { + return player; + } + + public boolean getDeny() { + return deny; + } + + public void setDeny(boolean deny) { + this.deny = deny; + } + + public String getDenyReason() { + return denyReason; + } + + public void setDenyReason(String denyReason) { + this.denyReason = denyReason; + } + + public int getCost() { + return cost; + } + + public void setCost(int cost) { + this.cost = cost; + } + +} diff --git a/src/net/TheDgtl/Stargate/event/StargateEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateEvent.java similarity index 55% rename from src/net/TheDgtl/Stargate/event/StargateEvent.java rename to src/main/java/net/knarcraft/stargate/event/StargateEvent.java index 7033f33..d3471da 100644 --- a/src/net/TheDgtl/Stargate/event/StargateEvent.java +++ b/src/main/java/net/knarcraft/stargate/event/StargateEvent.java @@ -1,48 +1,54 @@ -package net.TheDgtl.Stargate.event; - -import net.TheDgtl.Stargate.Portal; - -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public abstract class StargateEvent extends Event implements Cancellable { - protected Portal portal; - protected boolean cancelled; - - public StargateEvent(String event, Portal portal) { - this.portal = portal; - this.cancelled = false; - } - - public Portal getPortal() { - return portal; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; + +/* + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * An abstract event describing any stargate event + */ +@SuppressWarnings("unused") +public abstract class StargateEvent extends Event implements Cancellable { + + protected Portal portal; + protected boolean cancelled; + + public StargateEvent(String event, Portal portal) { + this.portal = portal; + this.cancelled = false; + } + + public Portal getPortal() { + return portal; + } + + @Override + public boolean isCancelled() { + return this.cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java b/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java new file mode 100644 index 0000000..180b700 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/event/StargateOpenEvent.java @@ -0,0 +1,65 @@ +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargateOpenEvent extends StargateEvent { + + private final Player player; + private boolean force; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargateOpenEvent(Player player, Portal portal, boolean force) { + super("StargateOpenEvent", portal); + + this.player = player; + this.force = force; + } + + /** + * Return the player than opened the gate. + * + * @return player than opened the gate + */ + public Player getPlayer() { + return player; + } + + public boolean getForce() { + return force; + } + + public void setForce(boolean force) { + this.force = force; + } + +} diff --git a/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java b/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java new file mode 100644 index 0000000..2a3a537 --- /dev/null +++ b/src/main/java/net/knarcraft/stargate/event/StargatePortalEvent.java @@ -0,0 +1,85 @@ +package net.knarcraft.stargate.event; + +import net.knarcraft.stargate.Portal; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * stargate - A portal plugin for Bukkit + * Copyright (C) 2011, 2012 Steven "Drakia" Scott + * Copyright (C) 2021 Kristian Knarvik + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +public class StargatePortalEvent extends StargateEvent { + + private final Player player; + private final Portal destination; + private Location exit; + + private static final HandlerList handlers = new HandlerList(); + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public StargatePortalEvent(Player player, Portal portal, Portal dest, Location exit) { + super("StargatePortalEvent", portal); + + this.player = player; + this.destination = dest; + this.exit = exit; + } + + /** + * Return the player that went through the gate. + * + * @return player that went through the gate + */ + public Player getPlayer() { + return player; + } + + /** + * Return the destination gate + * + * @return destination gate + */ + public Portal getDestination() { + return destination; + } + + /** + * Return the location of the players exit point + * + * @return org.bukkit.Location Location of the exit point + */ + public Location getExit() { + return exit; + } + + /** + * Set the location of the players exit point + */ + public void setExit(Location loc) { + this.exit = loc; + } + +} diff --git a/src/config.yml b/src/main/resources/config.yml similarity index 89% rename from src/config.yml rename to src/main/resources/config.yml index 65f2b73..75997b3 100644 --- a/src/config.yml +++ b/src/main/resources/config.yml @@ -1,54 +1,54 @@ -# Stargate Configuration File -# Main Stargate config -# -# portal-folder - The folder for storing portals -# gate-folder - The folder for storing gate layouts -# default-gate-network - The default gate network -# destroyexplosion - Whether or not to destroy gates with explosions (Creeper, TNT, etc) -# maxgates - The maximum number of gates allowed on a network - 0 for unlimited -# lang - The language file to load for messages -# destMemory - Whether to remember the cursor location between uses -# ignoreEntrance - Ignore the entrance blocks of a gate when checking. Used to work around snowmen -# handleVehicles - Whether to allow vehicles through gates -# sortLists - Whether to sort network lists alphabetically -# protectEntrance - Whether to protect gate entrance material (More resource intensive. Only enable if using destroyable open/closed material) -# signColor - The color used for drawing signs (Default: BLACK). -# verifyPortals - Whether or not all the non-sign blocks are checked to match the gate layout when a stargate is loaded. -############################ -# Stargate economy options # -############################ -# useeconomy - Whether to use an economy plugin -# createcost - The cost to create a gate -# destroycost - The cost to destroy a gate -# usecost - The cost to use a gate -# toowner - Whether the charge for using a gate goes to the gates owner -# chargefreedestination - Whether a gate whose destination is a free gate is still charged -# freegatesgreen - Whether a free gate in the destination list is drawn green -################# -# Debug options # -################# -# debug - Debug -- Only enable if you have issues, massive console output -# permdebug - This will output any and all Permissions checks to console, used for permissions debugging (Requires debug: true) -portal-folder: plugins/Stargate/portals/ -gate-folder: plugins/Stargate/gates/ -default-gate-network: central -destroyexplosion: false -maxgates: 0 -lang: en -destMemory: false -ignoreEntrance: false -handleVehicles: true -sortLists: false -protectEntrance: false -signColor: BLACK -useeconomy: false -createcost: 0 -destroycost: 0 -usecost: 0 -toowner: false -chargefreedestination: true -freegatesgreen: false -debug: false -permdebug: false -enableBungee: false +# stargate Configuration File +# Main stargate config +# +# portal-folder - The folder for storing portals +# gate-folder - The folder for storing gate layouts +# default-gate-network - The default gate network +# destroyexplosion - Whether or not to destroy gates with explosions (Creeper, TNT, etc) +# maxgates - The maximum number of gates allowed on a network - 0 for unlimited +# lang - The language file to load for messages +# destMemory - Whether to remember the cursor location between uses +# ignoreEntrance - Ignore the entrance blocks of a gate when checking. Used to work around snowmen +# handleVehicles - Whether to allow vehicles through gates +# sortLists - Whether to sort network lists alphabetically +# protectEntrance - Whether to protect gate entrance material (More resource intensive. Only enable if using destroyable open/closed material) +# signColor - The color used for drawing signs (Default: BLACK). +# verifyPortals - Whether or not all the non-sign blocks are checked to match the gate layout when a stargate is loaded. +############################ +# stargate economy options # +############################ +# useeconomy - Whether to use an economy plugin +# createcost - The cost to create a gate +# destroycost - The cost to destroy a gate +# usecost - The cost to use a gate +# toowner - Whether the charge for using a gate goes to the gates owner +# chargefreedestination - Whether a gate whose destination is a free gate is still charged +# freegatesgreen - Whether a free gate in the destination list is drawn green +################# +# Debug options # +################# +# debug - Debug -- Only enable if you have issues, massive console output +# permdebug - This will output any and all Permissions checks to console, used for permissions debugging (Requires debug: true) +portal-folder: plugins/stargate/portals/ +gate-folder: plugins/stargate/gates/ +default-gate-network: central +destroyexplosion: false +maxgates: 0 +lang: en +destMemory: false +ignoreEntrance: false +handleVehicles: true +sortLists: false +protectEntrance: false +signColor: BLACK +useeconomy: false +createcost: 0 +destroycost: 0 +usecost: 0 +toowner: false +chargefreedestination: true +freegatesgreen: false +debug: false +permdebug: false +enableBungee: false verifyPortals: false \ No newline at end of file diff --git a/src/net/TheDgtl/Stargate/resources/de.txt b/src/main/resources/lang/de.txt similarity index 89% rename from src/net/TheDgtl/Stargate/resources/de.txt rename to src/main/resources/lang/de.txt index 4bcfbb4..c10be27 100644 --- a/src/net/TheDgtl/Stargate/resources/de.txt +++ b/src/main/resources/lang/de.txt @@ -1,28 +1,28 @@ -author=EduardBaer -prefix=[Stargate] -teleportMsg=Du wurdest Teleportiert. -destroyMsg=Gate zerstört -invalidMsg=Ungültiges Ziel -blockMsg=Ziel blockiert -destEmpty=Zielliste leer -denyMsg=Zugriff verweigert - -ecoDeduct=%cost% abgezogen -ecoRefund=%cost% zurückerstattet -ecoObtain=%cost% von Stargate %portal% erhalten -ecoInFunds=Das kannst du dir nicht leisten. - -createMsg=Gate erstellt. -createNetDeny=Du hast keinen Zugriff auf dieses Netzwerk. -createGateDeny=Du hast keinen Zugriff auf dieses Gate-Layout. -createPersonal=Gate im persönlichen Netzwerk erstellt. -createNameLength=Name zu kurz oder zu lang. -createExists=Ein Gate mit diesem Name existiert bereits. -createFull=Dieses Netzwerk ist voll. -createWorldDeny=Du hast keinen Zugriff auf diese Welt. -createConflict=Dieses Gate steht im Konflikt mit einem bereits existierenden. - -signRightClick=Right click -signToUse=to use gate -signRandom=Random +author=EduardBaer +prefix=[Stargate] +teleportMsg=Du wurdest Teleportiert. +destroyMsg=Gate zerstört +invalidMsg=Ungültiges Ziel +blockMsg=Ziel blockiert +destEmpty=Zielliste leer +denyMsg=Zugriff verweigert + +ecoDeduct=%cost% abgezogen +ecoRefund=%cost% zurückerstattet +ecoObtain=%cost% von Stargate %portal% erhalten +ecoInFunds=Das kannst du dir nicht leisten. + +createMsg=Gate erstellt. +createNetDeny=Du hast keinen Zugriff auf dieses Netzwerk. +createGateDeny=Du hast keinen Zugriff auf dieses Gate-Layout. +createPersonal=Gate im persönlichen Netzwerk erstellt. +createNameLength=Name zu kurz oder zu chosenLanguage. +createExists=Ein Gate mit diesem Name existiert bereits. +createFull=Dieses Netzwerk ist voll. +createWorldDeny=Du hast keinen Zugriff auf diese Welt. +createConflict=Dieses Gate steht im Konflikt mit einem bereits existierenden. + +signRightClick=Right click +signToUse=to use gate +signRandom=Random signDisconnected=Disconnected \ No newline at end of file diff --git a/src/net/TheDgtl/Stargate/resources/en.txt b/src/main/resources/lang/en.txt similarity index 96% rename from src/net/TheDgtl/Stargate/resources/en.txt rename to src/main/resources/lang/en.txt index 8b50bd0..5227ba7 100644 --- a/src/net/TheDgtl/Stargate/resources/en.txt +++ b/src/main/resources/lang/en.txt @@ -1,32 +1,32 @@ -prefix=[Stargate] -teleportMsg=Teleported -destroyMsg=Gate Destroyed -invalidMsg=Invalid Destination -blockMsg=Destination Blocked -destEmpty=Destination List Empty -denyMsg=Access Denied - -ecoDeduct=Deducted %cost% -ecoRefund=Refunded %cost% -ecoObtain=Obtained %cost% from Stargate %portal% -ecoInFunds=Insufficient Funds - -createMsg=Gate Created -createNetDeny=You do not have access to that network -createGateDeny=You do not have access to that gate layout -createPersonal=Creating gate on personal network -createNameLength=Name too short or too long. -createExists=A gate by that name already exists -createFull=This network is full -createWorldDeny=You do not have access to that world -createConflict=Gate conflicts with existing gate - -signRightClick=Right click -signToUse=to use gate -signRandom=Random -signDisconnected=Disconnected - -bungeeDisabled=BungeeCord support is disabled. -bungeeDeny=You do not have permission to create BungeeCord gates. -bungeeEmpty=BungeeCord gates require both a destination and network. -bungeeSign=Teleport to +prefix=[Stargate] +teleportMsg=Teleported +destroyMsg=Gate Destroyed +invalidMsg=Invalid Destination +blockMsg=Destination Blocked +destEmpty=Destination List Empty +denyMsg=Access Denied + +ecoDeduct=Deducted %cost% +ecoRefund=Refunded %cost% +ecoObtain=Obtained %cost% from Stargate %portal% +ecoInFunds=Insufficient Funds + +createMsg=Gate Created +createNetDeny=You do not have access to that network +createGateDeny=You do not have access to that gate layout +createPersonal=Creating gate on personal network +createNameLength=Name too short or too long. +createExists=A gate by that name already exists +createFull=This network is full +createWorldDeny=You do not have access to that world +createConflict=Gate conflicts with existing gate + +signRightClick=Right click +signToUse=to use gate +signRandom=Random +signDisconnected=Disconnected + +bungeeDisabled=BungeeCord support is disabled. +bungeeDeny=You do not have permission to create BungeeCord gates. +bungeeEmpty=BungeeCord gates require both a destination and network. +bungeeSign=Teleport to diff --git a/src/net/TheDgtl/Stargate/resources/es.txt b/src/main/resources/lang/es.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/es.txt rename to src/main/resources/lang/es.txt diff --git a/src/net/TheDgtl/Stargate/resources/fr.txt b/src/main/resources/lang/fr.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/fr.txt rename to src/main/resources/lang/fr.txt diff --git a/src/net/TheDgtl/Stargate/resources/hu.txt b/src/main/resources/lang/hu.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/hu.txt rename to src/main/resources/lang/hu.txt diff --git a/src/net/TheDgtl/Stargate/resources/it.txt b/src/main/resources/lang/it.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/it.txt rename to src/main/resources/lang/it.txt diff --git a/src/net/TheDgtl/Stargate/resources/nl.txt b/src/main/resources/lang/nl.txt similarity index 90% rename from src/net/TheDgtl/Stargate/resources/nl.txt rename to src/main/resources/lang/nl.txt index 57f3db3..2e29b3c 100644 --- a/src/net/TheDgtl/Stargate/resources/nl.txt +++ b/src/main/resources/lang/nl.txt @@ -16,7 +16,7 @@ createMsg=Gate gemaakt createNetDeny=Je hebt geen toegang tot dat netwerk. createGateDeny=Je mag die Gate-Layout niet gebruiken createPersonal=Gate op persoonlijk netwerk gemaakt. -createNameLength=Naam te lang of te kort. +createNameLength=Naam te chosenLanguage of te kort. createExists=Er bestaat al een gate met die naam createFull=Dit netwerk is vol. createWorldDeny=Je mag niet in die wereld komen. diff --git a/src/net/TheDgtl/Stargate/resources/pt-br.txt b/src/main/resources/lang/pt-br.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/pt-br.txt rename to src/main/resources/lang/pt-br.txt diff --git a/src/net/TheDgtl/Stargate/resources/ru.txt b/src/main/resources/lang/ru.txt similarity index 100% rename from src/net/TheDgtl/Stargate/resources/ru.txt rename to src/main/resources/lang/ru.txt diff --git a/src/plugin.yml b/src/main/resources/plugin.yml similarity index 82% rename from src/plugin.yml rename to src/main/resources/plugin.yml index 75b676c..3f08d22 100644 --- a/src/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,30 +1,30 @@ -name: Stargate -main: net.TheDgtl.Stargate.Stargate -version: 0.8.0.3 -description: Stargate mod for Bukkit -author: Drakia -website: http://www.thedgtl.net -api-version: 1.13 -commands: - sg: - description: Used to reload the plugin. Console use only. - usage: / reload - Used to reload the plugin. Console use only. -permissions: - stargate.use: - description: Allow use of all gates linking to any world in any network - default: true - stargate.create: - description: Allow creating gates on any network - default: op - stargate.destroy: - description: Allow destruction gates on any network - default: op - stargate.free: - description: Allow free use/creation/destruction of gates - default: op - stargate.option: - description: Allow use of all options - default: op - stargate.admin: - description: Allow all admin features (Hidden/Private only so far) +name: Stargate +main: net.knarcraft.stargate.Stargate +version: 0.8.0.0 +description: Stargate mod for Bukkit +author: EpicKnarvik97 +website: https://knarcraft.net +api-version: 1.16 +commands: + sg: + description: Used to reload the plugin. Console use only. + usage: / reload - Used to reload the plugin. Console use only. +permissions: + stargate.use: + description: Allow use of all gates linking to any world in any network + default: true + stargate.create: + description: Allow creating gates on any network + default: op + stargate.destroy: + description: Allow destruction gates on any network + default: op + stargate.free: + description: Allow free use/creation/destruction of gates + default: op + stargate.option: + description: Allow use of all options + default: op + stargate.admin: + description: Allow all admin features (Hidden/Private only so far) default: op \ No newline at end of file diff --git a/src/net/TheDgtl/Stargate/Blox.java b/src/net/TheDgtl/Stargate/Blox.java deleted file mode 100644 index f45c023..0000000 --- a/src/net/TheDgtl/Stargate/Blox.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.TheDgtl.Stargate; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Sign; -import org.bukkit.block.data.type.WallSign; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class Blox { - private final int x; - private final int y; - private final int z; - private final World world; - private Blox parent = null; - - public Blox (World world, int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - this.world = world; - } - - public Blox (Block block) { - this.x = block.getX(); - this.y = block.getY(); - this.z = block.getZ(); - this.world = block.getWorld(); - } - - public Blox (Location location) { - this.x = location.getBlockX(); - this.y = location.getBlockY(); - this.z = location.getBlockZ(); - this.world = location.getWorld(); - } - - public Blox (World world, String string) { - String[] split = string.split(","); - this.x = Integer.parseInt(split[0]); - this.y = Integer.parseInt(split[1]); - this.z = Integer.parseInt(split[2]); - this.world = world; - } - - public Blox makeRelative(int x, int y, int z) { - return new Blox(this.world, this.x + x, this.y + y, this.z + z); - } - - public Location makeRelativeLoc(double x, double y, double z, float rotX, float rotY) { - return new Location(this.world, (double)this.x + x, (double)this.y + y, (double)this.z + z, rotX, rotY); - } - - public Blox modRelative(int right, int depth, int distance, int modX, int modY, int modZ) { - return makeRelative(-right * modX + distance * modZ, -depth * modY, -right * modZ + -distance * modX); - } - - public Location modRelativeLoc(double right, double depth, double distance, float rotX, float rotY, int modX, int modY, int modZ) { - return makeRelativeLoc(0.5 + -right * modX + distance * modZ, depth, 0.5 + -right * modZ + -distance * modX, rotX, 0); - } - - public void setType(Material type) { - world.getBlockAt(x, y, z).setType(type); - } - - public Material getType() { - return world.getBlockAt(x, y, z).getType(); - } - - public Block getBlock() { - return world.getBlockAt(x, y, z); - } - - public Location getLocation() { - return new Location(world, x, y, z); - } - - public int getX() { - return x; - } - - public int getY() { - return y; - } - - public int getZ() { - return z; - } - - public World getWorld() { - return world; - } - - public Block getParent() { - if (parent == null) findParent(); - if (parent == null) return null; - return parent.getBlock(); - } - - private void findParent() { - int offsetX = 0; - int offsetY = 0; - int offsetZ = 0; - - BlockData blk = getBlock().getBlockData(); - if (blk instanceof WallSign) { - BlockFace facing = ((WallSign) blk).getFacing().getOppositeFace(); - offsetX = facing.getModX(); - offsetZ = facing.getModZ(); - } else if (blk instanceof Sign) { - offsetY = -1; - } else { - return; - } - parent = new Blox(world, getX() + offsetX, getY() + offsetY, getZ() + offsetZ); - } - - public String toString() { - StringBuilder builder = new StringBuilder(); - //builder.append(world.getName()); - //builder.append(','); - builder.append(x); - builder.append(','); - builder.append(y); - builder.append(','); - builder.append(z); - return builder.toString(); - } - - @Override - public int hashCode() { - int result = 18; - - result = result * 27 + x; - result = result * 27 + y; - result = result * 27 + z; - result = result * 27 + world.getName().hashCode(); - - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - - Blox blox = (Blox) obj; - return (x == blox.x) && (y == blox.y) && (z == blox.z) && (world.getName().equals(blox.world.getName())); - } -} \ No newline at end of file diff --git a/src/net/TheDgtl/Stargate/BloxPopulator.java b/src/net/TheDgtl/Stargate/BloxPopulator.java deleted file mode 100644 index 88290fb..0000000 --- a/src/net/TheDgtl/Stargate/BloxPopulator.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.TheDgtl.Stargate; - -import org.bukkit.Axis; -import org.bukkit.Material; - -public class BloxPopulator { - private Blox blox; - private Material nextMat; - private Axis nextAxis; - - public BloxPopulator(Blox b, Material m) { - blox = b; - nextMat = m; - nextAxis = null; - } - - public BloxPopulator(Blox b, Material m, Axis a) { - blox = b; - nextMat = m; - nextAxis = a; - } - - public void setBlox(Blox b) { - blox = b; - } - - public void setMat(Material m) { - nextMat = m; - } - - public void setAxis(Axis a) { - nextAxis = a; - } - - public Blox getBlox() { - return blox; - } - - public Material getMat() { - return nextMat; - } - - public Axis getAxis() { - return nextAxis; - } - -} diff --git a/src/net/TheDgtl/Stargate/EconomyHandler.java b/src/net/TheDgtl/Stargate/EconomyHandler.java deleted file mode 100644 index 36963d7..0000000 --- a/src/net/TheDgtl/Stargate/EconomyHandler.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.TheDgtl.Stargate; - -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; - -import java.util.UUID; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class EconomyHandler { - public static boolean economyEnabled = false; - public static Economy economy = null; - public static Plugin vault = null; - - public static int useCost = 0; - public static int createCost = 0; - public static int destroyCost = 0; - public static boolean toOwner = false; - public static boolean chargeFreeDestination = true; - public static boolean freeGatesGreen = false; - - public static double getBalance(Player player) { - if (!economyEnabled) return 0; - return economy.getBalance(player); - } - - public static boolean chargePlayer(Player player, String target, double amount) { - if (!economyEnabled) return true; - if(player.getName().equals(target)) return true; - if(economy != null) { - if(!economy.has(player, amount)) return false; - economy.withdrawPlayer(player, amount); - economy.depositPlayer(target, amount); - } - return true; - } - - public static boolean chargePlayer(Player player, UUID target, double amount) { - if (!economyEnabled) return true; - if(player.getUniqueId().compareTo(target) == 0) return true; - if(economy != null) { - if(!economy.has(player, amount)) return false; - economy.withdrawPlayer(player, amount); - economy.depositPlayer(Bukkit.getOfflinePlayer(target), amount); - } - return true; - } - - public static boolean chargePlayer(Player player, double amount) { - if (!economyEnabled) return true; - if(economy != null) { - if(!economy.has(player, amount)) return false; - economy.withdrawPlayer(player, amount); - } - return true; - } - - public static String format(int amt) { - if (economyEnabled) { - return economy.format(amt); - } - return ""; - } - - public static boolean setupEconomy(PluginManager pm) { - if (!economyEnabled) return false; - // Check for Vault - Plugin p = pm.getPlugin("Vault"); - if (p != null && p.isEnabled()) { - RegisteredServiceProvider economyProvider = Stargate.server.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - vault = p; - return true; - } - } - economyEnabled = false; - return false; - } - - public static boolean useEconomy() { - return economyEnabled && economy != null; - } - -} diff --git a/src/net/TheDgtl/Stargate/Gate.java b/src/net/TheDgtl/Stargate/Gate.java deleted file mode 100644 index 31bb93f..0000000 --- a/src/net/TheDgtl/Stargate/Gate.java +++ /dev/null @@ -1,513 +0,0 @@ -package net.TheDgtl.Stargate; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Scanner; -import java.util.logging.Level; - -import org.bukkit.Material; -import org.bukkit.Tag; -import org.bukkit.block.Block; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class Gate { - private static final Character ANYTHING = ' '; - private static final Character ENTRANCE = '.'; - private static final Character EXIT = '*'; - private static final HashMap gates = new HashMap<>(); - private static final HashMap> controlBlocks = new HashMap<>(); - private static final HashSet frameBlocks = new HashSet<>(); - - private final String filename; - private final Character[][] layout; - private final HashMap types; - private RelativeBlockVector[] entrances = new RelativeBlockVector[0]; - private RelativeBlockVector[] border = new RelativeBlockVector[0]; - private RelativeBlockVector[] controls = new RelativeBlockVector[0]; - private RelativeBlockVector exitBlock = null; - private final HashMap exits = new HashMap<>(); - private Material portalBlockOpen = Material.NETHER_PORTAL; - private Material portalBlockClosed = Material.AIR; - private Material button = Material.STONE_BUTTON; - - // Economy information - private int useCost = -1; - private int createCost = -1; - private int destroyCost = -1; - private boolean toOwner = false; - - public Gate(String filename, Character[][] layout, HashMap types) { - this.filename = filename; - this.layout = layout; - this.types = types; - - populateCoordinates(); - } - - private void populateCoordinates() { - ArrayList entranceList = new ArrayList<>(); - ArrayList borderList = new ArrayList<>(); - ArrayList controlList = new ArrayList<>(); - RelativeBlockVector[] relativeExits = new RelativeBlockVector[layout[0].length]; - int[] exitDepths = new int[layout[0].length]; - RelativeBlockVector lastExit = null; - - for (int y = 0; y < layout.length; y++) { - for (int x = 0; x < layout[y].length; x++) { - Character key = layout[y][x]; - if (key.equals('-')) { - controlList.add(new RelativeBlockVector(x, y, 0)); - } - - if (key.equals(ENTRANCE) || key.equals(EXIT)) { - entranceList.add(new RelativeBlockVector(x, y, 0)); - exitDepths[x] = y; - if (key.equals(EXIT)) { - this.exitBlock = new RelativeBlockVector(x, y, 0); - } - } else if (!key.equals(ANYTHING)) { - borderList.add(new RelativeBlockVector(x, y, 0)); - } - } - } - - for (int x = 0; x < exitDepths.length; x++) { - relativeExits[x] = new RelativeBlockVector(x, exitDepths[x], 0); - } - - for (int x = relativeExits.length - 1; x >= 0; x--) { - if (relativeExits[x] != null) { - lastExit = relativeExits[x]; - } else { - relativeExits[x] = lastExit; - } - - if (exitDepths[x] > 0) this.exits.put(relativeExits[x], x); - } - - this.entrances = entranceList.toArray(this.entrances); - this.border = borderList.toArray(this.border); - this.controls = controlList.toArray(this.controls); - } - - public void save(String gateFolder) { - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(gateFolder + filename)); - - writeConfig(bw, "portal-open", portalBlockOpen.name()); - writeConfig(bw, "portal-closed", portalBlockClosed.name()); - writeConfig(bw, "button", button.name()); - if (useCost != -1) - writeConfig(bw, "usecost", useCost); - if (createCost != -1) - writeConfig(bw, "createcost", createCost); - if (destroyCost != -1) - writeConfig(bw, "destroycost", destroyCost); - writeConfig(bw, "toowner", toOwner); - - for (Map.Entry entry : types.entrySet()) { - Character type = entry.getKey(); - Material value = entry.getValue(); - // Skip control values - if (type.equals(ANYTHING) || type.equals(ENTRANCE) || type.equals(EXIT)) { - continue; - } - - bw.append(type); - bw.append('='); - if(value != null) { - bw.append(value.toString()); - } - bw.newLine(); - } - - bw.newLine(); - - for(Character[] aLayout : layout) { - for(Character symbol : aLayout) { - bw.append(symbol); - } - bw.newLine(); - } - - bw.close(); - } catch (IOException ex) { - Stargate.log.log(Level.SEVERE, "Could not save Gate " + filename + " - " + ex.getMessage()); - } - } - - private void writeConfig(BufferedWriter bw, String key, int value) throws IOException { - bw.append(String.format("%s=%d", key, value)); - bw.newLine(); - } - - private void writeConfig(BufferedWriter bw, String key, boolean value) throws IOException { - bw.append(String.format("%s=%b", key, value)); - bw.newLine(); - } - - private void writeConfig(BufferedWriter bw, String key, String value) throws IOException { - bw.append(String.format("%s=%s", key, value)); - bw.newLine(); - } - - public Character[][] getLayout() { - return layout; - } - - public HashMap getTypes() { - return types; - } - - public RelativeBlockVector[] getEntrances() { - return entrances; - } - - public RelativeBlockVector[] getBorder() { - return border; - } - - public RelativeBlockVector[] getControls() { - return controls; - } - - public HashMap getExits() { - return exits; - } - public RelativeBlockVector getExit() { - return exitBlock; - } - - public Material getControlBlock() { - return types.get('-'); - } - - public String getFilename() { - return filename; - } - - public Material getPortalBlockOpen() { - return portalBlockOpen; - } - - public void setPortalBlockOpen(Material type) { - portalBlockOpen = type; - } - - public Material getPortalBlockClosed() { - return portalBlockClosed; - } - - public void setPortalBlockClosed(Material type) { - portalBlockClosed = type; - } - - public Material getButton() { - return button; - } - - public int getUseCost() { - if (useCost < 0) return EconomyHandler.useCost; - return useCost; - } - - public Integer getCreateCost() { - if (createCost < 0) return EconomyHandler.createCost; - return createCost; - } - - public Integer getDestroyCost() { - if (destroyCost < 0) return EconomyHandler.destroyCost; - return destroyCost; - } - - public Boolean getToOwner() { - return toOwner; - } - - public boolean matches(Blox topleft, int modX, int modZ) { - return matches(topleft, modX, modZ, false); - } - - public boolean matches(Blox topleft, int modX, int modZ, boolean onCreate) { - HashMap portalTypes = new HashMap<>(types); - for (int y = 0; y < layout.length; y++) { - for (int x = 0; x < layout[y].length; x++) { - Character key = layout[y][x]; - - if (key.equals(ENTRANCE) || key.equals(EXIT)) { - if (Stargate.ignoreEntrance) continue; - - Material type = topleft.modRelative(x, y, 0, modX, 1, modZ).getType(); - - // Ignore entrance if it's air and we're creating a new gate - if (onCreate && type == Material.AIR) continue; - - if (type != portalBlockClosed && type != portalBlockOpen) { - Stargate.debug("Gate::Matches", "Entrance/Exit Material Mismatch: " + type); - return false; - } - } else if (!key.equals(ANYTHING)) { - Material id = portalTypes.get(key); - if(id == null) { - portalTypes.put(key, topleft.modRelative(x, y, 0, modX, 1, modZ).getType()); - } else if(topleft.modRelative(x, y, 0, modX, 1, modZ).getType() != id) { - Stargate.debug("Gate::Matches", "Block Type Mismatch: " + topleft.modRelative(x, y, 0, modX, 1, modZ).getType() + " != " + id); - return false; - } - } - } - } - - return true; - } - - public static void registerGate(Gate gate) { - gates.put(gate.getFilename(), gate); - - Material blockID = gate.getControlBlock(); - - if (!controlBlocks.containsKey(blockID)) { - controlBlocks.put(blockID, new ArrayList<>()); - } - - controlBlocks.get(blockID).add(gate); - } - - public static Gate loadGate(File file) { - Scanner scanner = null; - boolean designing = false; - ArrayList> design = new ArrayList<>(); - HashMap types = new HashMap<>(); - HashMap config = new HashMap<>(); - HashSet frameTypes = new HashSet<>(); - int cols = 0; - - // Init types map - types.put(ENTRANCE, Material.AIR); - types.put(EXIT, Material.AIR); - types.put(ANYTHING, Material.AIR); - - try { - scanner = new Scanner(file); - - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - - if (designing) { - ArrayList row = new ArrayList<>(); - - if (line.length() > cols) { - cols = line.length(); - } - - for (Character symbol : line.toCharArray()) { - if ((symbol.equals('?')) || (!types.containsKey(symbol))) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Unknown symbol '" + symbol + "' in diagram"); - return null; - } - row.add(symbol); - } - - design.add(row); - } else { - if ((line.isEmpty()) || (!line.contains("="))) { - designing = true; - } else { - String[] split = line.split("="); - String key = split[0].trim(); - String value = split[1].trim(); - - if (key.length() == 1) { - Character symbol = key.charAt(0); - Material id = Material.getMaterial(value); - if(id == null) { - throw new Exception("Invalid material in line: " + line); - } - types.put(symbol, id); - frameTypes.add(id); - } else { - config.put(key, value); - } - } - } - } - } catch (Exception ex) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - " + ex.getMessage()); - return null; - } finally { - if (scanner != null) scanner.close(); - } - - Character[][] layout = new Character[design.size()][cols]; - - for (int y = 0; y < design.size(); y++) { - ArrayList row = design.get(y); - Character[] result = new Character[cols]; - - for (int x = 0; x < cols; x++) { - if (x < row.size()) { - result[x] = row.get(x); - } else { - result[x] = ' '; - } - } - - layout[y] = result; - } - - Gate gate = new Gate(file.getName(), layout, types); - - gate.portalBlockOpen = readConfig(config, gate, file, "portal-open", gate.portalBlockOpen); - gate.portalBlockClosed = readConfig(config, gate, file, "portal-closed", gate.portalBlockClosed); - gate.button = readConfig(config, gate, file, "button", gate.button); - gate.useCost = readConfig(config, gate, file, "usecost", -1); - gate.destroyCost = readConfig(config, gate, file, "destroycost", -1); - gate.createCost = readConfig(config, gate, file, "createcost", -1); - gate.toOwner = (config.containsKey("toowner") ? Boolean.valueOf(config.get("toowner")) : EconomyHandler.toOwner); - - if (gate.getControls().length != 2) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gates must have exactly 2 control points."); - return null; - } - - if (!Tag.BUTTONS.isTagged(gate.button)) { - Stargate.log.log(Level.SEVERE, "Could not load Gate " + file.getName() + " - Gate button must be a type of button."); - return null; - } - - // Merge frame types, add open mat to list - frameBlocks.addAll(frameTypes); - - gate.save(file.getParent() + "/"); // Updates format for version changes - return gate; - } - - private static int readConfig(HashMap config, Gate gate, File file, String key, int def) { - if (config.containsKey(key)) { - try { - return Integer.parseInt(config.get(key)); - } catch (NumberFormatException ex) { - Stargate.log.log(Level.WARNING, String.format("%s reading %s: %s is not numeric", ex.getClass().getName(), file, key)); - } - } - - return def; - } - - private static Material readConfig(HashMap config, Gate gate, File file, String key, Material def) { - if (config.containsKey(key)) { - Material mat = Material.getMaterial(config.get(key)); - if(mat != null) { - return mat; - } - Stargate.log.log(Level.WARNING, String.format("Error reading %s: %s is not a material", file, key)); - } - return def; - } - - public static void loadGates(String gateFolder) { - File dir = new File(gateFolder); - File[] files; - - if (dir.exists()) { - files = dir.listFiles(new StargateFilenameFilter()); - } else { - files = new File[0]; - } - - if (files == null || files.length == 0) { - if (dir.mkdir()) { - populateDefaults(gateFolder); - } - } else { - for (File file : files) { - Gate gate = loadGate(file); - if (gate != null) registerGate(gate); - } - } - } - - public static void populateDefaults(String gateFolder) { - Character[][] layout = new Character[][] { - {' ', 'X','X', ' '}, - {'X', '.', '.', 'X'}, - {'-', '.', '.', '-'}, - {'X', '*', '.', 'X'}, - {' ', 'X', 'X', ' '}, - }; - HashMap types = new HashMap<>(); - types.put(ENTRANCE, Material.AIR); - types.put(EXIT, Material.AIR); - types.put(ANYTHING, Material.AIR); - types.put('X', Material.OBSIDIAN); - types.put('-', Material.OBSIDIAN); - - Gate gate = new Gate("nethergate.gate", layout, types); - gate.save(gateFolder); - registerGate(gate); - } - - public static Gate[] getGatesByControlBlock(Block block) { - return getGatesByControlBlock(block.getType()); - } - - public static Gate[] getGatesByControlBlock(Material type) { - Gate[] result = new Gate[0]; - ArrayList lookup = controlBlocks.get(type); - - if (lookup != null) result = lookup.toArray(result); - - return result; - } - - public static Gate getGateByName(String name) { - return gates.get(name); - } - - public static int getGateCount() { - return gates.size(); - } - - public static boolean isGateBlock(Material type) { - return frameBlocks.contains(type); - } - - static class StargateFilenameFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - return name.endsWith(".gate"); - } - } - - public static void clearGates() { - gates.clear(); - controlBlocks.clear(); - frameBlocks.clear(); - } -} diff --git a/src/net/TheDgtl/Stargate/LangLoader.java b/src/net/TheDgtl/Stargate/LangLoader.java deleted file mode 100644 index ad4a718..0000000 --- a/src/net/TheDgtl/Stargate/LangLoader.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.TheDgtl.Stargate; - -import org.bukkit.ChatColor; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Set; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class LangLoader { - private final String UTF8_BOM = "\uFEFF"; - // Variables - private final String datFolder; - private String lang; - private HashMap strList; - private final HashMap defList; - - public LangLoader(String datFolder, String lang) { - this.lang = lang; - this.datFolder = datFolder; - - File tmp = new File(datFolder, lang + ".txt"); - if (!tmp.exists()) { - tmp.getParentFile().mkdirs(); - } - updateLanguage(lang); - - strList = load(lang); - // We have a default hashMap used for when new text is added. - InputStream is = Stargate.class.getResourceAsStream("resources/" + lang + ".txt"); - if (is != null) { - defList = load("en", is); - } else { - defList = null; - Stargate.log.severe("[Stargate] Error loading backup language. There may be missing text ingame"); - } - } - - public boolean reload() { - // This extracts/updates the language as needed - updateLanguage(lang); - strList = load(lang); - return true; - } - - public String getString(String name) { - String val = strList.get(name); - if (val == null && defList != null) val = defList.get(name); - if (val == null) return ""; - return val; - } - - public void setLang(String lang) { - this.lang = lang; - } - - // This function updates on-disk language files - // with missing lines from the in-JAR files - private void updateLanguage(String lang) { - // Load the current language file - ArrayList keyList = new ArrayList<>(); - ArrayList valList = new ArrayList<>(); - - HashMap curLang = load(lang); - - InputStream is = Stargate.class.getResourceAsStream("resources/" + lang + ".txt"); - if (is == null) return; - - boolean updated = false; - FileOutputStream fos = null; - try { - // Input stuff - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - - String line = br.readLine(); - boolean firstLine = true; - while (line != null) { - // Strip UTF BOM - if (firstLine) line = removeUTF8BOM(line); - firstLine = false; - // Split at first "=" - int eq = line.indexOf('='); - if (eq == -1) { - keyList.add(""); - valList.add(""); - line = br.readLine(); - continue; - } - String key = line.substring(0, eq); - String val = line.substring(eq); - - if (curLang == null || curLang.get(key) == null) { - keyList.add(key); - valList.add(val); - updated = true; - } else { - keyList.add(key); - valList.add("=" + curLang.get(key).replace('\u00A7', '&')); - curLang.remove(key); - } - line = br.readLine(); - } - br.close(); - - // Save file - fos = new FileOutputStream(datFolder + lang + ".txt"); - OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8); - BufferedWriter bw = new BufferedWriter(out); - - // Output normal Language data - for (int i = 0; i < keyList.size(); i++) { - bw.write(keyList.get(i) + valList.get(i)); - bw.newLine(); - } - bw.newLine(); - // Output any custom language strings the user had - if(curLang != null) { - for (String key : curLang.keySet()) { - bw.write(key + "=" + curLang.get(key)); - bw.newLine(); - } - } - - bw.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - if (fos != null) { - try {fos.close();} catch (Exception ex) {} - } - } - if (updated) - Stargate.log.info("[Stargate] Your language file (" + lang + ".txt) has been updated"); - } - - private HashMap load(String lang) { - return load(lang, null); - } - - private HashMap load(String lang, InputStream is) { - HashMap strings = new HashMap<>(); - FileInputStream fis = null; - InputStreamReader isr = null; - try { - if (is == null) { - fis = new FileInputStream(datFolder + lang + ".txt"); - isr = new InputStreamReader(fis, StandardCharsets.UTF_8); - } else { - isr = new InputStreamReader(is, StandardCharsets.UTF_8); - } - BufferedReader br = new BufferedReader(isr); - String line = br.readLine(); - boolean firstLine = true; - while (line != null) { - // Strip UTF BOM - if (firstLine) line = removeUTF8BOM(line); - firstLine = false; - // Split at first "=" - int eq = line.indexOf('='); - if (eq == -1) { - line = br.readLine(); - continue; - } - String key = line.substring(0, eq); - String val = ChatColor.translateAlternateColorCodes('&', line.substring(eq + 1)); - strings.put(key, val); - line = br.readLine(); - } - } catch (Exception ex) { - return null; - } finally { - if (fis != null) { - try { - fis.close(); - } catch (Exception ex) {} - } - } - return strings; - } - - public void debug() { - Set keys = strList.keySet(); - for (String key : keys) { - Stargate.debug("LangLoader::Debug::strList", key + " => " + strList.get(key)); - } - if (defList == null) return; - keys = defList.keySet(); - for (String key : keys) { - Stargate.debug("LangLoader::Debug::defList", key + " => " + defList.get(key)); - } - } - - private String removeUTF8BOM(String s) { - if (s.startsWith(UTF8_BOM)) { - s = s.substring(1); - } - return s; - } -} diff --git a/src/net/TheDgtl/Stargate/Portal.java b/src/net/TheDgtl/Stargate/Portal.java deleted file mode 100644 index 2a74f76..0000000 --- a/src/net/TheDgtl/Stargate/Portal.java +++ /dev/null @@ -1,1495 +0,0 @@ -package net.TheDgtl.Stargate; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.*; -import java.util.logging.Level; - -import net.TheDgtl.Stargate.event.StargateActivateEvent; -import net.TheDgtl.Stargate.event.StargateCloseEvent; -import net.TheDgtl.Stargate.event.StargateCreateEvent; -import net.TheDgtl.Stargate.event.StargateDeactivateEvent; -import net.TheDgtl.Stargate.event.StargateOpenEvent; -import net.TheDgtl.Stargate.event.StargatePortalEvent; - -import org.bukkit.Axis; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.Sign; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Powerable; -import org.bukkit.block.data.type.WallSign; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.entity.minecart.StorageMinecart; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.util.Vector; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class Portal { - // Static variables used to store portal lists - private static final HashMap lookupBlocks = new HashMap<>(); - private static final HashMap lookupEntrances = new HashMap<>(); - private static final HashMap lookupControls = new HashMap<>(); - private static final ArrayList allPortals = new ArrayList<>(); - private static final HashMap> allPortalsNet = new HashMap<>(); - private static final HashMap> lookupNamesNet = new HashMap<>(); - - // A list of Bungee gates - private static final HashMap bungeePortals = new HashMap<>(); - - // Gate location block info - private final Blox topLeft; - private final int modX; - private final int modZ; - private final float rotX; - private final Axis rot; - - // Block references - private final Blox id; - private Blox button; - private Blox[] frame; - private Blox[] entrances; - - // Gate information - private String name; - private String destination; - private String lastDest = ""; - private String network; - private final Gate gate; - private String ownerName = ""; - private UUID ownerUUID = null; - private final World world; - private boolean verified; - private boolean fixed; - - // Options - private boolean hidden = false; - private boolean alwaysOn = false; - private boolean priv = false; - private boolean free = false; - private boolean backwards = false; - private boolean show = false; - private boolean noNetwork = false; - private boolean random = false; - private boolean bungee = false; - - // In-use information - private Player player; - private Player activePlayer; - private ArrayList destinations = new ArrayList<>(); - private boolean isOpen = false; - private long openTime; - - private Portal(Blox topLeft, int modX, int modZ, - float rotX, Blox id, Blox button, - String dest, String name, - boolean verified, String network, Gate gate, UUID ownerUUID, String ownerName, - boolean hidden, boolean alwaysOn, boolean priv, boolean free, boolean backwards, boolean show, boolean noNetwork, boolean random, boolean bungee) { - this.topLeft = topLeft; - this.modX = modX; - this.modZ = modZ; - this.rotX = rotX; - this.rot = rotX == 0.0F || rotX == 180.0F ? Axis.X : Axis.Z; - this.id = id; - this.destination = dest; - this.button = button; - this.verified = verified; - this.network = network; - this.name = name; - this.gate = gate; - this.ownerUUID = ownerUUID; - this.ownerName = ownerName; - this.hidden = hidden; - this.alwaysOn = alwaysOn; - this.priv = priv; - this.free = free; - this.backwards = backwards; - this.show = show; - this.noNetwork = noNetwork; - this.random = random; - this.bungee = bungee; - this.world = topLeft.getWorld(); - this.fixed = dest.length() > 0 || this.random || this.bungee; - - if (this.isAlwaysOn() && !this.isFixed()) { - this.alwaysOn = false; - Stargate.debug("Portal", "Can not create a non-fixed always-on gate. Setting AlwaysOn = false"); - } - - if (this.random && !this.isAlwaysOn()) { - this.alwaysOn = true; - Stargate.debug("Portal", "Gate marked as random, set to always-on"); - } - - if (verified) { - this.drawSign(); - } - } - - /** - * Option Check Functions - */ - public boolean isOpen() { - return isOpen || isAlwaysOn(); - } - - public boolean isAlwaysOn() { - return alwaysOn; - } - - public boolean isHidden() { - return hidden; - } - - public boolean isPrivate() { - return priv; - } - - public boolean isFree() { - return free; - } - - public boolean isBackwards() { - return backwards; - } - - public boolean isShown() { - return show; - } - - public boolean isNoNetwork() { - return noNetwork; - } - - public boolean isRandom() { - return random; - } - - public boolean isBungee() { - return bungee; - } - - public void setAlwaysOn(boolean alwaysOn) { - this.alwaysOn = alwaysOn; - } - - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - public void setPrivate(boolean priv) { - this.priv = priv; - } - - public void setFree(boolean free) { - this.free = free; - } - - public void setBackwards(boolean backwards) { - this.backwards = backwards; - } - - public void setShown(boolean show) { - this.show = show; - } - - public void setNoNetwork(boolean noNetwork) { - this.noNetwork = noNetwork; - } - - public void setRandom(boolean random) { - this.random = random; - } - - /** - * Getters and Setters - */ - - public float getRotation() { - return rotX; - } - - public Axis getAxis() { - return rot; - } - - public Player getActivePlayer() { - return activePlayer; - } - - public String getNetwork() { - return network; - } - - public void setNetwork(String network) { - this.network = network; - } - - public long getOpenTime() { - return openTime; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = filterName(name); - drawSign(); - } - - public Portal getDestination(Player player) { - if (isRandom()) { - destinations = getDestinations(player, getNetwork()); - if (destinations.size() == 0) { - return null; - } - String dest = destinations.get((new Random()).nextInt(destinations.size())); - destinations.clear(); - return Portal.getByName(dest, getNetwork()); - } - return Portal.getByName(destination, getNetwork()); - } - - public Portal getDestination() { - return getDestination(null); - } - - public void setDestination(Portal destination) { - setDestination(destination.getName()); - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public String getDestinationName() { - return destination; - } - - public Gate getGate() { - return gate; - } - - public String getOwnerName() { - return ownerName; - } - - public UUID getOwnerUUID() { - return ownerUUID; - } - - public void setOwner(UUID owner) { - this.ownerUUID = owner; - } - - public boolean isOwner(Player player) { - if(this.ownerUUID != null) { - return player.getUniqueId().compareTo(this.ownerUUID) == 0; - } else { - return player.getName().equalsIgnoreCase(this.ownerName); - } - } - - public Blox[] getEntrances() { - if (entrances == null) { - RelativeBlockVector[] space = gate.getEntrances(); - entrances = new Blox[space.length]; - int i = 0; - - for (RelativeBlockVector vector : space) { - entrances[i++] = getBlockAt(vector); - } - } - return entrances; - } - - public Blox[] getFrame() { - if (frame == null) { - RelativeBlockVector[] border = gate.getBorder(); - frame = new Blox[border.length]; - int i = 0; - - for (RelativeBlockVector vector : border) { - frame[i++] = getBlockAt(vector); - } - } - - return frame; - } - - public Blox getSign() { - return id; - } - - public World getWorld() { - return world; - } - - public Blox getButton() { - return button; - } - - public void setButton(Blox button) { - this.button = button; - } - - public static ArrayList getNetwork(String network) { - return allPortalsNet.get(network.toLowerCase()); - } - - public boolean open(boolean force) { - return open(null, force); - } - - public boolean open(Player openFor, boolean force) { - // Call the StargateOpenEvent - StargateOpenEvent event = new StargateOpenEvent(openFor, this, force); - Stargate.server.getPluginManager().callEvent(event); - if (event.isCancelled()) return false; - force = event.getForce(); - - if (isOpen() && !force) return false; - - Material openType = gate.getPortalBlockOpen(); - Axis ax = openType == Material.NETHER_PORTAL ? rot : null; - for (Blox inside : getEntrances()) { - Stargate.blockPopulatorQueue.add(new BloxPopulator(inside, openType, ax)); - } - - isOpen = true; - openTime = System.currentTimeMillis() / 1000; - Stargate.openList.add(this); - Stargate.activeList.remove(this); - - // Open remote gate - if (!isAlwaysOn()) { - player = openFor; - - Portal end = getDestination(); - // Only open dest if it's not-fixed or points at this gate - if (!random && end != null && (!end.isFixed() || end.getDestinationName().equalsIgnoreCase(getName())) && !end.isOpen()) { - end.open(openFor, false); - end.setDestination(this); - if (end.isVerified()) end.drawSign(); - } - } - - return true; - } - - public void close(boolean force) { - if (!isOpen) return; - // Call the StargateCloseEvent - StargateCloseEvent event = new StargateCloseEvent(this, force); - Stargate.server.getPluginManager().callEvent(event); - if (event.isCancelled()) return; - force = event.getForce(); - - if (isAlwaysOn() && !force) return; // Only close always-open if forced - - // Close this gate, then the dest gate. - Material closedType = gate.getPortalBlockClosed(); - for (Blox inside : getEntrances()) { - Stargate.blockPopulatorQueue.add(new BloxPopulator(inside, closedType)); - } - - player = null; - isOpen = false; - Stargate.openList.remove(this); - Stargate.activeList.remove(this); - - if (!isAlwaysOn()) { - Portal end = getDestination(); - - if (end != null && end.isOpen()) { - end.deactivate(); // Clear it's destination first. - end.close(false); - } - } - - deactivate(); - } - - public boolean isOpenFor(Player player) { - if (!isOpen) { - return false; - } - if ((isAlwaysOn()) || (this.player == null)) { - return true; - } - return (player != null) && (player.getName().equalsIgnoreCase(this.player.getName())); - } - - public boolean isFixed() { - return fixed; - } - - public boolean isPowered() { - RelativeBlockVector[] controls = gate.getControls(); - - for (RelativeBlockVector vector : controls) { - BlockData data = getBlockAt(vector).getBlock().getBlockData(); - - if (data instanceof Powerable && ((Powerable) data).isPowered()) { - return true; - } - } - - return false; - } - - public void teleport(Player player, Portal origin, PlayerMoveEvent event) { - Location traveller = player.getLocation(); - Location exit = getExit(traveller); - - // Handle backwards gates - int adjust = 180; - if (isBackwards() != origin.isBackwards()) - adjust = 0; - exit.setYaw(traveller.getYaw() - origin.getRotation() + this.getRotation() + adjust); - - // Call the StargatePortalEvent to allow plugins to change destination - if (!origin.equals(this)) { - StargatePortalEvent pEvent = new StargatePortalEvent(player, origin, this, exit); - Stargate.server.getPluginManager().callEvent(pEvent); - // Teleport is cancelled - if (pEvent.isCancelled()) { - origin.teleport(player, origin, event); - return; - } - // Update exit if needed - exit = pEvent.getExit(); - } - - // If no event is passed in, assume it's a teleport, and act as such - if (event == null) { - exit.setYaw(this.getRotation()); - player.teleport(exit); - } else { - // The new method to teleport in a move event is set the "to" field. - event.setTo(exit); - } - } - - public void teleport(final Vehicle vehicle) { - Location traveller = new Location(this.world, vehicle.getLocation().getX(), vehicle.getLocation().getY(), vehicle.getLocation().getZ()); - Location exit = getExit(traveller); - - double velocity = vehicle.getVelocity().length(); - - // Stop and teleport - vehicle.setVelocity(new Vector()); - - // Get new velocity - final Vector newVelocity = new Vector(modX, 0.0F, modZ); - newVelocity.multiply(velocity); - - List passengers = vehicle.getPassengers(); - if (!passengers.isEmpty()) { - final Vehicle v = exit.getWorld().spawn(exit, vehicle.getClass()); - final Entity passenger = passengers.get(0); - vehicle.eject(); - vehicle.remove(); - passenger.eject(); - passenger.teleport(exit); - Stargate.server.getScheduler().scheduleSyncDelayedTask(Stargate.stargate, () -> { - v.addPassenger(passenger); - v.setVelocity(newVelocity); - }, 1); - } else { - Vehicle mc = exit.getWorld().spawn(exit, vehicle.getClass()); - if (mc instanceof StorageMinecart) { - StorageMinecart smc = (StorageMinecart)mc; - smc.getInventory().setContents(((StorageMinecart)vehicle).getInventory().getContents()); - } - mc.setVelocity(newVelocity); - vehicle.remove(); - } - } - - public Location getExit(Location traveller) { - Location loc = null; - // Check if the gate has an exit block - if (gate.getExit() != null) { - Blox exit = getBlockAt(gate.getExit()); - int back = (isBackwards()) ? -1 : 1; - loc = exit.modRelativeLoc(0D, 0D, 1D, traveller.getYaw(), traveller.getPitch(), modX * back, 1, modZ * back); - } else { - Stargate.log.log(Level.WARNING, "[Stargate] Missing destination point in .gate file " + gate.getFilename()); - } - - if (loc != null) { - BlockData bd = getWorld().getBlockAt(loc).getBlockData(); - if (bd instanceof Bisected && ((Bisected) bd).getHalf() == Bisected.Half.BOTTOM) { - loc.add(0, 0.5, 0); - } - - loc.setPitch(traveller.getPitch()); - return loc; - } - return traveller; - } - - public boolean isChunkLoaded() { - return getWorld().isChunkLoaded(topLeft.getBlock().getChunk()); - } - - public boolean isVerified() { - verified = true; - if(!Stargate.verifyPortals) { - return true; - } - for (RelativeBlockVector control : gate.getControls()) { - verified = verified && getBlockAt(control).getBlock().getType().equals(gate.getControlBlock()); - } - return verified; - } - - public boolean wasVerified() { - if(!Stargate.verifyPortals) { - return true; - } - return verified; - } - - public boolean checkIntegrity() { - if(!Stargate.verifyPortals) { - return true; - } - return gate.matches(topLeft, modX, modZ); - } - - public ArrayList getDestinations(Player player, String network) { - ArrayList destinations = new ArrayList<>(); - for (String dest : allPortalsNet.get(network.toLowerCase())) { - Portal portal = getByName(dest, network); - if (portal == null) continue; - // Check if dest is a random gate - if (portal.isRandom()) continue; - // Check if dest is always open (Don't show if so) - if (portal.isAlwaysOn() && !portal.isShown()) continue; - // Check if dest is this portal - if (dest.equalsIgnoreCase(getName())) continue; - // Check if dest is a fixed gate not pointing to this gate - if (portal.isFixed() && !portal.getDestinationName().equalsIgnoreCase(getName())) continue; - // Allow random use by non-players (Minecarts) - if (player == null) { - destinations.add(portal.getName()); - continue; - } - // Check if this player can access the dest world - if (!Stargate.canAccessWorld(player, portal.getWorld().getName())) continue; - // Visible to this player. - if (Stargate.canSee(player, portal)) { - destinations.add(portal.getName()); - } - } - return destinations; - } - - public boolean activate(Player player) { - destinations.clear(); - destination = ""; - Stargate.activeList.add(this); - activePlayer = player; - String network = getNetwork(); - destinations = getDestinations(player, network); - if (Stargate.sortLists) { - Collections.sort(destinations); - } - if (Stargate.destMemory && !lastDest.isEmpty() && destinations.contains(lastDest)) { - destination = lastDest; - } - - StargateActivateEvent event = new StargateActivateEvent(this, player, destinations, destination); - Stargate.server.getPluginManager().callEvent(event); - if (event.isCancelled()) { - Stargate.activeList.remove(this); - return false; - } - destination = event.getDestination(); - destinations = event.getDestinations(); - drawSign(); - return true; - } - - public void deactivate() { - StargateDeactivateEvent event = new StargateDeactivateEvent(this); - Stargate.server.getPluginManager().callEvent(event); - if (event.isCancelled()) return; - - Stargate.activeList.remove(this); - if (isFixed()) { - return; - } - destinations.clear(); - destination = ""; - activePlayer = null; - drawSign(); - } - - public boolean isActive() { - return isFixed() || (destinations.size() > 0); - } - - public void cycleDestination(Player player) { - cycleDestination(player, 1); - } - - public void cycleDestination(Player player, int dir) { - boolean activate = false; - if (!isActive() || getActivePlayer() != player) { - // If the event is cancelled, return - if (!activate(player)) { - return; - } - Stargate.debug("cycleDestination", "Network Size: " + allPortalsNet.get(network.toLowerCase()).size()); - Stargate.debug("cycleDestination", "Player has access to: " + destinations.size()); - activate = true; - } - - if (destinations.size() == 0) { - Stargate.sendMessage(player, Stargate.getString("destEmpty")); - return; - } - - if (!Stargate.destMemory || !activate || lastDest.isEmpty()) { - int index = destinations.indexOf(destination); - index += dir; - if (index >= destinations.size()) - index = 0; - else if (index < 0) - index = destinations.size() - 1; - destination = destinations.get(index); - lastDest = destination; - } - openTime = System.currentTimeMillis() / 1000; - drawSign(); - } - - public final void drawSign() { - BlockState state = id.getBlock().getState(); - if (!(state instanceof Sign)) { - Stargate.log.warning("[Stargate] Sign block is not a Sign object"); - Stargate.debug("Portal::drawSign", "Block: " + id.getBlock().getType() + " @ " + id.getBlock().getLocation()); - return; - } - Sign sign = (Sign) state; - Stargate.setLine(sign, 0, "-" + name + "-"); - int max = destinations.size() - 1; - int done = 0; - - if (!isActive()) { - Stargate.setLine(sign, ++done, Stargate.getString("signRightClick")); - Stargate.setLine(sign, ++done, Stargate.getString("signToUse")); - if (!noNetwork) { - Stargate.setLine(sign, ++done, "(" + network + ")"); - } - } else { - // Awesome new logic for Bungee gates - if (isBungee()) { - Stargate.setLine(sign, ++done, Stargate.getString("bungeeSign")); - Stargate.setLine(sign, ++done, ">" + destination + "<"); - Stargate.setLine(sign, ++done, "[" + network + "]"); - } else if (isFixed()) { - if (isRandom()) { - Stargate.setLine(sign, ++done, "> " + Stargate.getString("signRandom") + " <"); - } else { - Stargate.setLine(sign, ++done, ">" + destination + "<"); - } - if (noNetwork) { - Stargate.setLine(sign, ++done, ""); - } else { - Stargate.setLine(sign, ++done, "(" + network + ")"); - } - Portal dest = Portal.getByName(destination, network); - if (dest == null && !isRandom()) { - Stargate.setLine(sign, ++done, Stargate.getString("signDisconnected")); - } else { - Stargate.setLine(sign, ++done, ""); - } - } else { - int index = destinations.indexOf(destination); - if ((index == max) && (max > 1) && (++done <= 3)) { - if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index - 2), network); - boolean green = Stargate.isFree(activePlayer, this, dest); - Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 2)); - } else { - Stargate.setLine(sign, done, destinations.get(index - 2)); - } - } - if ((index > 0) && (++done <= 3)) { - if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index - 1), network); - boolean green = Stargate.isFree(activePlayer, this, dest); - Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index - 1)); - } else { - Stargate.setLine(sign, done, destinations.get(index - 1)); - } - } - if (++done <= 3) { - if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destination, network); - boolean green = Stargate.isFree(activePlayer, this, dest); - Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + ">" + destination + "<"); - } else { - Stargate.setLine(sign, done, " >" + destination + "< "); - } - } - if ((max >= index + 1) && (++done <= 3)) { - if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index + 1), network); - boolean green = Stargate.isFree(activePlayer, this, dest); - Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 1)); - } else { - Stargate.setLine(sign, done, destinations.get(index + 1)); - } - } - if ((max >= index + 2) && (++done <= 3)) { - if (EconomyHandler.useEconomy() && EconomyHandler.freeGatesGreen) { - Portal dest = Portal.getByName(destinations.get(index + 2), network); - boolean green = Stargate.isFree(activePlayer, this, dest); - Stargate.setLine(sign, done, (green ? ChatColor.DARK_GREEN : "") + destinations.get(index + 2)); - } else { - Stargate.setLine(sign, done, destinations.get(index + 2)); - } - } - } - } - - for (done++; done <= 3; done++) { - sign.setLine(done, ""); - } - - sign.update(); - } - - public void unregister(boolean removeAll) { - Stargate.debug("Unregister", "Unregistering gate " + getName()); - close(true); - - for (Blox block : getFrame()) { - lookupBlocks.remove(block); - } - // Include the sign and button - lookupBlocks.remove(id); - if (button != null) { - lookupBlocks.remove(button); - } - - lookupControls.remove(id); - if (button != null) - lookupControls.remove(button); - - for (Blox entrance : getEntrances()) { - lookupEntrances.remove(entrance); - } - - if (removeAll) - allPortals.remove(this); - - if (bungee) { - bungeePortals.remove(getName().toLowerCase()); - } else { - lookupNamesNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - allPortalsNet.get(getNetwork().toLowerCase()).remove(getName().toLowerCase()); - - for (String originName : allPortalsNet.get(getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, getNetwork()); - if (origin == null) continue; - if (!origin.getDestinationName().equalsIgnoreCase(getName())) continue; - if (!origin.isVerified()) continue; - if (origin.isFixed()) origin.drawSign(); - if (origin.isAlwaysOn()) origin.close(true); - } - } - - if (id.getBlock().getBlockData() instanceof WallSign) { - Sign sign = (Sign)id.getBlock().getState(); - sign.setLine(0, getName()); - sign.setLine(1, ""); - sign.setLine(2, ""); - sign.setLine(3, ""); - sign.update(); - } - - saveAllGates(getWorld()); - } - - private Blox getBlockAt(RelativeBlockVector vector) { - return topLeft.modRelative(vector.getRight(), vector.getDepth(), vector.getDistance(), modX, 1, modZ); - } - - private void register() { - fixed = destination.length() > 0 || random || bungee; - - // Bungee gates are stored in their own list - if (isBungee()) { - bungeePortals.put(getName().toLowerCase(), this); - } else { - // Check if network exists in our network list - if (!lookupNamesNet.containsKey(getNetwork().toLowerCase())) { - Stargate.debug("register", "Network " + getNetwork() + " not in lookupNamesNet, adding"); - lookupNamesNet.put(getNetwork().toLowerCase(), new HashMap<>()); - } - lookupNamesNet.get(getNetwork().toLowerCase()).put(getName().toLowerCase(), this); - - // Check if this network exists - if (!allPortalsNet.containsKey(getNetwork().toLowerCase())) { - Stargate.debug("register", "Network " + getNetwork() + " not in allPortalsNet, adding"); - allPortalsNet.put(getNetwork().toLowerCase(), new ArrayList<>()); - } - allPortalsNet.get(getNetwork().toLowerCase()).add(getName().toLowerCase()); - } - - for (Blox block : getFrame()) { - lookupBlocks.put(block, this); - } - // Include the sign and button - lookupBlocks.put(id, this); - if (button != null) { - lookupBlocks.put(button, this); - } - - lookupControls.put(id, this); - if (button != null) - lookupControls.put(button, this); - - for (Blox entrance : getEntrances()) { - lookupEntrances.put(entrance, this); - } - - allPortals.add(this); - } - - public static Portal createPortal(SignChangeEvent event, Player player) { - Blox id = new Blox(event.getBlock()); - Block idParent = id.getParent(); - if (idParent == null) { - return null; - } - - if (Gate.getGatesByControlBlock(idParent).length == 0) return null; - - if (Portal.getByBlock(idParent) != null) { - Stargate.debug("createPortal", "idParent belongs to existing gate"); - return null; - } - - Blox parent = new Blox(player.getWorld(), idParent.getX(), idParent.getY(), idParent.getZ()); - Blox topleft = null; - String name = filterName(event.getLine(0)); - String destName = filterName(event.getLine(1)); - String network = filterName(event.getLine(2)); - String options = filterName(event.getLine(3)).toLowerCase(); - boolean hidden = (options.indexOf('h') != -1); - boolean alwaysOn = (options.indexOf('a') != -1); - boolean priv = (options.indexOf('p') != -1); - boolean free = (options.indexOf('f') != - 1); - boolean backwards = (options.indexOf('b') != -1); - boolean show = (options.indexOf('s') != -1); - boolean noNetwork = (options.indexOf('n') != -1); - boolean random = (options.indexOf('r') != -1); - boolean bungee = (options.indexOf('u') != -1); - - // Check permissions for options. - if (hidden && !Stargate.canOption(player, "hidden")) hidden = false; - if (alwaysOn && !Stargate.canOption(player, "alwayson")) alwaysOn = false; - if (priv && !Stargate.canOption(player, "private")) priv = false; - if (free && !Stargate.canOption(player, "free")) free = false; - if (backwards && !Stargate.canOption(player, "backwards")) backwards = false; - if (show && !Stargate.canOption(player, "show")) show = false; - if (noNetwork && !Stargate.canOption(player, "nonetwork")) noNetwork = false; - if (random && !Stargate.canOption(player, "random")) random = false; - - // Can not create a non-fixed always-on gate. - if (alwaysOn && destName.length() == 0) { - alwaysOn = false; - } - - // Show isn't useful if A is false - if (show && !alwaysOn) { - show = false; - } - - // Random gates are always on and can't be shown - if (random) { - alwaysOn = true; - show = false; - } - - // Bungee gates are always on and don't support Random - if (bungee) { - alwaysOn = true; - random = false; - } - - // Moved the layout check so as to avoid invalid messages when not making a gate - int modX = 0; - int modZ = 0; - float rotX = 0f; - BlockFace buttonfacing = BlockFace.DOWN; - - if (idParent.getX() > id.getBlock().getX()) { - modZ -= 1; - rotX = 90f; - buttonfacing = BlockFace.WEST; - } else if (idParent.getX() < id.getBlock().getX()) { - modZ += 1; - rotX = 270f; - buttonfacing = BlockFace.EAST; - } else if (idParent.getZ() > id.getBlock().getZ()) { - modX += 1; - rotX = 180f; - buttonfacing = BlockFace.NORTH; - } else if (idParent.getZ() < id.getBlock().getZ()) { - modX -= 1; - rotX = 0f; - buttonfacing = BlockFace.SOUTH; - } - - Gate[] possibleGates = Gate.getGatesByControlBlock(idParent); - Gate gate = null; - RelativeBlockVector buttonVector = null; - - for (Gate possibility : possibleGates) { - if ((gate == null) && (buttonVector == null)) { - RelativeBlockVector[] vectors = possibility.getControls(); - RelativeBlockVector otherControl = null; - - for (RelativeBlockVector vector : vectors) { - Blox tl = parent.modRelative(-vector.getRight(), -vector.getDepth(), -vector.getDistance(), modX, 1, modZ); - - if (gate == null) { - if (possibility.matches(tl, modX, modZ, true)) { - gate = possibility; - topleft = tl; - - if (otherControl != null) { - buttonVector = otherControl; - } - } - } else if (otherControl != null) { - buttonVector = vector; - } - - otherControl = vector; - } - } - } - - if ((gate == null) || (buttonVector == null)) { - Stargate.debug("createPortal", "Could not find matching gate layout"); - return null; - } - - // If the player is trying to create a Bungee gate without permissions, drop out here - // Do this after the gate layout check, in the least - if (bungee) { - if (!Stargate.enableBungee) { - Stargate.sendMessage(player, Stargate.getString("bungeeDisabled")); - return null; - } else if (!Stargate.hasPerm(player, "stargate.admin.bungee")) { - Stargate.sendMessage(player, Stargate.getString("bungeeDeny")); - return null; - } else if (destName.isEmpty() || network.isEmpty()) { - Stargate.sendMessage(player, Stargate.getString("bungeeEmpty")); - return null; - } - } - - // Debug - Stargate.debug("createPortal", "h = " + hidden + " a = " + alwaysOn + " p = " + priv + " f = " + free + " b = " + backwards + " s = " + show + " n = " + noNetwork + " r = " + random + " u = " + bungee); - - if (!bungee && (network.length() < 1 || network.length() > 11)) { - network = Stargate.getDefaultNetwork(); - } - - boolean deny = false; - String denyMsg = ""; - - // Check if the player can create gates on this network - if (!bungee && !Stargate.canCreate(player, network)) { - Stargate.debug("createPortal", "Player doesn't have create permissions on network. Trying personal"); - if (Stargate.canCreatePersonal(player)) { - network = player.getName(); - if (network.length() > 11) network = network.substring(0, 11); - Stargate.debug("createPortal", "Creating personal portal"); - Stargate.sendMessage(player, Stargate.getString("createPersonal")); - } else { - Stargate.debug("createPortal", "Player does not have access to network"); - deny = true; - denyMsg = Stargate.getString("createNetDeny"); - //return null; - } - } - - // Check if the player can create this gate layout - String gateName = gate.getFilename(); - gateName = gateName.substring(0, gateName.indexOf('.')); - if (!deny && !Stargate.canCreateGate(player, gateName)) { - Stargate.debug("createPortal", "Player does not have access to gate layout"); - deny = true; - denyMsg = Stargate.getString("createGateDeny"); - } - - // Check if the user can create gates to this world. - if (!bungee && !deny && destName.length() > 0) { - Portal p = Portal.getByName(destName, network); - if (p != null) { - String world = p.getWorld().getName(); - if (!Stargate.canAccessWorld(player, world)) { - Stargate.debug("canCreate", "Player does not have access to destination world"); - deny = true; - denyMsg = Stargate.getString("createWorldDeny"); - } - } - } - - // Bleh, gotta check to make sure none of this gate belongs to another gate. Boo slow. - for (RelativeBlockVector v : gate.getBorder()) { - Blox b = topleft.modRelative(v.getRight(), v.getDepth(), v.getDistance(), modX, 1, modZ); - if (Portal.getByBlock(b.getBlock()) != null) { - Stargate.debug("createPortal", "Gate conflicts with existing gate"); - Stargate.sendMessage(player, Stargate.getString("createConflict")); - return null; - } - } - - Blox button = null; - Portal portal = null; - portal = new Portal(topleft, modX, modZ, rotX, id, button, destName, name, false, network, gate, player.getUniqueId(), player.getName(), hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); - - int cost = Stargate.getCreateCost(player, gate); - - // Call StargateCreateEvent - StargateCreateEvent cEvent = new StargateCreateEvent(player, portal, event.getLines(), deny, denyMsg, cost); - Stargate.server.getPluginManager().callEvent(cEvent); - if (cEvent.isCancelled()) { - return null; - } - if (cEvent.getDeny()) { - Stargate.sendMessage(player, cEvent.getDenyReason()); - return null; - } - - cost = cEvent.getCost(); - - // Name & Network can be changed in the event, so do these checks here. - if (portal.getName().length() < 1 || portal.getName().length() > 11) { - Stargate.debug("createPortal", "Name length error"); - Stargate.sendMessage(player, Stargate.getString("createNameLength")); - return null; - } - - // Don't do network checks for bungee gates - if (portal.isBungee()) { - if (bungeePortals.get(portal.getName().toLowerCase()) != null) { - Stargate.debug("createPortal::Bungee", "Gate Exists"); - Stargate.sendMessage(player, Stargate.getString("createExists")); - return null; - } - } else { - if (getByName(portal.getName(), portal.getNetwork()) != null) { - Stargate.debug("createPortal", "Name Error"); - Stargate.sendMessage(player, Stargate.getString("createExists")); - return null; - } - - // Check if there are too many gates in this network - ArrayList netList = allPortalsNet.get(portal.getNetwork().toLowerCase()); - if (Stargate.maxGates > 0 && netList != null && netList.size() >= Stargate.maxGates) { - Stargate.sendMessage(player, Stargate.getString("createFull")); - return null; - } - } - - if (cost > 0) { - if (!Stargate.chargePlayer(player, cost)) { - String inFundMsg = Stargate.getString("ecoInFunds"); - inFundMsg = Stargate.replaceVars(inFundMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), name}); - Stargate.sendMessage(player, inFundMsg); - Stargate.debug("createPortal", "Insufficient Funds"); - return null; - } - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), name}); - Stargate.sendMessage(player, deductMsg, false); - } - - // No button on an always-open gate. - if (!alwaysOn) { - button = topleft.modRelative(buttonVector.getRight(), buttonVector.getDepth(), buttonVector.getDistance() + 1, modX, 1, modZ); - Directional buttondata = (Directional) Bukkit.createBlockData(gate.getButton()); - buttondata.setFacing(buttonfacing); - button.getBlock().setBlockData(buttondata); - portal.setButton(button); - } - - portal.register(); - portal.drawSign(); - // Open always on gate - if (portal.isRandom() || portal.isBungee()) { - portal.open(true); - } else if (portal.isAlwaysOn()) { - Portal dest = Portal.getByName(destName, portal.getNetwork()); - if (dest != null) { - portal.open(true); - dest.drawSign(); - } - // Set the inside of the gate to its closed material - } else { - for (Blox inside : portal.getEntrances()) { - inside.setType(portal.getGate().getPortalBlockClosed()); - } - } - - // Don't do network stuff for bungee gates - if (!portal.isBungee()) { - // Open any always on gate pointing at this gate - for (String originName : allPortalsNet.get(portal.getNetwork().toLowerCase())) { - Portal origin = Portal.getByName(originName, portal.getNetwork()); - if (origin == null) continue; - if (!origin.getDestinationName().equalsIgnoreCase(portal.getName())) continue; - if (!origin.isVerified()) continue; - if (origin.isFixed()) origin.drawSign(); - if (origin.isAlwaysOn()) origin.open(true); - } - } - - saveAllGates(portal.getWorld()); - - return portal; - } - - public static Portal getByName(String name, String network) { - if (!lookupNamesNet.containsKey(network.toLowerCase())) return null; - return lookupNamesNet.get(network.toLowerCase()).get(name.toLowerCase()); - - } - - public static Portal getByEntrance(Location location) { - return lookupEntrances.get(new Blox(location)); - } - - public static Portal getByEntrance(Block block) { - return lookupEntrances.get(new Blox(block)); - } - - public static Portal getByAdjacentEntrance(Location loc) { - int centerX = loc.getBlockX(); - int centerY = loc.getBlockY(); - int centerZ = loc.getBlockZ(); - World world = loc.getWorld(); - Portal portal = lookupEntrances.get(new Blox(world, centerX, centerY, centerZ)); - if(portal != null) { - return portal; - } - portal = lookupEntrances.get(new Blox(world, centerX + 1, centerY, centerZ)); - if(portal != null) { - return portal; - } - portal = lookupEntrances.get(new Blox(world, centerX - 1, centerY, centerZ)); - if(portal != null) { - return portal; - } - portal = lookupEntrances.get(new Blox(world, centerX, centerY, centerZ + 1)); - if(portal != null) { - return portal; - } - portal = lookupEntrances.get(new Blox(world, centerX, centerY, centerZ - 1)); - if(portal != null) { - return portal; - } - return null; - } - - public static Portal getByControl(Block block) { - return lookupControls.get(new Blox(block)); - } - - public static Portal getByBlock(Block block) { - return lookupBlocks.get(new Blox(block)); - } - - public static Portal getBungeeGate(String name) { - return bungeePortals.get(name.toLowerCase()); - } - - public static void saveAllGates(World world) { - Stargate.managedWorlds.add(world.getName()); - String loc = Stargate.getSaveLocation() + "/" + world.getName() + ".db"; - - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(loc, false)); - - for (Portal portal : allPortals) { - String wName = portal.world.getName(); - if (!wName.equalsIgnoreCase(world.getName())) continue; - StringBuilder builder = new StringBuilder(); - Blox sign = portal.id; - Blox button = portal.button; - - builder.append(portal.name); - builder.append(':'); - builder.append(sign.toString()); - builder.append(':'); - builder.append((button != null) ? button.toString() : ""); - builder.append(':'); - builder.append(portal.modX); - builder.append(':'); - builder.append(portal.modZ); - builder.append(':'); - builder.append(portal.rotX); - builder.append(':'); - builder.append(portal.topLeft.toString()); - builder.append(':'); - builder.append(portal.gate.getFilename()); - builder.append(':'); - builder.append(portal.isFixed() ? portal.getDestinationName() : ""); - builder.append(':'); - builder.append(portal.getNetwork()); - builder.append(':'); - UUID owner = portal.getOwnerUUID(); - if(owner != null) { - builder.append(portal.getOwnerUUID().toString()); - } else { - builder.append(portal.getOwnerName()); - } - builder.append(':'); - builder.append(portal.isHidden()); - builder.append(':'); - builder.append(portal.isAlwaysOn()); - builder.append(':'); - builder.append(portal.isPrivate()); - builder.append(':'); - builder.append(portal.world.getName()); - builder.append(':'); - builder.append(portal.isFree()); - builder.append(':'); - builder.append(portal.isBackwards()); - builder.append(':'); - builder.append(portal.isShown()); - builder.append(':'); - builder.append(portal.isNoNetwork()); - builder.append(':'); - builder.append(portal.isRandom()); - builder.append(':'); - builder.append(portal.isBungee()); - - bw.append(builder.toString()); - bw.newLine(); - } - - bw.close(); - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while writing stargates to " + loc + ": " + e); - } - } - - public static void clearGates() { - lookupBlocks.clear(); - lookupNamesNet.clear(); - lookupEntrances.clear(); - lookupControls.clear(); - allPortals.clear(); - allPortalsNet.clear(); - } - - public static boolean loadAllGates(World world) { - String location = Stargate.getSaveLocation(); - - File db = new File(location, world.getName() + ".db"); - - if (db.exists()) { - int l = 0; - int portalCount = 0; - try { - Scanner scanner = new Scanner(db); - while (scanner.hasNextLine()) { - l++; - String line = scanner.nextLine().trim(); - if (line.startsWith("#") || line.isEmpty()) { - continue; - } - String[] split = line.split(":"); - if (split.length < 8) { - Stargate.log.info("[Stargate] Invalid line - " + l); - continue; - } - String name = split[0]; - Blox sign = new Blox(world, split[1]); - Blox button = (split[2].length() > 0) ? new Blox(world, split[2]) : null; - int modX = Integer.parseInt(split[3]); - int modZ = Integer.parseInt(split[4]); - float rotX = Float.parseFloat(split[5]); - Blox topLeft = new Blox(world, split[6]); - Gate gate = Gate.getGateByName(split[7]); - if (gate == null) { - Stargate.log.info("[Stargate] Gate layout on line " + l + " does not exist [" + split[7] + "]"); - continue; - } - - String dest = (split.length > 8) ? split[8] : ""; - String network = (split.length > 9) ? split[9] : Stargate.getDefaultNetwork(); - if (network.isEmpty()) network = Stargate.getDefaultNetwork(); - String ownerString = (split.length > 10) ? split[10] : ""; - boolean hidden = (split.length > 11) && split[11].equalsIgnoreCase("true"); - boolean alwaysOn = (split.length > 12) && split[12].equalsIgnoreCase("true"); - boolean priv = (split.length > 13) && split[13].equalsIgnoreCase("true"); - boolean free = (split.length > 15) && split[15].equalsIgnoreCase("true"); - boolean backwards = (split.length > 16) && split[16].equalsIgnoreCase("true"); - boolean show = (split.length > 17) && split[17].equalsIgnoreCase("true"); - boolean noNetwork = (split.length > 18) && split[18].equalsIgnoreCase("true"); - boolean random = (split.length > 19) && split[19].equalsIgnoreCase("true"); - boolean bungee = (split.length > 20) && split[20].equalsIgnoreCase("true"); - - // Attempt to get owner as UUID - UUID ownerUUID = null; - String ownerName; - if(ownerString.length() > 16) { - try { - ownerUUID = UUID.fromString(ownerString); - OfflinePlayer offlineOwner = Bukkit.getServer().getOfflinePlayer(ownerUUID); - ownerName = offlineOwner.getName(); - } catch (IllegalArgumentException ex) { - // neither name nor UUID, so keep it as-is - ownerName = ownerString; - Stargate.debug("loadAllGates", "Invalid Stargate owner string: " + ownerString); - } - } else { - ownerName = ownerString; - } - - Portal portal = new Portal(topLeft, modX, modZ, rotX, sign, button, dest, name, false, network, gate, ownerUUID, ownerName, hidden, alwaysOn, priv, free, backwards, show, noNetwork, random, bungee); - portal.register(); - portal.close(true); - } - scanner.close(); - - // Open any always-on gates. Do this here as it should be more efficient than in the loop. - int OpenCount = 0; - for (Iterator iter = allPortals.iterator(); iter.hasNext(); ) { - Portal portal = iter.next(); - if (portal == null) continue; - - // Verify portal integrity/register portal - if (!portal.wasVerified()) { - if (!portal.isVerified() || !portal.checkIntegrity()) { - // DEBUG - for (RelativeBlockVector control : portal.getGate().getControls()) { - if (!portal.getBlockAt(control).getBlock().getType().equals(portal.getGate().getControlBlock())) { - Stargate.debug("loadAllGates", "Control Block Type == " + portal.getBlockAt(control).getBlock().getType().name()); - } - } - portal.unregister(false); - iter.remove(); - Stargate.log.info("[Stargate] Destroying stargate at " + portal.toString()); - continue; - } - } - portalCount++; - - if (portal.isFixed() && (Stargate.enableBungee && portal.isBungee() - || portal.getDestination() != null && portal.isAlwaysOn())) { - portal.open(true); - OpenCount++; - } - } - Stargate.log.info("[Stargate] {" + world.getName() + "} Loaded " + portalCount + " stargates with " + OpenCount + " set as always-on"); - return true; - } catch (Exception e) { - Stargate.log.log(Level.SEVERE, "Exception while reading stargates from " + db.getName() + ": " + l); - e.printStackTrace(); - } - } else { - Stargate.log.info("[Stargate] {" + world.getName() + "} No stargates for world "); - } - return false; - } - - public static void closeAllGates() { - Stargate.log.info("Closing all stargates."); - for (Portal p : allPortals) { - if (p == null) continue; - p.close(true); - } - } - - public static String filterName(String input) { - if (input == null) { - return ""; - } - return input.replaceAll("[\\|:#]", "").trim(); - } - - @Override - public String toString() { - return String.format("Portal [id=%s, network=%s name=%s, type=%s]", id, network, name, gate.getFilename()); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((network == null) ? 0 : network.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Portal other = (Portal) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equalsIgnoreCase(other.name)) - return false; - if (network == null) { - if (other.network != null) - return false; - } else if (!network.equalsIgnoreCase(other.network)) - return false; - return true; - } -} diff --git a/src/net/TheDgtl/Stargate/Stargate.java b/src/net/TheDgtl/Stargate/Stargate.java deleted file mode 100644 index 2b995c5..0000000 --- a/src/net/TheDgtl/Stargate/Stargate.java +++ /dev/null @@ -1,1294 +0,0 @@ -package net.TheDgtl.Stargate; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.TheDgtl.Stargate.event.StargateAccessEvent; -import net.TheDgtl.Stargate.event.StargateDestroyEvent; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.Tag; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.EndGateway; -import org.bukkit.block.Sign; -import org.bukkit.block.data.Orientable; -import org.bukkit.block.data.type.WallSign; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.Event.Result; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.event.server.PluginEnableEvent; -import org.bukkit.event.vehicle.VehicleMoveEvent; -import org.bukkit.event.world.WorldLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011 Shaun (sturmeh) - * Copyright (C) 2011 Dinnerbone - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -@SuppressWarnings("unused") -public class Stargate extends JavaPlugin { - public static Logger log; - private FileConfiguration newConfig; - private PluginManager pm; - public static Server server; - public static Stargate stargate; - private static LangLoader lang; - - private static String portalFolder; - private static String gateFolder; - private static String langFolder; - private static String defNetwork = "central"; - private static boolean destroyExplosion = false; - public static int maxGates = 0; - private static String langName = "en"; - private static final int activeTime = 10; - private static final int openTime = 10; - public static boolean destMemory = false; - public static boolean handleVehicles = true; - public static boolean sortLists = false; - public static boolean protectEntrance = false; - public static boolean enableBungee = true; - public static boolean verifyPortals = true; - public static ChatColor signColor; - - // Temp workaround for snowmen, don't check gate entrance - public static boolean ignoreEntrance = false; - - // Used for debug - public static boolean debug = false; - public static boolean permDebug = false; - - public static ConcurrentLinkedQueue openList = new ConcurrentLinkedQueue<>(); - public static ConcurrentLinkedQueue activeList = new ConcurrentLinkedQueue<>(); - - // Used for populating gate open/closed material. - public static Queue blockPopulatorQueue = new LinkedList<>(); - - // HashMap of player names for Bungee support - public static Map bungeeQueue = new HashMap<>(); - - // World names that contain stargates - public static HashSet managedWorlds = new HashSet<>(); - - public void onDisable() { - Portal.closeAllGates(); - Portal.clearGates(); - managedWorlds.clear(); - getServer().getScheduler().cancelTasks(this); - } - - public void onEnable() { - PluginDescriptionFile pdfFile = this.getDescription(); - pm = getServer().getPluginManager(); - newConfig = this.getConfig(); - log = Logger.getLogger("Minecraft"); - Stargate.server = getServer(); - Stargate.stargate = this; - - // Set portalFile and gateFolder to the plugin folder as defaults. - portalFolder = getDataFolder().getPath().replaceAll("\\\\", "/") + "/portals/"; - gateFolder = getDataFolder().getPath().replaceAll("\\\\", "/") + "/gates/"; - langFolder = getDataFolder().getPath().replaceAll("\\\\", "/") + "/lang/"; - - log.info(pdfFile.getName() + " v." + pdfFile.getVersion() + " is enabled."); - - // Register events before loading gates to stop weird things happening. - pm.registerEvents(new pListener(), this); - pm.registerEvents(new bListener(), this); - - pm.registerEvents(new vListener(), this); - pm.registerEvents(new eListener(), this); - pm.registerEvents(new wListener(), this); - pm.registerEvents(new sListener(), this); - - this.loadConfig(); - - // Enable the required channels for Bungee support - if (enableBungee) { - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new pmListener()); - } - - // It is important to load languages here, as they are used during reloadGates() - lang = new LangLoader(langFolder, Stargate.langName); - - this.migrate(); - this.loadGates(); - this.loadAllPortals(); - - // Check to see if Economy is loaded yet. - if (EconomyHandler.setupEconomy(pm)) { - if (EconomyHandler.economy != null) - log.info("[Stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); - } - - getServer().getScheduler().scheduleSyncRepeatingTask(this, new SGThread(), 0L, 100L); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new BlockPopulatorThread(), 0L, 1L); - } - - public void loadConfig() { - reloadConfig(); - newConfig = this.getConfig(); - // Copy default values if required - newConfig.options().copyDefaults(true); - - // Load values into variables - portalFolder = newConfig.getString("portal-folder"); - gateFolder = newConfig.getString("gate-folder"); - defNetwork = newConfig.getString("default-gate-network").trim(); - destroyExplosion = newConfig.getBoolean("destroyexplosion"); - maxGates = newConfig.getInt("maxgates"); - langName = newConfig.getString("lang"); - destMemory = newConfig.getBoolean("destMemory"); - ignoreEntrance = newConfig.getBoolean("ignoreEntrance"); - handleVehicles = newConfig.getBoolean("handleVehicles"); - sortLists = newConfig.getBoolean("sortLists"); - protectEntrance = newConfig.getBoolean("protectEntrance"); - enableBungee = newConfig.getBoolean("enableBungee"); - verifyPortals = newConfig.getBoolean("verifyPortals"); - // Sign color - String sc = newConfig.getString("signColor"); - try { - signColor = ChatColor.valueOf(sc.toUpperCase()); - } catch (Exception ignore) { - log.warning("[Stargate] You have specified an invalid color in your config.yml. Defaulting to BLACK"); - signColor = ChatColor.BLACK; - } - // Debug - debug = newConfig.getBoolean("debug"); - permDebug = newConfig.getBoolean("permdebug"); - // Economy - EconomyHandler.economyEnabled = newConfig.getBoolean("useeconomy"); - EconomyHandler.createCost = newConfig.getInt("createcost"); - EconomyHandler.destroyCost = newConfig.getInt("destroycost"); - EconomyHandler.useCost = newConfig.getInt("usecost"); - EconomyHandler.toOwner = newConfig.getBoolean("toowner"); - EconomyHandler.chargeFreeDestination = newConfig.getBoolean("chargefreedestination"); - EconomyHandler.freeGatesGreen = newConfig.getBoolean("freegatesgreen"); - - this.saveConfig(); - } - - public void closeAllPortals() { - // Close all gates prior to reloading - for (Portal p : openList) { - p.close(true); - } - } - - public void loadGates() { - Gate.loadGates(gateFolder); - log.info("[Stargate] Loaded " + Gate.getGateCount() + " gate layouts"); - } - - public void loadAllPortals() { - for (World world : getServer().getWorlds()) { - if(!managedWorlds.contains(world.getName())) { - Portal.loadAllGates(world); - managedWorlds.add(world.getName()); - } - } - } - - private void migrate() { - // Only migrate if new file doesn't exist. - File newPortalDir = new File(portalFolder); - if (!newPortalDir.exists()) { - newPortalDir.mkdirs(); - } - File newFile = new File(portalFolder, getServer().getWorlds().get(0).getName() + ".db"); - if (!newFile.exists()) { - newFile.getParentFile().mkdirs(); - } - } - - public static void debug(String rout, String msg) { - if (Stargate.debug) { - log.info("[Stargate::" + rout + "] " + msg); - } else { - log.log(Level.FINEST, "[Stargate::" + rout + "] " + msg); - } - } - - public static void sendMessage(CommandSender player, String message) { - sendMessage(player, message, true); - } - - public static void sendMessage(CommandSender player, String message, boolean error) { - if (message.isEmpty()) return; - message = message.replaceAll("(&([a-f0-9]))", "\u00A7$2"); - if (error) - player.sendMessage(ChatColor.RED + Stargate.getString("prefix") + ChatColor.WHITE + message); - else - player.sendMessage(ChatColor.GREEN + Stargate.getString("prefix") + ChatColor.WHITE + message); - } - - public static void setLine(Sign sign, int index, String text) { - sign.setLine(index, Stargate.signColor + text); - } - - public static String getSaveLocation() { - return portalFolder; - } - - public static String getGateFolder() { - return gateFolder; - } - - public static String getDefaultNetwork() { - return defNetwork; - } - - public static String getString(String name) { - return lang.getString(name); - } - - public static void openPortal(Player player, Portal portal) { - Portal destination = portal.getDestination(); - - // Always-open gate -- Do nothing - if (portal.isAlwaysOn()) { - return; - } - - // Random gate -- Do nothing - if (portal.isRandom()) - return; - - // Invalid destination - if ((destination == null) || (destination == portal)) { - Stargate.sendMessage(player, Stargate.getString("invalidMsg")); - return; - } - - // Gate is already open - if (portal.isOpen()) { - // Close if this player opened the gate - if (portal.getActivePlayer() == player) { - portal.close(false); - } - return; - } - - // Gate that someone else is using -- Deny access - if ((!portal.isFixed()) && portal.isActive() && (portal.getActivePlayer() != player)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - // Check if the player can use the private gate - if (portal.isPrivate() && !Stargate.canPrivate(player, portal)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - // Destination blocked - if ((destination.isOpen()) && (!destination.isAlwaysOn())) { - Stargate.sendMessage(player, Stargate.getString("blockMsg")); - return; - } - - // Open gate - portal.open(player, false); - } - - /* - * Check whether the player has the given permissions. - */ - public static boolean hasPerm(Player player, String perm) { - if (permDebug) - Stargate.debug("hasPerm::SuperPerm(" + player.getName() + ")", perm + " => " + player.hasPermission(perm)); - return player.hasPermission(perm); - } - - /* - * Check a deep permission, this will check to see if the permissions is defined for this use - * If using Permissions it will return the same as hasPerm - * If using SuperPerms will return true if the node isn't defined - * Or the value of the node if it is - */ - public static boolean hasPermDeep(Player player, String perm) { - if (!player.isPermissionSet(perm)) { - if (permDebug) - Stargate.debug("hasPermDeep::SuperPerm", perm + " => true"); - return true; - } - if (permDebug) - Stargate.debug("hasPermDeep::SuperPerms", perm + " => " + player.hasPermission(perm)); - return player.hasPermission(perm); - } - - /* - * Check whether player can teleport to dest world - */ - public static boolean canAccessWorld(Player player, String world) { - // Can use all Stargate player features or access all worlds - if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.world")) { - // Do a deep check to see if the player lacks this specific world node - return hasPermDeep(player, "stargate.world." + world); - } - // Can access dest world - return hasPerm(player, "stargate.world." + world); - } - - /* - * Check whether player can use network - */ - public static boolean canAccessNetwork(Player player, String network) { - // Can user all Stargate player features, or access all networks - if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.network")) { - // Do a deep check to see if the player lacks this specific network node - return hasPermDeep(player, "stargate.network." + network); - } - // Can access this network - if (hasPerm(player, "stargate.network." + network)) return true; - // Is able to create personal gates (Assumption is made they can also access them) - String playerName = player.getName(); - if (playerName.length() > 11) playerName = playerName.substring(0, 11); - return network.equals(playerName) && hasPerm(player, "stargate.create.personal"); - } - - /* - * Check whether the player can access this server - */ - public static boolean canAccessServer(Player player, String server) { - // Can user all Stargate player features, or access all servers - if (hasPerm(player, "stargate.use") || hasPerm(player, "stargate.servers")) { - // Do a deep check to see if the player lacks this specific server node - return hasPermDeep(player, "stargate.server." + server); - } - // Can access this server - return hasPerm(player, "stargate.server." + server); - } - - /* - * Call the StargateAccessPortal event, used for other plugins to bypass Permissions checks - */ - public static boolean canAccessPortal(Player player, Portal portal, boolean deny) { - StargateAccessEvent event = new StargateAccessEvent(player, portal, deny); - Stargate.server.getPluginManager().callEvent(event); - return !event.getDeny(); - } - - /* - * Return true if the portal is free for the player - */ - public static boolean isFree(Player player, Portal src, Portal dest) { - // This gate is free - if (src.isFree()) return true; - // Player gets free use - if (hasPerm(player, "stargate.free") || Stargate.hasPerm(player, "stargate.free.use")) return true; - // Don't charge for free destination gates - return dest != null && !EconomyHandler.chargeFreeDestination && dest.isFree(); - } - - /* - * Check whether the player can see this gate (Hidden property check) - */ - public static boolean canSee(Player player, Portal portal) { - // The gate is not hidden - if (!portal.isHidden()) return true; - // The player is an admin with the ability to see hidden gates - if (hasPerm(player, "stargate.admin") || hasPerm(player, "stargate.admin.hidden")) return true; - // The player is the owner of the gate - return portal.isOwner(player); - } - - /* - * Check if the player can use this private gate - */ - public static boolean canPrivate(Player player, Portal portal) { - // Check if the player is the owner of the gate - if (portal.isOwner(player)) return true; - // The player is an admin with the ability to use private gates - return hasPerm(player, "stargate.admin") || hasPerm(player, "stargate.admin.private"); - } - - /* - * Check if the player has access to {option} - */ - public static boolean canOption(Player player, String option) { - // Check if the player can use all options - if (hasPerm(player, "stargate.option")) return true; - // Check if they can use this specific option - return hasPerm(player, "stargate.option." + option); - } - - /* - * Check if the player can create gates on {network} - */ - public static boolean canCreate(Player player, String network) { - // Check for general create - if (hasPerm(player, "stargate.create")) return true; - // Check for all network create permission - if (hasPerm(player, "stargate.create.network")) { - // Do a deep check to see if the player lacks this specific network node - return hasPermDeep(player, "stargate.create.network." + network); - } - // Check for this specific network - return hasPerm(player, "stargate.create.network." + network); - - } - - /* - * Check if the player can create a personal gate - */ - public static boolean canCreatePersonal(Player player) { - // Check for general create - if (hasPerm(player, "stargate.create")) return true; - // Check for personal - return hasPerm(player, "stargate.create.personal"); - } - - /* - * Check if the player can create this gate layout - */ - public static boolean canCreateGate(Player player, String gate) { - // Check for general create - if (hasPerm(player, "stargate.create")) return true; - // Check for all gate create permissions - if (hasPerm(player, "stargate.create.gate")) { - // Do a deep check to see if the player lacks this specific gate node - return hasPermDeep(player, "stargate.create.gate." + gate); - } - // Check for this specific gate - return hasPerm(player, "stargate.create.gate." + gate); - } - - /* - * Check if the player can destroy this gate - */ - public static boolean canDestroy(Player player, Portal portal) { - String network = portal.getNetwork(); - // Check for general destroy - if (hasPerm(player, "stargate.destroy")) return true; - // Check for all network destroy permission - if (hasPerm(player, "stargate.destroy.network")) { - // Do a deep check to see if the player lacks permission for this network node - return hasPermDeep(player, "stargate.destroy.network." + network); - } - // Check for this specific network - if (hasPerm(player, "stargate.destroy.network." + network)) return true; - // Check for personal gate - return portal.isOwner(player) && hasPerm(player, "stargate.destroy.personal"); - } - - /* - * Charge player for {action} if required, true on success, false if can't afford - */ - public static boolean chargePlayer(Player player, String target, int cost) { - // If cost is 0 - if (cost == 0) return true; - // Economy is disabled - if (!EconomyHandler.useEconomy()) return true; - // Charge player - return EconomyHandler.chargePlayer(player, target, cost); - } - - /* - * Charge player for {action} if required, true on success, false if can't afford - */ - public static boolean chargePlayer(Player player, UUID target, int cost) { - // If cost is 0 - if (cost == 0) return true; - // Economy is disabled - if (!EconomyHandler.useEconomy()) return true; - // Charge player - return EconomyHandler.chargePlayer(player, target, cost); - } - - /* - * Charge player for {action} if required, true on success, false if can't afford - */ - public static boolean chargePlayer(Player player, int cost) { - // If cost is 0 - if (cost == 0) return true; - // Economy is disabled - if (!EconomyHandler.useEconomy()) return true; - // Charge player - return EconomyHandler.chargePlayer(player, cost); - } - - /* - * Determine the cost of a gate - */ - public static int getUseCost(Player player, Portal src, Portal dest) { - // Not using Economy - if (!EconomyHandler.useEconomy()) return 0; - // Portal is free - if (src.isFree()) return 0; - // Not charging for free destinations - if (dest != null && !EconomyHandler.chargeFreeDestination && dest.isFree()) return 0; - // Cost is 0 if the player owns this gate and funds go to the owner - if (src.getGate().getToOwner() && src.isOwner(player)) return 0; - // Player gets free gate use - if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.use")) return 0; - - return src.getGate().getUseCost(); - } - - /* - * Determine the cost to create the gate - */ - public static int getCreateCost(Player player, Gate gate) { - // Not using Economy - if (!EconomyHandler.useEconomy()) return 0; - // Player gets free gate destruction - if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.create")) return 0; - - return gate.getCreateCost(); - } - - /* - * Determine the cost to destroy the gate - */ - public static int getDestroyCost(Player player, Gate gate) { - // Not using Economy - if (!EconomyHandler.useEconomy()) return 0; - // Player gets free gate destruction - if (hasPerm(player, "stargate.free") || hasPerm(player, "stargate.free.destroy")) return 0; - - return gate.getDestroyCost(); - } - - /* - * Check if a plugin is loaded/enabled already. Returns the plugin if so, null otherwise - */ - private Plugin checkPlugin(String p) { - Plugin plugin = pm.getPlugin(p); - return checkPlugin(plugin); - } - - private Plugin checkPlugin(Plugin plugin) { - if (plugin != null && plugin.isEnabled()) { - log.info("[Stargate] Found " + plugin.getDescription().getName() + " (v" + plugin.getDescription().getVersion() + ")"); - return plugin; - } - return null; - } - - /* - * Parse a given text string and replace the variables - */ - public static String replaceVars(String format, String[] search, String[] replace) { - if (search.length != replace.length) return ""; - for (int i = 0; i < search.length; i++) { - format = format.replace(search[i], replace[i]); - } - return format; - } - - private class vListener implements Listener { - @EventHandler - public void onVehicleMove(VehicleMoveEvent event) { - if (!handleVehicles) return; - List passengers = event.getVehicle().getPassengers(); - Vehicle vehicle = event.getVehicle(); - - Portal portal = Portal.getByEntrance(event.getTo()); - if (portal == null || !portal.isOpen()) return; - - // We don't support vehicles in Bungee portals - if (portal.isBungee()) return; - - if (!passengers.isEmpty() && passengers.get(0) instanceof Player) { - /* - Player player = (Player) passengers.get(0); - if (!portal.isOpenFor(player)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - Portal dest = portal.getDestination(player); - if (dest == null) return; - boolean deny = false; - // Check if player has access to this network - if (!canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - // Check if player has access to destination world - if (!canAccessWorld(player, dest.getWorld().getName())) { - deny = true; - } - - if (!canAccessPortal(player, portal, deny)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - portal.close(false); - return; - } - - int cost = Stargate.getUseCost(player, portal, dest); - if (cost > 0) { - boolean success; - if(portal.getGate().getToOwner()) { - if(portal.getOwnerUUID() == null) { - success = Stargate.chargePlayer(player, portal.getOwnerUUID(), cost); - } else { - success = Stargate.chargePlayer(player, portal.getOwnerName(), cost); - } - } else { - success = Stargate.chargePlayer(player, cost); - } - if(!success) { - // Insufficient Funds - Stargate.sendMessage(player, Stargate.getString("inFunds")); - portal.close(false); - return; - } - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - sendMessage(player, deductMsg, false); - if (portal.getGate().getToOwner()) { - Player p; - if(portal.getOwnerUUID() != null) { - p = server.getPlayer(portal.getOwnerUUID()); - } else { - p = server.getPlayer(portal.getOwnerName()); - } - if (p != null) { - String obtainedMsg = Stargate.getString("ecoObtain"); - obtainedMsg = Stargate.replaceVars(obtainedMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - Stargate.sendMessage(p, obtainedMsg, false); - } - } - } - - Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false); - dest.teleport(vehicle); - portal.close(false); - */ - } else { - Portal dest = portal.getDestination(); - if (dest == null) return; - dest.teleport(vehicle); - } - } - } - - private class pListener implements Listener { - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - if (!enableBungee) return; - - Player player = event.getPlayer(); - String destination = bungeeQueue.remove(player.getName().toLowerCase()); - if (destination == null) return; - - Portal portal = Portal.getBungeeGate(destination); - if (portal == null) { - Stargate.debug("PlayerJoin", "Error fetching destination portal: " + destination); - return; - } - portal.teleport(player, portal, null); - } - - @EventHandler - public void onPlayerTeleport(PlayerTeleportEvent event) { - // cancel portal and endgateway teleportation if it's from a Stargate entrance - PlayerTeleportEvent.TeleportCause cause = event.getCause(); - if(!event.isCancelled() - && (cause == PlayerTeleportEvent.TeleportCause.NETHER_PORTAL - || cause == PlayerTeleportEvent.TeleportCause.END_GATEWAY && World.Environment.THE_END == event.getFrom().getWorld().getEnvironment()) - && Portal.getByAdjacentEntrance(event.getFrom()) != null) { - event.setCancelled(true); - } - } - - @EventHandler - public void onPlayerMove(PlayerMoveEvent event) { - if (event.isCancelled()) return; - - // Check to see if the player actually moved - if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockY() == event.getTo().getBlockY() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) { - return; - } - - Player player = event.getPlayer(); - Portal portal = Portal.getByEntrance(event.getTo()); - // No portal or not open - if (portal == null || !portal.isOpen()) return; - - // Not open for this player - if (!portal.isOpenFor(player)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - portal.teleport(player, portal, event); - return; - } - - Portal destination = portal.getDestination(player); - if (!portal.isBungee() && destination == null) return; - - boolean deny = false; - // Check if player has access to this server for Bungee gates - if (portal.isBungee()) { - if (!canAccessServer(player, portal.getNetwork())) { - deny = true; - } - } else { - // Check if player has access to this network - if (!canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - // Check if player has access to destination world - if (!canAccessWorld(player, destination.getWorld().getName())) { - deny = true; - } - } - - if (!canAccessPortal(player, portal, deny)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - portal.teleport(player, portal, event); - portal.close(false); - return; - } - - int cost = Stargate.getUseCost(player, portal, destination); - if (cost > 0) { - boolean success; - if(portal.getGate().getToOwner()) { - if(portal.getOwnerUUID() == null) { - success = Stargate.chargePlayer(player, portal.getOwnerUUID(), cost); - } else { - success = Stargate.chargePlayer(player, portal.getOwnerName(), cost); - } - } else { - success = Stargate.chargePlayer(player, cost); - } - if(!success) { - // Insufficient Funds - Stargate.sendMessage(player, Stargate.getString("inFunds")); - portal.close(false); - return; - } - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - sendMessage(player, deductMsg, false); - if (portal.getGate().getToOwner() && portal.getOwnerUUID() != null) { - Player p; - if(portal.getOwnerUUID() != null) { - p = server.getPlayer(portal.getOwnerUUID()); - } else { - p = server.getPlayer(portal.getOwnerName()); - } - if (p != null) { - String obtainedMsg = Stargate.getString("ecoObtain"); - obtainedMsg = Stargate.replaceVars(obtainedMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - Stargate.sendMessage(p, obtainedMsg, false); - } - } - } - - Stargate.sendMessage(player, Stargate.getString("teleportMsg"), false); - - // BungeeCord Support - if (portal.isBungee()) { - if (!enableBungee) { - player.sendMessage(Stargate.getString("bungeeDisabled")); - portal.close(false); - return; - } - - // Teleport the player back to this gate, for sanity's sake - portal.teleport(player, portal, event); - - // Send the SGBungee packet first, it will be queued by BC if required - try { - // Build the message, format is #@# - String msg = event.getPlayer().getName() + "#@#" + portal.getDestinationName(); - // Build the message data, sent over the SGBungee bungeecord channel - ByteArrayOutputStream bao = new ByteArrayOutputStream(); - DataOutputStream msgData = new DataOutputStream(bao); - msgData.writeUTF("Forward"); - msgData.writeUTF(portal.getNetwork()); // Server - msgData.writeUTF("SGBungee"); // Channel - msgData.writeShort(msg.length()); // Data Length - msgData.writeBytes(msg); // Data - player.sendPluginMessage(stargate, "BungeeCord", bao.toByteArray()); - } catch (IOException ex) { - Stargate.log.severe("[Stargate] Error sending BungeeCord teleport packet"); - ex.printStackTrace(); - return; - } - - // Connect player to new server - try { - ByteArrayOutputStream bao = new ByteArrayOutputStream(); - DataOutputStream msgData = new DataOutputStream(bao); - msgData.writeUTF("Connect"); - msgData.writeUTF(portal.getNetwork()); - - player.sendPluginMessage(stargate, "BungeeCord", bao.toByteArray()); - bao.reset(); - } catch(IOException ex) { - Stargate.log.severe("[Stargate] Error sending BungeeCord connect packet"); - ex.printStackTrace(); - return; - } - - // Close portal if required (Should never be) - portal.close(false); - return; - } - - destination.teleport(player, portal, event); - portal.close(false); - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) { - Player player = event.getPlayer(); - Block block = event.getClickedBlock(); - - if(block == null) return; - - // Right click - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (block.getBlockData() instanceof WallSign) { - Portal portal = Portal.getByBlock(block); - if (portal == null) return; - // Cancel item use - event.setUseItemInHand(Result.DENY); - event.setUseInteractedBlock(Result.DENY); - - boolean deny = false; - if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - if (!Stargate.canAccessPortal(player, portal, deny)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - if ((!portal.isOpen()) && (!portal.isFixed())) { - portal.cycleDestination(player); - } - return; - } - - // Implement right-click to toggle a stargate, gets around spawn protection problem. - if (Tag.BUTTONS.isTagged(block.getType())) { - Portal portal = Portal.getByBlock(block); - if (portal == null) return; - - // Cancel item use - event.setUseItemInHand(Result.DENY); - event.setUseInteractedBlock(Result.DENY); - - boolean deny = false; - if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - if (!Stargate.canAccessPortal(player, portal, deny)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - openPortal(player, portal); - if (portal.isOpenFor(player)) { - event.setUseInteractedBlock(Result.ALLOW); - } - } - return; - } - - // Left click - if (event.getAction() == Action.LEFT_CLICK_BLOCK) { - // Check if we're scrolling a sign - if (block.getBlockData() instanceof WallSign) { - Portal portal = Portal.getByBlock(block); - if (portal == null) return; - - event.setUseInteractedBlock(Result.DENY); - // Only cancel event in creative mode - if (player.getGameMode().equals(GameMode.CREATIVE)) { - event.setCancelled(true); - } - - boolean deny = false; - if (!Stargate.canAccessNetwork(player, portal.getNetwork())) { - deny = true; - } - - if (!Stargate.canAccessPortal(player, portal, deny)) { - Stargate.sendMessage(player, Stargate.getString("denyMsg")); - return; - } - - if ((!portal.isOpen()) && (!portal.isFixed())) { - portal.cycleDestination(player, -1); - } - } - } - } - } - - private class bListener implements Listener { - @EventHandler - public void onSignChange(SignChangeEvent event) { - if (event.isCancelled()) return; - Player player = event.getPlayer(); - Block block = event.getBlock(); - if (!(block.getBlockData() instanceof WallSign)) return; - - final Portal portal = Portal.createPortal(event, player); - // Not creating a gate, just placing a sign - if (portal == null) return; - - Stargate.sendMessage(player, Stargate.getString("createMsg"), false); - Stargate.debug("onSignChange", "Initialized stargate: " + portal.getName()); - Stargate.server.getScheduler().scheduleSyncDelayedTask(stargate, new Runnable() { - public void run() { - portal.drawSign(); - } - }, 1); - } - - // Switch to HIGHEST priority so as to come after block protection plugins (Hopefully) - @EventHandler(priority = EventPriority.HIGHEST) - public void onBlockBreak(BlockBreakEvent event) { - if (event.isCancelled()) return; - Block block = event.getBlock(); - Player player = event.getPlayer(); - - Portal portal = Portal.getByBlock(block); - if (portal == null && protectEntrance) - portal = Portal.getByEntrance(block); - if (portal == null) return; - - boolean deny = false; - String denyMsg = ""; - - if (!Stargate.canDestroy(player, portal)) { - denyMsg = "Permission Denied"; // TODO: Change to Stargate.getString() - deny = true; - Stargate.log.info("[Stargate] " + player.getName() + " tried to destroy gate"); - } - - int cost = Stargate.getDestroyCost(player, portal.getGate()); - - StargateDestroyEvent dEvent = new StargateDestroyEvent(portal, player, deny, denyMsg, cost); - Stargate.server.getPluginManager().callEvent(dEvent); - if (dEvent.isCancelled()) { - event.setCancelled(true); - return; - } - if (dEvent.getDeny()) { - Stargate.sendMessage(player, dEvent.getDenyReason()); - event.setCancelled(true); - return; - } - - cost = dEvent.getCost(); - - if (cost != 0) { - if (!Stargate.chargePlayer(player, cost)) { - Stargate.debug("onBlockBreak", "Insufficient Funds"); - Stargate.sendMessage(player, Stargate.getString("inFunds")); - event.setCancelled(true); - return; - } - - if (cost > 0) { - String deductMsg = Stargate.getString("ecoDeduct"); - deductMsg = Stargate.replaceVars(deductMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(cost), portal.getName()}); - sendMessage(player, deductMsg, false); - } else if (cost < 0) { - String refundMsg = Stargate.getString("ecoRefund"); - refundMsg = Stargate.replaceVars(refundMsg, new String[] {"%cost%", "%portal%"}, new String[] {EconomyHandler.format(-cost), portal.getName()}); - sendMessage(player, refundMsg, false); - } - } - - portal.unregister(true); - Stargate.sendMessage(player, Stargate.getString("destroyMsg"), false); - } - - @EventHandler - public void onBlockPhysics(BlockPhysicsEvent event) { - Block block = event.getBlock(); - Portal portal = null; - - // Handle keeping portal material and buttons around - if (block.getType() == Material.NETHER_PORTAL) { - portal = Portal.getByEntrance(block); - } else if (Tag.BUTTONS.isTagged(block.getType())) { - portal = Portal.getByControl(block); - } - if (portal != null) event.setCancelled(true); - } - - @EventHandler - public void onBlockFromTo(BlockFromToEvent event) { - Portal portal = Portal.getByEntrance(event.getBlock()); - - if (portal != null) { - event.setCancelled((event.getBlock().getY() == event.getToBlock().getY())); - } - } - - @EventHandler - public void onPistonExtend(BlockPistonExtendEvent event) { - for(Block block : event.getBlocks()) { - Portal portal = Portal.getByBlock(block); - if (portal != null) { - event.setCancelled(true); - return; - } - } - } - - @EventHandler - public void onPistonRetract(BlockPistonRetractEvent event) { - if (!event.isSticky()) return; - for(Block block : event.getBlocks()) { - Portal portal = Portal.getByBlock(block); - if (portal != null) { - event.setCancelled(true); - return; - } - } - } - } - - private class wListener implements Listener { - @EventHandler - public void onWorldLoad(WorldLoadEvent event) { - if(!managedWorlds.contains(event.getWorld().getName()) - && Portal.loadAllGates(event.getWorld())) { - managedWorlds.add(event.getWorld().getName()); - } - } - - // We need to reload all gates on world unload, boo - @EventHandler - public void onWorldUnload(WorldUnloadEvent event) { - Stargate.debug("onWorldUnload", "Reloading all Stargates"); - World w = event.getWorld(); - if(managedWorlds.contains(w.getName())) { - managedWorlds.remove(w.getName()); - Portal.clearGates(); - for(World world : server.getWorlds()) { - if(managedWorlds.contains(world.getName())) { - Portal.loadAllGates(world); - } - } - } - } - } - - private class eListener implements Listener { - @EventHandler - public void onEntityExplode(EntityExplodeEvent event) { - if (event.isCancelled()) return; - for (Block b : event.blockList()) { - Portal portal = Portal.getByBlock(b); - if (portal == null) continue; - if (destroyExplosion) { - portal.unregister(true); - } else { - event.setCancelled(true); - break; - } - } - } - } - - private class sListener implements Listener { - @EventHandler - public void onPluginEnable(PluginEnableEvent event) { - if (EconomyHandler.setupEconomy(getServer().getPluginManager())) { - log.info("[Stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); - } - } - - @EventHandler - public void onPluginDisable(PluginDisableEvent event) { - if (event.getPlugin().equals(EconomyHandler.vault)) { - log.info("[Stargate] Vault plugin lost."); - } - } - } - - private class BlockPopulatorThread implements Runnable { - public void run() { - long sTime = System.nanoTime(); - while (System.nanoTime() - sTime < 25000000) { - BloxPopulator b = Stargate.blockPopulatorQueue.poll(); - if (b == null) return; - Block blk = b.getBlox().getBlock(); - blk.setType(b.getMat(), false); - if(b.getMat() == Material.END_GATEWAY && blk.getWorld().getEnvironment() == World.Environment.THE_END) { - // force a location to prevent exit gateway generation - EndGateway gateway = (EndGateway) blk.getState(); - gateway.setExitLocation(blk.getWorld().getSpawnLocation()); - gateway.setExactTeleport(true); - gateway.update(false, false); - } else if(b.getAxis() != null) { - Orientable orientable = (Orientable) blk.getBlockData(); - orientable.setAxis(b.getAxis()); - blk.setBlockData(orientable); - } - } - } - } - - private class SGThread implements Runnable { - public void run() { - long time = System.currentTimeMillis() / 1000; - // Close open portals - for (Iterator iter = Stargate.openList.iterator(); iter.hasNext();) { - Portal p = iter.next(); - // Skip always open gates - if (p.isAlwaysOn()) continue; - if (!p.isOpen()) continue; - if (time > p.getOpenTime() + Stargate.openTime) { - p.close(false); - iter.remove(); - } - } - // Deactivate active portals - for (Iterator iter = Stargate.activeList.iterator(); iter.hasNext();) { - Portal p = iter.next(); - if (!p.isActive()) continue; - if (time > p.getOpenTime() + Stargate.activeTime) { - p.deactivate(); - iter.remove(); - } - } - } - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - String cmd = command.getName(); - if (cmd.equalsIgnoreCase("sg")) { - if (args.length != 1) return false; - if (args[0].equalsIgnoreCase("about")) { - sender.sendMessage("Stargate Plugin created by Drakia"); - if (!lang.getString("author").isEmpty()) - sender.sendMessage("Language created by " + lang.getString("author")); - return true; - } - if (sender instanceof Player) { - Player p = (Player)sender; - if (!hasPerm(p, "stargate.admin") && !hasPerm(p, "stargate.admin.reload")) { - sendMessage(sender, "Permission Denied"); - return true; - } - } - if (args[0].equalsIgnoreCase("reload")) { - // Deactivate portals - for (Portal p : activeList) { - p.deactivate(); - } - // Close portals - closeAllPortals(); - // Clear all lists - activeList.clear(); - openList.clear(); - managedWorlds.clear(); - Portal.clearGates(); - Gate.clearGates(); - - // Store the old Bungee enabled value - boolean oldEnableBungee = enableBungee; - // Reload data - loadConfig(); - loadGates(); - loadAllPortals(); - lang.setLang(langName); - lang.reload(); - - // Load Economy support if enabled/clear if disabled - if (EconomyHandler.economyEnabled && EconomyHandler.economy == null) { - if (EconomyHandler.setupEconomy(pm)) { - if (EconomyHandler.economy != null) - log.info("[Stargate] Vault v" + EconomyHandler.vault.getDescription().getVersion() + " found"); - } - } - if (!EconomyHandler.economyEnabled) { - EconomyHandler.vault = null; - EconomyHandler.economy = null; - } - - // Enable the required channels for Bungee support - if (oldEnableBungee != enableBungee) { - if (enableBungee) { - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new pmListener()); - } else { - Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "BungeeCord"); - } - } - - sendMessage(sender, "Stargate reloaded"); - return true; - } - return false; - } - return false; - } -} diff --git a/src/net/TheDgtl/Stargate/event/StargateActivateEvent.java b/src/net/TheDgtl/Stargate/event/StargateActivateEvent.java deleted file mode 100644 index e254c3b..0000000 --- a/src/net/TheDgtl/Stargate/event/StargateActivateEvent.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.TheDgtl.Stargate.event; - -import java.util.ArrayList; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -import net.TheDgtl.Stargate.Portal; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateActivateEvent extends StargateEvent { - private final Player player; - private ArrayList destinations; - private String destination; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - public StargateActivateEvent(Portal portal, Player player, ArrayList destinations, String destination) { - super("StargatActivateEvent", portal); - - this.player = player; - this.destinations = destinations; - this.destination = destination; - } - - public Player getPlayer() { - return player; - } - - public ArrayList getDestinations() { - return destinations; - } - - public void setDestinations(ArrayList destinations) { - this.destinations = destinations; - } - - public String getDestination() { - return destination; - } - - public void setDestination(String destination) { - this.destination = destination; - } -} diff --git a/src/net/TheDgtl/Stargate/event/StargateCreateEvent.java b/src/net/TheDgtl/Stargate/event/StargateCreateEvent.java deleted file mode 100644 index 05a46d0..0000000 --- a/src/net/TheDgtl/Stargate/event/StargateCreateEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.TheDgtl.Stargate.event; - -import net.TheDgtl.Stargate.Portal; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateCreateEvent extends StargateEvent { - private final Player player; - private boolean deny; - private String denyReason; - private final String[] lines; - private int cost; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public StargateCreateEvent(Player player, Portal portal, String[] lines, boolean deny, String denyReason, int cost) { - super("StargateCreateEvent", portal); - this.player = player; - this.lines = lines; - this.deny = deny; - this.denyReason = denyReason; - this.cost = cost; - } - - public Player getPlayer() { - return player; - } - - public String getLine(int index) throws IndexOutOfBoundsException { - return lines[index]; - } - - public boolean getDeny() { - return deny; - } - - public void setDeny(boolean deny) { - this.deny = deny; - } - - public String getDenyReason() { - return denyReason; - } - - public void setDenyReason(String denyReason) { - this.denyReason = denyReason; - } - - public int getCost() { - return cost; - } - - public void setCost(int cost) { - this.cost = cost; - } - -} diff --git a/src/net/TheDgtl/Stargate/event/StargateDestroyEvent.java b/src/net/TheDgtl/Stargate/event/StargateDestroyEvent.java deleted file mode 100644 index 7ea06fe..0000000 --- a/src/net/TheDgtl/Stargate/event/StargateDestroyEvent.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.TheDgtl.Stargate.event; - -import net.TheDgtl.Stargate.Portal; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateDestroyEvent extends StargateEvent { - private final Player player; - private boolean deny; - private String denyReason; - private int cost; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public StargateDestroyEvent(Portal portal, Player player, boolean deny, String denyMsg, int cost) { - super("StargateDestroyEvent", portal); - this.player = player; - this.deny = deny; - this.denyReason = denyMsg; - this.cost = cost; - } - - public Player getPlayer() { - return player; - } - - public boolean getDeny() { - return deny; - } - - public void setDeny(boolean deny) { - this.deny = deny; - } - - public String getDenyReason() { - return denyReason; - } - - public void setDenyReason(String denyReason) { - this.denyReason = denyReason; - } - - public int getCost() { - return cost; - } - - public void setCost(int cost) { - this.cost = cost; - } - -} diff --git a/src/net/TheDgtl/Stargate/event/StargateOpenEvent.java b/src/net/TheDgtl/Stargate/event/StargateOpenEvent.java deleted file mode 100644 index 26ddc08..0000000 --- a/src/net/TheDgtl/Stargate/event/StargateOpenEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.TheDgtl.Stargate.event; - -import net.TheDgtl.Stargate.Portal; - -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargateOpenEvent extends StargateEvent { - private final Player player; - private boolean force; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - public StargateOpenEvent(Player player, Portal portal, boolean force) { - super ("StargateOpenEvent", portal); - - this.player = player; - this.force = force; - } - - /** - * Return the player than opened the gate. - * @return player than opened the gate - */ - public Player getPlayer() { - return player; - } - - public boolean getForce() { - return force; - } - - public void setForce(boolean force) { - this.force = force; - } -} diff --git a/src/net/TheDgtl/Stargate/event/StargatePortalEvent.java b/src/net/TheDgtl/Stargate/event/StargatePortalEvent.java deleted file mode 100644 index d02eb63..0000000 --- a/src/net/TheDgtl/Stargate/event/StargatePortalEvent.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.TheDgtl.Stargate.event; - -import net.TheDgtl.Stargate.Portal; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -/** - * Stargate - A portal plugin for Bukkit - * Copyright (C) 2011, 2012 Steven "Drakia" Scott - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -public class StargatePortalEvent extends StargateEvent { - private final Player player; - private final Portal destination; - private Location exit; - - private static final HandlerList handlers = new HandlerList(); - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public StargatePortalEvent(Player player, Portal portal, Portal dest, Location exit) { - super ("StargatePortalEvent", portal); - - this.player = player; - this.destination = dest; - this.exit = exit; - } - - /** - * Return the player that went through the gate. - * @return player that went through the gate - */ - public Player getPlayer() { - return player; - } - - /** - * Return the destination gate - * @return destination gate - */ - public Portal getDestination() { - return destination; - } - - /** - * Return the location of the players exit point - * @return org.bukkit.Location Location of the exit point - */ - public Location getExit() { - return exit; - } - - /** - * Set the location of the players exit point - */ - public void setExit(Location loc) { - this.exit = loc; - } -} diff --git a/src/net/TheDgtl/Stargate/pmListener.java b/src/net/TheDgtl/Stargate/pmListener.java deleted file mode 100644 index ee83ba9..0000000 --- a/src/net/TheDgtl/Stargate/pmListener.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.TheDgtl.Stargate; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; - -import org.bukkit.entity.Player; -import org.bukkit.plugin.messaging.PluginMessageListener; - -public class pmListener implements PluginMessageListener { - - @Override - public void onPluginMessageReceived(String channel, Player unused, byte[] message) { - if (!Stargate.enableBungee || !channel.equals("BungeeCord")) return; - - // Get data from message - String inChannel; - byte[] data; - try { - DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); - inChannel = in.readUTF(); - short len = in.readShort(); - data = new byte[len]; - in.readFully(data); - } catch (IOException ex) { - Stargate.log.severe("[Stargate] Error receiving BungeeCord message"); - ex.printStackTrace(); - return; - } - - // Verify that it's an SGBungee packet - if (!inChannel.equals("SGBungee")) { - return; - } - - // Data should be player name, and destination gate name - String msg = new String(data); - String[] parts = msg.split("#@#"); - - String playerName = parts[0]; - String destination = parts[1]; - - // Check if the player is online, if so, teleport, otherwise, queue - Player player = Stargate.server.getPlayer(playerName); - if (player == null) { - Stargate.bungeeQueue.put(playerName.toLowerCase(), destination); - } else { - Portal dest = Portal.getBungeeGate(destination); - // Specified an invalid gate. For now we'll just let them connect at their current location - if (dest == null) { - Stargate.log.info("[Stargate] Bungee gate " + destination + " does not exist"); - return; - } - dest.teleport(player, dest, null); - } - } -}