diff --git a/pom.xml b/pom.xml index 6e49052f8..0bb3998a4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,104 +1,104 @@ - - 4.0.0 - org.maxgamer - QuickShop - Reremake 1.3.7.2 - - - - GPL v3 License - http://www.gnu.org/licenses/ - repo - - - - org.maxgamer.quickshop - Ghost_chu - UTF-8 - - - https://github.com/${developer}/${name}/issues - GitHub Issues - - - - https://github.com/${developer}/${version} - scm:git:git://github.com/${developer}/${version}.git - scm:git:git@github.com:${developer}/${version}.git - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - UTF-8 - - - - - - true - src/main/resources - - - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - sk89q-repo - http://maven.sk89q.com/repo/ - - - mv-core - http://repo.onarandombox.com/content/repositories/multiverse/ - - - fanciful-repo - https://github.com/mkremins/fanciful/tree/mvn-repo - - - dmulloy2-repo - http://repo.dmulloy2.net/nexus/repository/public/ - - - - - - org.spigotmc - spigot-api - 1.13.2-R0.1-SNAPSHOT - provided - - - net.milkbowl.vault - VaultAPI - 1.6 - system - ${basedir}/lib/Vault1.6.10.jar - - - com.onarandombox.multiversecore - Multiverse-Core - 2.5.1 - provided - - - com.lishid - OpenInv - 3.3.0 - system - ${basedir}/lib/OpenInv.jar - - - + + 4.0.0 + org.maxgamer + QuickShop + Reremake 1.4.0-SNAPSHOT + + + + GPL v3 License + http://www.gnu.org/licenses/ + repo + + + + org.maxgamer.quickshop + Ghost_chu + UTF-8 + + + https://github.com/${developer}/${name}/issues + GitHub Issues + + + + https://github.com/${developer}/${version} + scm:git:git://github.com/${developer}/${version}.git + scm:git:git@github.com:${developer}/${version}.git + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + UTF-8 + + + + + + true + src/main/resources + + + + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + sk89q-repo + http://maven.sk89q.com/repo/ + + + mv-core + http://repo.onarandombox.com/content/repositories/multiverse/ + + + fanciful-repo + https://github.com/mkremins/fanciful/tree/mvn-repo + + + dmulloy2-repo + http://repo.dmulloy2.net/nexus/repository/public/ + + + + + + org.spigotmc + spigot-api + 1.14-pre5-SNAPSHOT + provided + + + net.milkbowl.vault + VaultAPI + 1.6 + system + ${basedir}/lib/Vault1.6.10.jar + + + com.onarandombox.multiversecore + Multiverse-Core + 2.5.1 + provided + + + com.lishid + OpenInv + 3.3.0 + system + ${basedir}/lib/OpenInv.jar + + + diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java index 6337e0b9f..9010ba406 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/BlockListener.java @@ -1,276 +1,276 @@ -package org.maxgamer.quickshop.Listeners; - -import java.sql.SQLException; - -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.DoubleChest; -import org.bukkit.block.Hopper; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.entity.minecart.HopperMinecart; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockExplodeEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.inventory.InventoryMoveItemEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Database.DatabaseHelper; -import org.maxgamer.quickshop.Shop.Info; -import org.maxgamer.quickshop.Shop.Shop; -import org.maxgamer.quickshop.Shop.ShopAction; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Util; - -public class BlockListener implements Listener { - private QuickShop plugin; - - public BlockListener(QuickShop plugin) { - this.plugin = plugin; - } - - /** - * Listens for chest placement, so a doublechest shop can't be created. - */ - @EventHandler(ignoreCancelled = true) - public void onPlace(BlockPlaceEvent e) { - BlockState bs = e.getBlock().getState(); - if (bs instanceof DoubleChest == false) - return; - Block b = e.getBlock(); - Player p = e.getPlayer(); - Block chest = Util.getSecondHalf(b); - if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p.hasPermission("quickshop.create.double")) { - e.setCancelled(true); - p.sendMessage(MsgUtil.getMessage("no-double-chests")); - } - } - - /** - * Removes chests when they're destroyed. - */ - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBreak(BlockBreakEvent e) { - Block b = e.getBlock(); - if(b.getState() instanceof Sign) { - Sign sign = (Sign)b.getState(); - if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ - //Ignore break lockette sign - plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette or other sign-lock plugin)"); - return; - } - } - Player p = e.getPlayer(); - // If the shop was a chest - if (Util.canBeShop(b,null,true)) { - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) - return; - // If they're either survival or the owner, they can break it - if (p.getGameMode() == GameMode.CREATIVE && !p.getUniqueId().equals(shop.getOwner())) { - e.setCancelled(true); - p.sendMessage(MsgUtil.getMessage("no-creative-break")); - return; - } - // Cancel their current menu... Doesnt cancel other's menu's. - Info action = plugin.getShopManager().getActions().get(p.getUniqueId()); - if (action != null) { - action.setAction(ShopAction.CANCELLED); - } - shop.delete(); - try { - DatabaseHelper.removeShop(plugin.getDB(), shop.getLocation().getBlockX(), shop.getLocation().getBlockY(), shop.getLocation().getBlockZ(), shop.getLocation().getWorld().getName()); - } catch (SQLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - p.sendMessage(MsgUtil.getMessage("success-removed-shop")); - } else if (b.getType() == Material.WALL_SIGN) { - if(b instanceof Sign) { - Sign sign = (Sign)b; - if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ - //Ignore break lockette sign - plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette)"); - return; - } - } - Shop shop = getShopNextTo(b.getLocation()); - if (shop == null) - return; - // If they're in creative and not the owner, don't let them - // (accidents happen) - if (p.getGameMode() == GameMode.CREATIVE && !p.getUniqueId().equals(shop.getOwner())) { - //Check SuperTool - if(p.getInventory().getItemInMainHand().getType()==Material.GOLDEN_AXE) { - p.sendMessage(MsgUtil.getMessage("break-shop-use-supertool")); - return; - } - e.setCancelled(true); - p.sendMessage(MsgUtil.getMessage("no-creative-break",MsgUtil.getItemi18n(Material.GOLDEN_AXE.name()))); - return; - } - if (e.isCancelled()) { - return; - } - e.setCancelled(true); - // Cancel the event so that the sign does not - // drop.. TODO: Find a better way. - //b.setType(Material.AIR); - } - } - //Protect Minecart steal shop - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onInventoryMove(InventoryMoveItemEvent event){ - if (plugin.getConfig().getBoolean("protect.minecart")){ - // Additional Hopper Minecart Check - if (event.getDestination().getHolder() instanceof HopperMinecart) { - HopperMinecart hm = (HopperMinecart) event.getDestination().getHolder(); - Location minecartLoc = new Location(hm.getWorld(), hm.getLocation().getBlockX(), hm.getLocation().getBlockY()+1, hm.getLocation().getBlockZ()); - Shop shop = plugin.getShopManager().getShop(minecartLoc); - if (shop == null) { - return; - } - event.setCancelled(true); - hm.remove(); - plugin.getLogger().warning("[Exploit Alert] a HopperMinecart tried to move the item of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A HopperMinecart tried to move the item of "+shop); - } - } - if(plugin.getConfig().getBoolean("protect.hopper")) { - if (event.getDestination().getHolder() instanceof Hopper) { - Hopper h = (Hopper) event.getDestination().getHolder(); - Location minecartLoc = new Location(h.getWorld(), h.getLocation().getBlockX(), h.getLocation().getBlockY()+1, h.getLocation().getBlockZ()); - Shop shop = plugin.getShopManager().getShop(minecartLoc); - if (shop == null) { - return; - } - event.setCancelled(true); - } - } - } - //Protect Entity pickup shop - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onMobChangeBlock(EntityChangeBlockEvent event) { - Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); - if (shop == null) { - return; - } - if (shop !=null){ - if(plugin.getConfig().getBoolean("protect.entity")) { - event.setCancelled(true); - event.getEntity().remove(); - plugin.getLogger().warning("[Exploit Alert] a Entity tried to break the shop of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A Entity tried to break the shop of "+shop); - }else { - shop.delete(); - } - } - } - //Protect Redstone active shop - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockRedstoneChange(BlockRedstoneEvent event){ - if (!plugin.getConfig().getBoolean("protect.redstone")){ - return; - } - Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); - if (shop == null) { - return; - } - if (shop != null){ - event.setNewCurrent(event.getOldCurrent()); - plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A Redstone tried to active of "+shop); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onStructureGrow(StructureGrowEvent event){ - if (!plugin.getConfig().getBoolean("protect.structuregrow")) { - return; - } - for (BlockState blockstate : event.getBlocks()){ - Shop shop = plugin.getShopManager().getShop(blockstate.getLocation()); - if (shop == null) { - return; - } - if(shop !=null) { - event.setCancelled(true); - plugin.getLogger().warning("[Exploit Alert] a StructureGrowing tried to break the shop of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A StructureGrowing tried to break the shop of "+shop); - } - - } - } - - /** - * Handles shops breaking through explosions - */ - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onExplode(EntityExplodeEvent e) { - for (int i = 0; i < e.blockList().size(); i++) { - Block b = e.blockList().get(i); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if(plugin.getConfig().getBoolean("protect.explode")) { - e.setCancelled(true); - plugin.getLogger().warning("[Exploit Alert] a EntityExplode tried to break the shop of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A EntityExplode tried to break the shop of "+shop); - }else { - shop.delete(); - } - } - } - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockExplode(BlockExplodeEvent e) { - for (int i = 0; i < e.blockList().size(); i++) { - Block b = e.blockList().get(i); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if(plugin.getConfig().getBoolean("protect.explode")) { - e.setCancelled(true); - plugin.getLogger().warning("[Exploit Alert] a BlockExplode tried to break the shop of "+shop); - Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A BlockExplode tried to break the shop of "+shop); - }else { - shop.delete(); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent e) { - Block newBlock = e.getNewState().getBlock(); - Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation()); - Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation()); - if(thisBlockShop == null && underBlockShop == null) - return; - e.setCancelled(true); - } - /** - * Gets the shop a sign is attached to - * - * @param loc - * The location of the sign - * @return The shop - */ - private Shop getShopNextTo(Location loc) { - Block b = Util.getAttached(loc.getBlock()); - // Util.getAttached(b) - if (b == null) - return null; - return plugin.getShopManager().getShop(b.getLocation()); - } +package org.maxgamer.quickshop.Listeners; + +import java.sql.SQLException; + +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.DoubleChest; +import org.bukkit.block.Hopper; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.entity.minecart.HopperMinecart; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Database.DatabaseHelper; +import org.maxgamer.quickshop.Shop.Info; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Shop.ShopAction; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Util; + +public class BlockListener implements Listener { + private QuickShop plugin; + + public BlockListener(QuickShop plugin) { + this.plugin = plugin; + } + + /** + * Listens for chest placement, so a doublechest shop can't be created. + */ + @EventHandler(ignoreCancelled = true) + public void onPlace(BlockPlaceEvent e) { + BlockState bs = e.getBlock().getState(); + if (bs instanceof DoubleChest == false) + return; + Block b = e.getBlock(); + Player p = e.getPlayer(); + Block chest = Util.getSecondHalf(b); + if (chest != null && plugin.getShopManager().getShop(chest.getLocation()) != null && !p.hasPermission("quickshop.create.double")) { + e.setCancelled(true); + p.sendMessage(MsgUtil.getMessage("no-double-chests")); + } + } + + /** + * Removes chests when they're destroyed. + */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBreak(BlockBreakEvent e) { + Block b = e.getBlock(); + if(b.getState() instanceof Sign) { + Sign sign = (Sign)b.getState(); + if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ + //Ignore break lockette sign + plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette or other sign-lock plugin)"); + return; + } + } + Player p = e.getPlayer(); + // If the shop was a chest + if (Util.canBeShop(b,null,true)) { + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) + return; + // If they're either survival or the owner, they can break it + if (p.getGameMode() == GameMode.CREATIVE && !p.getUniqueId().equals(shop.getOwner())) { + e.setCancelled(true); + p.sendMessage(MsgUtil.getMessage("no-creative-break")); + return; + } + // Cancel their current menu... Doesnt cancel other's menu's. + Info action = plugin.getShopManager().getActions().get(p.getUniqueId()); + if (action != null) { + action.setAction(ShopAction.CANCELLED); + } + shop.delete(); + try { + DatabaseHelper.removeShop(plugin.getDB(), shop.getLocation().getBlockX(), shop.getLocation().getBlockY(), shop.getLocation().getBlockZ(), shop.getLocation().getWorld().getName()); + } catch (SQLException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + p.sendMessage(MsgUtil.getMessage("success-removed-shop")); + } else if (Util.isWallSign(b.getType())) { + if(b instanceof Sign) { + Sign sign = (Sign)b; + if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ + //Ignore break lockette sign + plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette)"); + return; + } + } + Shop shop = getShopNextTo(b.getLocation()); + if (shop == null) + return; + // If they're in creative and not the owner, don't let them + // (accidents happen) + if (p.getGameMode() == GameMode.CREATIVE && !p.getUniqueId().equals(shop.getOwner())) { + //Check SuperTool + if(p.getInventory().getItemInMainHand().getType()==Material.GOLDEN_AXE) { + p.sendMessage(MsgUtil.getMessage("break-shop-use-supertool")); + return; + } + e.setCancelled(true); + p.sendMessage(MsgUtil.getMessage("no-creative-break",MsgUtil.getItemi18n(Material.GOLDEN_AXE.name()))); + return; + } + if (e.isCancelled()) { + return; + } + e.setCancelled(true); + // Cancel the event so that the sign does not + // drop.. TODO: Find a better way. + //b.setType(Material.AIR); + } + } + //Protect Minecart steal shop + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onInventoryMove(InventoryMoveItemEvent event){ + if (plugin.getConfig().getBoolean("protect.minecart")){ + // Additional Hopper Minecart Check + if (event.getDestination().getHolder() instanceof HopperMinecart) { + HopperMinecart hm = (HopperMinecart) event.getDestination().getHolder(); + Location minecartLoc = new Location(hm.getWorld(), hm.getLocation().getBlockX(), hm.getLocation().getBlockY()+1, hm.getLocation().getBlockZ()); + Shop shop = plugin.getShopManager().getShop(minecartLoc); + if (shop == null) { + return; + } + event.setCancelled(true); + hm.remove(); + plugin.getLogger().warning("[Exploit Alert] a HopperMinecart tried to move the item of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A HopperMinecart tried to move the item of "+shop); + } + } + if(plugin.getConfig().getBoolean("protect.hopper")) { + if (event.getDestination().getHolder() instanceof Hopper) { + Hopper h = (Hopper) event.getDestination().getHolder(); + Location minecartLoc = new Location(h.getWorld(), h.getLocation().getBlockX(), h.getLocation().getBlockY()+1, h.getLocation().getBlockZ()); + Shop shop = plugin.getShopManager().getShop(minecartLoc); + if (shop == null) { + return; + } + event.setCancelled(true); + } + } + } + //Protect Entity pickup shop + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onMobChangeBlock(EntityChangeBlockEvent event) { + Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); + if (shop == null) { + return; + } + if (shop !=null){ + if(plugin.getConfig().getBoolean("protect.entity")) { + event.setCancelled(true); + event.getEntity().remove(); + plugin.getLogger().warning("[Exploit Alert] a Entity tried to break the shop of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A Entity tried to break the shop of "+shop); + }else { + shop.delete(); + } + } + } + //Protect Redstone active shop + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockRedstoneChange(BlockRedstoneEvent event){ + if (!plugin.getConfig().getBoolean("protect.redstone")){ + return; + } + Shop shop = plugin.getShopManager().getShop(event.getBlock().getLocation()); + if (shop == null) { + return; + } + if (shop != null){ + event.setNewCurrent(event.getOldCurrent()); + plugin.getLogger().warning("[Exploit Alert] a Redstone tried to active of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A Redstone tried to active of "+shop); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onStructureGrow(StructureGrowEvent event){ + if (!plugin.getConfig().getBoolean("protect.structuregrow")) { + return; + } + for (BlockState blockstate : event.getBlocks()){ + Shop shop = plugin.getShopManager().getShop(blockstate.getLocation()); + if (shop == null) { + return; + } + if(shop !=null) { + event.setCancelled(true); + plugin.getLogger().warning("[Exploit Alert] a StructureGrowing tried to break the shop of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A StructureGrowing tried to break the shop of "+shop); + } + + } + } + + /** + * Handles shops breaking through explosions + */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onExplode(EntityExplodeEvent e) { + for (int i = 0; i < e.blockList().size(); i++) { + Block b = e.blockList().get(i); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if(plugin.getConfig().getBoolean("protect.explode")) { + e.setCancelled(true); + plugin.getLogger().warning("[Exploit Alert] a EntityExplode tried to break the shop of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A EntityExplode tried to break the shop of "+shop); + }else { + shop.delete(); + } + } + } + } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent e) { + for (int i = 0; i < e.blockList().size(); i++) { + Block b = e.blockList().get(i); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if(plugin.getConfig().getBoolean("protect.explode")) { + e.setCancelled(true); + plugin.getLogger().warning("[Exploit Alert] a BlockExplode tried to break the shop of "+shop); + Util.sendMessageToOps(ChatColor.RED+"[QuickShop][Exploit alert] A BlockExplode tried to break the shop of "+shop); + }else { + shop.delete(); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent e) { + Block newBlock = e.getNewState().getBlock(); + Shop thisBlockShop = plugin.getShopManager().getShop(newBlock.getLocation()); + Shop underBlockShop = plugin.getShopManager().getShop(newBlock.getRelative(BlockFace.DOWN).getLocation()); + if(thisBlockShop == null && underBlockShop == null) + return; + e.setCancelled(true); + } + /** + * Gets the shop a sign is attached to + * + * @param loc + * The location of the sign + * @return The shop + */ + private Shop getShopNextTo(Location loc) { + Block b = Util.getAttached(loc.getBlock()); + // Util.getAttached(b) + if (b == null) + return null; + return plugin.getShopManager().getShop(b.getLocation()); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java index e072bc141..89a46420a 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/LockListener.java @@ -1,147 +1,147 @@ -package org.maxgamer.quickshop.Listeners; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -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.BlockPlaceEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Shop.Shop; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Util; - -public class LockListener implements Listener { - private QuickShop plugin; - - public LockListener(QuickShop plugin) { - this.plugin = plugin; - } - - @EventHandler(ignoreCancelled = true) - public void onClick(PlayerInteractEvent e) { - Block b = e.getClickedBlock(); - Player p = e.getPlayer(); - if (e.getAction() != Action.RIGHT_CLICK_BLOCK) - return; // Didn't right click it, we dont care. - if (!Util.canBeShop(b,null,true)) - return; // Interacted with air - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - // Make sure they're not using the non-shop half of a double chest. - if (shop == null) { - b = Util.getSecondHalf(b); - if (b == null) - return; - shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) - return; - } - if (!shop.getOwner().equals(p.getUniqueId())) { - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.getMessage("bypassing-lock")); - return; - } - p.sendMessage(MsgUtil.getMessage("that-is-locked")); - e.setCancelled(true); - return; - } - } - /** - * Handles hopper placement - */ - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent e) { - Block b = e.getBlock(); - try { - if (b.getType() != Material.HOPPER) - return; - } catch (NoSuchFieldError er) { - return; // Your server doesn't have hoppers - } - Player p = e.getPlayer(); - if (Util.isOtherShopWithinHopperReach(b, p) == false) - return; - - if (p.hasPermission("quickshop.other.open")) { - p.sendMessage(MsgUtil.getMessage("bypassing-lock")); - return; - } - p.sendMessage(MsgUtil.getMessage("that-is-locked")); - e.setCancelled(true); - } - - /** - * Removes chests when they're destroyed. - */ - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBreak(BlockBreakEvent e) { - Block b = e.getBlock(); - if(b.getState() instanceof Sign) { - Sign sign = (Sign)b.getState(); - if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ - //Ignore break lockette sign - plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette or other sign-lock plugin)"); - return; - } - } - Player p = e.getPlayer(); - // If the chest was a chest - if (Util.canBeShop(b,null,true)) { - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) - return; // Wasn't a shop - // If they owned it or have bypass perms, they can destroy it - if (!shop.getOwner().equals(p.getUniqueId()) && !p.hasPermission("quickshop.other.destroy")) { - e.setCancelled(true); - p.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } else if (b.getType() == Material.WALL_SIGN) { - if(b instanceof Sign) { - Sign sign = (Sign)b; - if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ - //Ignore break lockette sign - plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette)"); - return; - } - } - b = Util.getAttached(b); - if (b == null) - return; - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop == null) - return; - // If they're the shop owner or have bypass perms, they can destroy - // it. - if (!shop.getOwner().equals(p.getUniqueId()) && !p.hasPermission("quickshop.other.destroy")) { - e.setCancelled(true); - p.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - } - - /** - * Handles shops breaking through explosions - */ - @EventHandler(priority = EventPriority.LOW,ignoreCancelled=true) - public void onExplode(EntityExplodeEvent e) { - if (e.isCancelled()) - return; - for (int i = 0; i < e.blockList().size(); i++) { - Block b = e.blockList().get(i); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - // ToDo: Shouldn't I be decrementing 1 here? Concurrency and - // all.. - e.blockList().remove(b); - } - } - } +package org.maxgamer.quickshop.Listeners; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +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.BlockPlaceEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Util; + +public class LockListener implements Listener { + private QuickShop plugin; + + public LockListener(QuickShop plugin) { + this.plugin = plugin; + } + + @EventHandler(ignoreCancelled = true) + public void onClick(PlayerInteractEvent e) { + Block b = e.getClickedBlock(); + Player p = e.getPlayer(); + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) + return; // Didn't right click it, we dont care. + if (!Util.canBeShop(b,null,true)) + return; // Interacted with air + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + // Make sure they're not using the non-shop half of a double chest. + if (shop == null) { + b = Util.getSecondHalf(b); + if (b == null) + return; + shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) + return; + } + if (!shop.getOwner().equals(p.getUniqueId())) { + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.getMessage("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.getMessage("that-is-locked")); + e.setCancelled(true); + return; + } + } + /** + * Handles hopper placement + */ + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent e) { + Block b = e.getBlock(); + try { + if (b.getType() != Material.HOPPER) + return; + } catch (NoSuchFieldError er) { + return; // Your server doesn't have hoppers + } + Player p = e.getPlayer(); + if (Util.isOtherShopWithinHopperReach(b, p) == false) + return; + + if (p.hasPermission("quickshop.other.open")) { + p.sendMessage(MsgUtil.getMessage("bypassing-lock")); + return; + } + p.sendMessage(MsgUtil.getMessage("that-is-locked")); + e.setCancelled(true); + } + + /** + * Removes chests when they're destroyed. + */ + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBreak(BlockBreakEvent e) { + Block b = e.getBlock(); + if(b.getState() instanceof Sign) { + Sign sign = (Sign)b.getState(); + if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ + //Ignore break lockette sign + plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette or other sign-lock plugin)"); + return; + } + } + Player p = e.getPlayer(); + // If the chest was a chest + if (Util.canBeShop(b,null,true)) { + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) + return; // Wasn't a shop + // If they owned it or have bypass perms, they can destroy it + if (!shop.getOwner().equals(p.getUniqueId()) && !p.hasPermission("quickshop.other.destroy")) { + e.setCancelled(true); + p.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } else if (Util.isWallSign(b.getType())) { + if(b instanceof Sign) { + Sign sign = (Sign)b; + if(sign.getLine(0).equals(plugin.getConfig().getString("lockette.private"))||sign.getLine(0).equals(plugin.getConfig().getString("lockette.more_users"))){ + //Ignore break lockette sign + plugin.getLogger().info("Skipped a dead-lock shop sign.(Lockette)"); + return; + } + } + b = Util.getAttached(b); + if (b == null) + return; + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop == null) + return; + // If they're the shop owner or have bypass perms, they can destroy + // it. + if (!shop.getOwner().equals(p.getUniqueId()) && !p.hasPermission("quickshop.other.destroy")) { + e.setCancelled(true); + p.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + } + + /** + * Handles shops breaking through explosions + */ + @EventHandler(priority = EventPriority.LOW,ignoreCancelled=true) + public void onExplode(EntityExplodeEvent e) { + if (e.isCancelled()) + return; + for (int i = 0; i < e.blockList().size(); i++) { + Block b = e.blockList().get(i); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + // ToDo: Shouldn't I be decrementing 1 here? Concurrency and + // all.. + e.blockList().remove(b); + } + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java index 3a9493988..153170abc 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java @@ -1,253 +1,253 @@ -package org.maxgamer.quickshop.Listeners; - -import org.bukkit.*; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -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.inventory.InventoryCloseEvent; -import org.bukkit.event.player.*; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.BlockIterator; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Shop.Info; -import org.maxgamer.quickshop.Shop.Shop; -import org.maxgamer.quickshop.Shop.ShopAction; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Util; - -//import com.griefcraft.lwc.LWC; -//import com.griefcraft.lwc.LWCPlugin; - -import java.util.HashMap; -import java.util.UUID; - -public class PlayerListener implements Listener { - private QuickShop plugin; - - public PlayerListener(QuickShop plugin) { - this.plugin = plugin; - } - - /* - * Could be useful one day private LinkedList getParents(Class - * clazz){ LinkedList classes = new LinkedList(); - * - * while(clazz != null){ classes.add("Extends " + ChatColor.GREEN + - * clazz.getCanonicalName()); for(Class iface : clazz.getInterfaces()){ - * classes.add("Implements " + ChatColor.RED + iface.getCanonicalName()); - * classes.addAll(getParents(iface)); } - * - * clazz = clazz.getSuperclass(); } return classes; } - */ - /** - * Handles players left clicking a chest. Left click a NORMAL chest with item : - * Send creation menu Left click a SHOP chest : Send purchase menu - */ - @EventHandler(priority = EventPriority.MONITOR) - public void onClick(PlayerInteractEvent e) { - if (e.getAction().equals(Action.LEFT_CLICK_BLOCK)) { - Block b = e.getClickedBlock(); - if (!Util.canBeShop(b,null,true) && b.getType() != Material.WALL_SIGN) { - return; - } - Player p = e.getPlayer(); - Location loc = b.getLocation(); - ItemStack item = e.getItem(); - // Get the shop - Shop shop = plugin.getShopManager().getShop(loc); - // If that wasn't a shop, search nearby shops - if (shop == null) { - Block attached = null; - - if (b.getType() == Material.WALL_SIGN) { - attached = Util.getAttached(b); - if (attached != null) { - shop = plugin.getShopManager().getShop(attached.getLocation()); - } - } else if (b.getType() == Material.CHEST || b.getType() == Material.TRAPPED_CHEST) { - attached = Util.getSecondHalf(b); - if (attached != null) { - Shop secondHalfShop = plugin.getShopManager().getShop(attached.getLocation()); - if (secondHalfShop != null && !p.getUniqueId().equals(secondHalfShop.getOwner())) { - // If player not the owner of the shop, make him select the second half of the - // shop - // Otherwise owner will be able to create new double chest shop - shop = secondHalfShop; - } - } - } - } - // Purchase handling - if (shop != null && p.hasPermission("quickshop.use")) { - if(plugin.getConfig().getBoolean("shop.sneak-to-trade")&&!p.isSneaking()) - return; - shop.onClick(); - // Text menu - MsgUtil.sendShopInfo(p, shop); - shop.setSignText(); - if (shop.isSelling()) { - p.sendMessage(MsgUtil.getMessage("how-many-buy")); - } else { - int items = Util.countItems(p.getInventory(), shop.getItem()); - p.sendMessage(MsgUtil.getMessage("how-many-sell", "" + items)); - } - // Add the new action - HashMap actions = plugin.getShopManager().getActions(); - Info info = new Info(shop.getLocation(), ShopAction.BUY, null, null, shop); - actions.put(p.getUniqueId(), info); - return; - } - // Handles creating shops - else if (!e.isCancelled() && shop == null && item != null && item.getType() != Material.AIR - && p.hasPermission("quickshop.create.sell") && Util.canBeShop(b,null,true) - && p.getGameMode() != GameMode.CREATIVE) { - if(e.isCancelled()) - return; - if(plugin.getConfig().getBoolean("shop.sneak-to-create")&&!p.isSneaking()) - return; - if (!plugin.getShopManager().canBuildShop(p, b, e.getBlockFace())) { - // As of the new checking system, most plugins will tell the - // player why they can't create a shop there. - // So telling them a message would cause spam etc. - Util.debugLog("Can't be shop"); - return; - } - if (Util.getSecondHalf(b) != null && !p.hasPermission("quickshop.create.double")) { - p.sendMessage(MsgUtil.getMessage("no-double-chests")); - return; - } - if (Util.isBlacklisted(item.getType()) - && !p.hasPermission("quickshop.bypass." + item.getType().name())) { - p.sendMessage(MsgUtil.getMessage("blacklisted-item")); - return; - } - if (b.getType()==Material.ENDER_CHEST) { - if(!p.hasPermission("quickshop.create.enderchest")) { - Util.debugLog("No permission"); - Util.debugLog(""+p.hasPermission("quickshop.create.enderchest")); - return; - } - } - if (!Util.canBeShop(b,e.getPlayer().getUniqueId(),false) && b.getType() != Material.WALL_SIGN) { - Util.debugLog("Can't create shop there"); - return; - } - // Finds out where the sign should be placed for the shop - Block last = null; - Location from = p.getLocation().clone(); - from.setY(b.getY()); - from.setPitch(0); - BlockIterator bIt = new BlockIterator(from, 0, 7); - while (bIt.hasNext()) { - Block n = bIt.next(); - if (n.equals(b)) - break; - last = n; - } - // Send creation menu. - Info info = new Info(b.getLocation(), ShopAction.CREATE, e.getItem(), last); - plugin.getShopManager().getActions().put(p.getUniqueId(), info); - p.sendMessage( - MsgUtil.getMessage("how-much-to-trade-for", MsgUtil.getItemi18n(Util.getName(info.getItem())))); - } - } else if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) - && e.getClickedBlock().getType() == Material.WALL_SIGN) { - Block block; - if (e.getClickedBlock().getType() == Material.WALL_SIGN) { - block = Util.getAttached(e.getClickedBlock()); - } else { - block = e.getClickedBlock(); - } - if (plugin.getShopManager().getShop(block.getLocation()) != null && plugin.getShopManager().getShop(block.getLocation()).getOwner().equals(e.getPlayer().getUniqueId())) { - if(plugin.getConfig().getBoolean("shop.sneak-to-control")&&!e.getPlayer().isSneaking()) - return; - MsgUtil.sendControlPanelInfo((CommandSender) e.getPlayer(), - plugin.getShopManager().getShop(block.getLocation())); - plugin.getShopManager().getShop(block.getLocation()).setSignText(); - } - } - - } - - @EventHandler(priority = EventPriority.HIGH,ignoreCancelled=true) - /** - * Waits for a player to move too far from a shop, then cancels the menu. - */ - public void onMove(PlayerMoveEvent e) { - if (e.isCancelled()) - return; - Info info = plugin.getShopManager().getActions().get(e.getPlayer().getUniqueId()); - if (info != null) { - Player p = e.getPlayer(); - Location loc1 = info.getLocation(); - Location loc2 = p.getLocation(); - if (loc1.getWorld() != loc2.getWorld() || loc1.distanceSquared(loc2) > 25) { - if (info.getAction() == ShopAction.CREATE) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - } else if (info.getAction() == ShopAction.BUY) { - p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); - } - plugin.getShopManager().getActions().remove(p.getUniqueId()); - return; - } - } - } - - @EventHandler(ignoreCancelled=true) - public void onTeleport(PlayerTeleportEvent e) { - PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); - onMove(me); - Util.inventoryCheck(e.getPlayer().getInventory()); - } - - @EventHandler(ignoreCancelled=true) - public void onJoin(PlayerJoinEvent e) { - // Notify the player any messages they were sent - if(plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) { - Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { - @Override - public void run() { - MsgUtil.flush(e.getPlayer()); - Util.inventoryCheck(e.getPlayer().getInventory()); - } - }, 60); - } - - } - - @EventHandler(ignoreCancelled=true) - public void onPlayerQuit(PlayerQuitEvent e) { - // Remove them from the menu - plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId()); - } - @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) - public void onInventoryClose(InventoryCloseEvent e) { - try { - Inventory inventory = e.getInventory(); - if (inventory == null) { - Util.debugLog("Inventory: null"); - return; - } - Location location = inventory.getLocation(); - if (location == null) { - Util.debugLog("Location: null"); - return; - } - Shop shop = plugin.getShopManager().getShop(location); - if (shop == null) { - return; - } - Util.debugLog("Shop: "+shop.toString()); - Util.debugLog("Updateing shops.."); - shop.setSignText(); - } catch (Throwable t) { - - } - } - -} +package org.maxgamer.quickshop.Listeners; + +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +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.inventory.InventoryCloseEvent; +import org.bukkit.event.player.*; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BlockIterator; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Shop.Info; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Shop.ShopAction; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Util; + +//import com.griefcraft.lwc.LWC; +//import com.griefcraft.lwc.LWCPlugin; + +import java.util.HashMap; +import java.util.UUID; + +public class PlayerListener implements Listener { + private QuickShop plugin; + + public PlayerListener(QuickShop plugin) { + this.plugin = plugin; + } + + /* + * Could be useful one day private LinkedList getParents(Class + * clazz){ LinkedList classes = new LinkedList(); + * + * while(clazz != null){ classes.add("Extends " + ChatColor.GREEN + + * clazz.getCanonicalName()); for(Class iface : clazz.getInterfaces()){ + * classes.add("Implements " + ChatColor.RED + iface.getCanonicalName()); + * classes.addAll(getParents(iface)); } + * + * clazz = clazz.getSuperclass(); } return classes; } + */ + /** + * Handles players left clicking a chest. Left click a NORMAL chest with item : + * Send creation menu Left click a SHOP chest : Send purchase menu + */ + @EventHandler(priority = EventPriority.MONITOR) + public void onClick(PlayerInteractEvent e) { + if (e.getAction().equals(Action.LEFT_CLICK_BLOCK)) { + Block b = e.getClickedBlock(); + if (!Util.canBeShop(b,null,true) && Util.isWallSign(b.getType())) { + return; + } + Player p = e.getPlayer(); + Location loc = b.getLocation(); + ItemStack item = e.getItem(); + // Get the shop + Shop shop = plugin.getShopManager().getShop(loc); + // If that wasn't a shop, search nearby shops + if (shop == null) { + Block attached = null; + + if (Util.isWallSign(b.getType())) { + attached = Util.getAttached(b); + if (attached != null) { + shop = plugin.getShopManager().getShop(attached.getLocation()); + } + } else if (b.getType() == Material.CHEST || b.getType() == Material.TRAPPED_CHEST) { + attached = Util.getSecondHalf(b); + if (attached != null) { + Shop secondHalfShop = plugin.getShopManager().getShop(attached.getLocation()); + if (secondHalfShop != null && !p.getUniqueId().equals(secondHalfShop.getOwner())) { + // If player not the owner of the shop, make him select the second half of the + // shop + // Otherwise owner will be able to create new double chest shop + shop = secondHalfShop; + } + } + } + } + // Purchase handling + if (shop != null && p.hasPermission("quickshop.use")) { + if(plugin.getConfig().getBoolean("shop.sneak-to-trade")&&!p.isSneaking()) + return; + shop.onClick(); + // Text menu + MsgUtil.sendShopInfo(p, shop); + shop.setSignText(); + if (shop.isSelling()) { + p.sendMessage(MsgUtil.getMessage("how-many-buy")); + } else { + int items = Util.countItems(p.getInventory(), shop.getItem()); + p.sendMessage(MsgUtil.getMessage("how-many-sell", "" + items)); + } + // Add the new action + HashMap actions = plugin.getShopManager().getActions(); + Info info = new Info(shop.getLocation(), ShopAction.BUY, null, null, shop); + actions.put(p.getUniqueId(), info); + return; + } + // Handles creating shops + else if (!e.isCancelled() && shop == null && item != null && item.getType() != Material.AIR + && p.hasPermission("quickshop.create.sell") && Util.canBeShop(b,null,true) + && p.getGameMode() != GameMode.CREATIVE) { + if(e.isCancelled()) + return; + if(plugin.getConfig().getBoolean("shop.sneak-to-create")&&!p.isSneaking()) + return; + if (!plugin.getShopManager().canBuildShop(p, b, e.getBlockFace())) { + // As of the new checking system, most plugins will tell the + // player why they can't create a shop there. + // So telling them a message would cause spam etc. + Util.debugLog("Can't be shop"); + return; + } + if (Util.getSecondHalf(b) != null && !p.hasPermission("quickshop.create.double")) { + p.sendMessage(MsgUtil.getMessage("no-double-chests")); + return; + } + if (Util.isBlacklisted(item.getType()) + && !p.hasPermission("quickshop.bypass." + item.getType().name())) { + p.sendMessage(MsgUtil.getMessage("blacklisted-item")); + return; + } + if (b.getType()==Material.ENDER_CHEST) { + if(!p.hasPermission("quickshop.create.enderchest")) { + Util.debugLog("No permission"); + Util.debugLog(""+p.hasPermission("quickshop.create.enderchest")); + return; + } + } + if (!Util.canBeShop(b,e.getPlayer().getUniqueId(),false) && Util.isWallSign(b.getType())) { + Util.debugLog("Can't create shop there"); + return; + } + // Finds out where the sign should be placed for the shop + Block last = null; + Location from = p.getLocation().clone(); + from.setY(b.getY()); + from.setPitch(0); + BlockIterator bIt = new BlockIterator(from, 0, 7); + while (bIt.hasNext()) { + Block n = bIt.next(); + if (n.equals(b)) + break; + last = n; + } + // Send creation menu. + Info info = new Info(b.getLocation(), ShopAction.CREATE, e.getItem(), last); + plugin.getShopManager().getActions().put(p.getUniqueId(), info); + p.sendMessage( + MsgUtil.getMessage("how-much-to-trade-for", MsgUtil.getItemi18n(Util.getName(info.getItem())))); + } + } else if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) + && Util.isWallSign(e.getClickedBlock().getType())) { + Block block; + if (Util.isWallSign(e.getClickedBlock().getType())) { + block = Util.getAttached(e.getClickedBlock()); + } else { + block = e.getClickedBlock(); + } + if (plugin.getShopManager().getShop(block.getLocation()) != null && plugin.getShopManager().getShop(block.getLocation()).getOwner().equals(e.getPlayer().getUniqueId())) { + if(plugin.getConfig().getBoolean("shop.sneak-to-control")&&!e.getPlayer().isSneaking()) + return; + MsgUtil.sendControlPanelInfo((CommandSender) e.getPlayer(), + plugin.getShopManager().getShop(block.getLocation())); + plugin.getShopManager().getShop(block.getLocation()).setSignText(); + } + } + + } + + @EventHandler(priority = EventPriority.HIGH,ignoreCancelled=true) + /** + * Waits for a player to move too far from a shop, then cancels the menu. + */ + public void onMove(PlayerMoveEvent e) { + if (e.isCancelled()) + return; + Info info = plugin.getShopManager().getActions().get(e.getPlayer().getUniqueId()); + if (info != null) { + Player p = e.getPlayer(); + Location loc1 = info.getLocation(); + Location loc2 = p.getLocation(); + if (loc1.getWorld() != loc2.getWorld() || loc1.distanceSquared(loc2) > 25) { + if (info.getAction() == ShopAction.CREATE) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + } else if (info.getAction() == ShopAction.BUY) { + p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); + } + plugin.getShopManager().getActions().remove(p.getUniqueId()); + return; + } + } + } + + @EventHandler(ignoreCancelled=true) + public void onTeleport(PlayerTeleportEvent e) { + PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); + onMove(me); + Util.inventoryCheck(e.getPlayer().getInventory()); + } + + @EventHandler(ignoreCancelled=true) + public void onJoin(PlayerJoinEvent e) { + // Notify the player any messages they were sent + if(plugin.getConfig().getBoolean("shop.auto-fetch-shop-messages")) { + Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { + @Override + public void run() { + MsgUtil.flush(e.getPlayer()); + Util.inventoryCheck(e.getPlayer().getInventory()); + } + }, 60); + } + + } + + @EventHandler(ignoreCancelled=true) + public void onPlayerQuit(PlayerQuitEvent e) { + // Remove them from the menu + plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId()); + } + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) + public void onInventoryClose(InventoryCloseEvent e) { + try { + Inventory inventory = e.getInventory(); + if (inventory == null) { + Util.debugLog("Inventory: null"); + return; + } + Location location = inventory.getLocation(); + if (location == null) { + Util.debugLog("Location: null"); + return; + } + Shop shop = plugin.getShopManager().getShop(location); + if (shop == null) { + return; + } + Util.debugLog("Shop: "+shop.toString()); + Util.debugLog("Updateing shops.."); + shop.setSignText(); + } catch (Throwable t) { + + } + } + +} diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java index 175c90213..f20758173 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ContainerShop.java @@ -541,7 +541,7 @@ public class ContainerShop implements Shop { final String signHeader = MsgUtil.getMessage("signs.header", ""); final String signHeader2 = MsgUtil.getMessage("sign.header", this.ownerName()); for (Block b : blocks) { - if (b.getType() != Material.WALL_SIGN) + if (Util.isWallSign(b.getType())) continue; if (!isAttached(b)) continue; @@ -565,7 +565,7 @@ public class ContainerShop implements Shop { } public boolean isAttached(Block b) { - if (b.getType() != Material.WALL_SIGN) + if (Util.isWallSign(b.getType())) new IllegalArgumentException(b + " Is not a sign!").printStackTrace(); return this.getLocation().getBlock().equals(Util.getAttached(b)); } diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java index 5d4139aef..3d080364b 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java @@ -1,781 +1,781 @@ -package org.maxgamer.quickshop.Shop; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.UUID; -import java.util.logging.Level; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -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.BlockState; -import org.bukkit.block.data.Waterlogged; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.Sign; -import org.bukkit.plugin.RegisteredListener; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Database.Database; -import org.maxgamer.quickshop.Database.DatabaseHelper; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Util; - -public class ShopManager { - QuickShop plugin = QuickShop.instance; - private HashMap actions = new HashMap(); - private HashMap>> shops = new HashMap>>(); - final private static ItemStack AIR = new ItemStack(Material.AIR); - - - public ShopManager(QuickShop plugin) { - this.plugin = plugin; - } - - public Database getDatabase() { - return plugin.getDB(); - } - - /** - * @return Returns the HashMap. Info contains what - * their last question etc was. - */ - public HashMap getActions() { - return this.actions; - } - - public void createShop(Shop shop,Info info) { - ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner())); - Bukkit.getPluginManager().callEvent(ssShopCreateEvent); - if(ssShopCreateEvent.isCancelled()) { - return; - } - Location loc = shop.getLocation(); - ItemStack item = shop.getItem(); - try { - // Write it to the database - DatabaseHelper.createShop(shop.getOwner().toString(), shop.getPrice(), item, (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); - // Add it to the world - addShop(loc.getWorld().getName(), shop); - } catch (Exception error) { - error.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Could not create shop! Changes will revert after a reboot!"); - } - //Create sign - if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) { - Material signType = info.getSignBlock().getType(); - if (signType != Material.AIR && signType != Material.CAVE_AIR && signType != Material.VOID_AIR && signType != Material.WATER) { - return; - } - boolean isWaterLogged = false; - if (info.getSignBlock().getType() == Material.WATER) - isWaterLogged = true; - final BlockState bs = info.getSignBlock().getState(); - final BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); - bs.setType(Material.WALL_SIGN); - if (isWaterLogged) { - Waterlogged waterable = (Waterlogged) bs.getBlockData(); - waterable.setWaterlogged(true); // Looks like sign directly put in water - } - Sign sign = (Sign) bs.getData(); - sign.setFacingDirection(bf); - bs.setData(sign); - bs.update(true); - shop.setSignText(); - - /* - * Block b = shop.getLocation().getBlock(); ItemFrame iFrame = (ItemFrame) - * b.getWorld().spawnEntity(b.getLocation(), EntityType.ITEM_FRAME); - * - * BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, - * BlockFace.SOUTH, BlockFace.WEST}; for(BlockFace face : faces){ if(face == bf) - * continue; //This is the sign's location iFrame.setFacingDirection(bf, true); - * //iFrame.setItem(shop.getItem()); ItemStack iStack = shop.getItem().clone(); - * iStack.setAmount(0); iFrame.setItem(iStack); /* Field handleField = - * iFrame.getClass().getField("entity"); handleField.setAccessible(true); Object - * handle = handleField.get(iFrame); - * - * ItemStack bukkitStack = shop.getItem(); - * - * Field itemStackHandle = - * - * Method setItemStack = handle.getClass().getMethod("a", Object.class); - * setItemStack. - */ - // } - } - } - - /** - * Loads the given shop into storage. This method is used for loading data - * from the database. Do not use this method to create a shop. - * - * @param world - * The world the shop is in - * @param shop - * The shop to load - */ - public void loadShop(String world, Shop shop) { - this.addShop(world, shop); - } - - /** - * Returns a hashmap of World -> Chunk -> Shop - * - * @return a hashmap of World -> Chunk -> Shop - */ - public HashMap>> getShops() { - return this.shops; - } - - /** - * Returns a hashmap of Chunk -> Shop - * - * @param world - * The name of the world (case sensitive) to get the list of - * shops from - * @return a hashmap of Chunk -> Shop - */ - public HashMap> getShops(String world) { - return this.shops.get(world); - } - - /** - * Returns a hashmap of Shops - * - * @param c - * The chunk to search. Referencing doesn't matter, only - * coordinates and world are used. - * @return - */ - public HashMap getShops(Chunk c) { - // long start = System.nanoTime(); - HashMap shops = getShops(c.getWorld().getName(), c.getX(), c.getZ()); - // long end = System.nanoTime(); - // plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) + - // "ms."); - return shops; - } - - public HashMap getShops(String world, int chunkX, int chunkZ) { - HashMap> inWorld = this.getShops(world); - if (inWorld == null) { - return null; - } - ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); - return inWorld.get(shopChunk); - } - - /** - * Gets a shop in a specific location - * - * @param loc - * The location to get the shop from - * @return The shop at that location - */ - public Shop getShop(Location loc) { - HashMap inChunk = getShops(loc.getChunk()); - if (inChunk == null) { - return null; - } - // We can do this because WorldListener updates the world reference so - // the world in loc is the same as world in inChunk.get(loc) - return inChunk.get(loc); - } - /** - * Adds a shop to the world. Does NOT require the chunk or world to be loaded - * - * @param world The name of the world - * @param shop The shop to add - */ - private void addShop(String world, Shop shop) { - - ShopLoadEvent shopLoadEvent = new ShopLoadEvent(shop); - Bukkit.getPluginManager().callEvent(shopLoadEvent); - if (shopLoadEvent.isCancelled()) { - return; - } - - HashMap> inWorld = this.getShops().get(world); - // There's no world storage yet. We need to create that hashmap. - if (inWorld == null) { - inWorld = new HashMap>(3); - // Put it in the data universe - this.getShops().put(world, inWorld); - } - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - // Get the chunk set from the world info - ShopChunk shopChunk = new ShopChunk(world, x, z); - HashMap inChunk = inWorld.get(shopChunk); - // That chunk data hasn't been created yet - Create it! - if (inChunk == null) { - inChunk = new HashMap(1); - // Put it in the world - inWorld.put(shopChunk, inChunk); - } - // Put the shop in its location in the chunk list. - inChunk.put(shop.getLocation(), shop); - } - - /** - * Removes a shop from the world. Does NOT remove it from the database. * - * REQUIRES * the world to be loaded - * - * @param shop - * The shop to remove - */ - public void removeShop(Shop shop) { - ShopUnloadEvent shopUnloadEvent = new ShopUnloadEvent(shop); - Bukkit.getPluginManager().callEvent(shopUnloadEvent); - Location loc = shop.getLocation(); - String world = loc.getWorld().getName(); - HashMap> inWorld = this.getShops().get(world); - int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); - int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); - ShopChunk shopChunk = new ShopChunk(world, x, z); - HashMap inChunk = inWorld.get(shopChunk); - inChunk.remove(loc); - } - - /** - * Removes all shops from memory and the world. Does not delete them from - * the database. Call this on plugin disable ONLY. - */ - public void clear() { - if (plugin.display) { - for (World world : Bukkit.getWorlds()) { - for (Chunk chunk : world.getLoadedChunks()) { - HashMap inChunk = this.getShops(chunk); - if (inChunk == null) - continue; - for (Shop shop : inChunk.values()) { - shop.onUnload(); - } - } - } - } - this.actions.clear(); - this.shops.clear(); - } - - /** - * Checks other plugins to make sure they can use the chest they're making a - * shop. - * - * @param p - * The player to check - * @param b - * The block to check - * @return True if they're allowed to place a shop there. - */ - public boolean canBuildShop(Player p, Block b, BlockFace bf) { - RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 - try { - if (plugin.openInvPlugin != null) { - for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) { - if (listener.getPlugin() == plugin.openInvPlugin) { - openInvRegisteredListener = listener; - PlayerInteractEvent.getHandlerList().unregister(listener); - break; - } - } - } - - - if (plugin.limit) { - int owned = 0; - if (!plugin.getConfig().getBoolean("limits.old-algorithm")) { - for (HashMap> shopmap : getShops().values()) { - for (HashMap shopLocs : shopmap.values()) { - for (Shop shop : shopLocs.values()) { - if (shop.getOwner().equals(p.getUniqueId())&&!shop.isUnlimited()) { - owned++; - } - } - } - } - }else { - Iterator it = getShopIterator(); - while (it.hasNext()) { - if (it.next().getOwner().equals(p.getUniqueId())) { - owned++; - } - } - } - - int max = plugin.getShopLimit(p); - if (owned + 1 > max) { - //p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!"); - p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned),String.valueOf(max))); - return false; - } - } - PlayerInteractEvent pie = new PlayerInteractEvent(p, Action.RIGHT_CLICK_BLOCK, AIR, b, bf); // PIE = PlayerInteractEvent - What else? - Bukkit.getPluginManager().callEvent(pie); - pie.getPlayer().closeInventory(); // If the player has chat open, this - // will close their chat. - if (pie.isCancelled()) { - return false; - } - ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); - Bukkit.getPluginManager().callEvent(spce); - if (spce.isCancelled()) { - return false; - } - } finally { - if (plugin.openInvPlugin != null && openInvRegisteredListener != null) { - PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener); - } - } - - return true; - } - - public void handleChat(final Player p, String msg) { - final String message = ChatColor.stripColor(msg); - // Use from the main thread, because Bukkit hates life - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - HashMap actions = getActions(); - // They wanted to do something. - Info info = actions.remove(p.getUniqueId()); - if (info == null) - return; // multithreaded means this can happen - if (info.getLocation().getWorld() != p.getLocation().getWorld()) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - return; - } - if (info.getLocation().distanceSquared(p.getLocation()) > 25) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - return; - } - /* Creation handling */ - if (info.getAction() == ShopAction.CREATE) { - actionCreate(p, actions, info, message); - /* Purchase Handling */ - } else if (info.getAction() == ShopAction.BUY) { - actionTrade(p, actions, info, message); - } - /* If it was already cancelled (from destroyed) */ - else { - return; // It was cancelled, go away. - } - } - }); - } - private void actionTrade(Player p, HashMap actions, Info info, String message) { - int amount = 0; - try { - amount = Integer.parseInt(message); - } catch (NumberFormatException e) { - p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); - return; - } - // Get the shop they interacted with - Shop shop = plugin.getShopManager().getShop(info.getLocation()); - // It's not valid anymore - if (shop == null || Util.canBeShop(info.getLocation().getBlock(),null,true) == false) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.getMessage("shop-has-changed")); - return; - } - if(shop.isBuying()) { - actionBuy(p, actions, info, message,shop,amount); - }else if (shop.isSelling()) { - actionSell(p, actions, info, message,shop,amount); - }else { - p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); - plugin.getLogger().warning("Shop data broken? Loc:"+shop.getLocation().toString()); - return; - } - } - - @SuppressWarnings("deprecation") - private void actionBuy(Player p, HashMap actions2, Info info, String message, Shop shop, int amount) { - int space = shop.getRemainingSpace(); - if(space == -1) - space=10000; - if (space < amount) { - p.sendMessage(MsgUtil.getMessage("shop-has-no-space", "" + space, shop.getDataName())); - return; - } - int count = Util.countItems(p.getInventory(), shop.getItem()); - // Not enough items - if (amount > count) { - p.sendMessage(MsgUtil.getMessage("you-dont-have-that-many-items", "" + count, shop.getDataName())); - return; - } - if (amount == 0) { - // Dumb. - MsgUtil.sendPurchaseSuccess(p, shop, amount); - return; - } else if (amount < 0) { - // & Dumber - p.sendMessage(MsgUtil.getMessage("negative-amount")); - return; - } - ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) - return; // Cancelled - // Money handling - if (!p.getUniqueId().equals(shop.getOwner())) { - // Don't tax them if they're purchasing from - // themselves. - // Do charge an amount of tax though. - double tax = plugin.getConfig().getDouble("tax"); - if (shop.getOwner().equals(p.getUniqueId())) { - tax = 0; - } - double total = amount * shop.getPrice(); - if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { - // Tries to check their balance nicely to see if - // they can afford it. - if (plugin.getEcon().getBalance(shop.getOwner()) < amount * shop.getPrice()) { - p.sendMessage(MsgUtil.getMessage("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); - return; - } - // Check for plugins faking econ.has(amount) - if (!plugin.getEcon().withdraw(shop.getOwner(), total)) { - p.sendMessage(MsgUtil.getMessage("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); - return; - } - if (tax != 0) { - plugin.getEcon().deposit(Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), total * tax); - } - } - // Give them the money after we know we succeeded - plugin.getEcon().deposit(p.getUniqueId(), total * (1 - tax)); - // Notify the owner of the purchase. - String msg = MsgUtil.getMessage("player-sold-to-your-store", p.getName(), "" + amount, shop.getDataName()); - if (space == amount) - msg += "\n" + MsgUtil.getMessage("shop-out-of-space", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ()); - MsgUtil.send(shop.getOwner(), msg,shop.isUnlimited()); - } - shop.buy(p, amount); - MsgUtil.sendSellSuccess(p, shop, amount); - plugin.log(p.getName() + " sold " + amount + " for " + (shop.getPrice() * amount) + " to " + shop.toString()); - shop.setSignText(); // Update the signs count - } - @SuppressWarnings("deprecation") - private void actionSell(Player p, HashMap actions2, Info info, String message, Shop shop2, int amount) { - Shop shop = plugin.getShopManager().getShop(info.getLocation()); - // It's not valid anymore - if (shop == null || Util.canBeShop(info.getLocation().getBlock(),null,true) == false) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.getMessage("shop-has-changed")); - return; - } - int stock = shop.getRemainingStock(); - if(stock==-1) - stock=10000; - if (stock < amount) { - p.sendMessage(MsgUtil.getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), shop.getDataName())); - return; - } - if (amount == 0) { - // Dumb. - MsgUtil.sendPurchaseSuccess(p, shop, amount); - return; - } else if (amount < 0) { - // & Dumber - p.sendMessage(MsgUtil.getMessage("negative-amount")); - return; - } - int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); - if (amount > pSpace) { - p.sendMessage(MsgUtil.getMessage("not-enough-space", "" + pSpace)); - return; - } - ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) - return; // Cancelled - // Money handling - if (!p.getUniqueId().equals(shop.getOwner())) { - // Check their balance. Works with *most* economy - // plugins* - if (plugin.getEcon().getBalance(p.getUniqueId()) < amount * shop.getPrice()) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getUniqueId())))); - return; - } - // Don't tax them if they're purchasing from - // themselves. - // Do charge an amount of tax though. - double tax = plugin.getConfig().getDouble("tax"); - if (shop.getOwner().equals(p.getUniqueId())) { - tax = 0; - } - - double total = amount * shop.getPrice(); - if (!plugin.getEcon().withdraw(p.getUniqueId(), total)) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getUniqueId())))); - return; - } - if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { - plugin.getEcon().deposit(shop.getOwner(), total * (1 - tax)); - if (tax != 0) { - plugin.getEcon().deposit(Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), total * tax); - } - } - // Notify the shop owner - if (plugin.getConfig().getBoolean("show-tax")) { - String msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, shop.getDataName(), Util.format((tax * total))); - if (stock == amount) - msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), shop.getDataName()); - MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); - } else { - String msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, shop.getDataName()); - if (stock == amount) - msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), shop.getDataName()); - MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); - } - // Transfers the item from A to B - - } - shop.sell(p, amount); - MsgUtil.sendPurchaseSuccess(p, shop, amount); - plugin.log(p.getName() + " bought " + amount + " for " + (shop.getPrice() * amount) + " from " + shop.toString()); - } - - @SuppressWarnings("deprecation") - private void actionCreate(Player p, HashMap actions2, Info info, String message) { - Util.debugLog("actionCreate"); - try { - // Checking the shop can be created - Util.debugLog("calling for protection check..."); - BlockBreakEvent be = new BlockBreakEvent(info.getLocation().getBlock(), p); - Bukkit.getPluginManager().callEvent(be); - if (be.isCancelled()) { - be.getPlayer().sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - if (plugin.getShopManager().getShop(info.getLocation()) != null) { - p.sendMessage(MsgUtil.getMessage("shop-already-owned")); - return; - } - if (Util.getSecondHalf(info.getLocation().getBlock()) != null - && !p.hasPermission("quickshop.create.double")) { - p.sendMessage(MsgUtil.getMessage("no-double-chests")); - return; - } - if (Util.canBeShop(info.getLocation().getBlock(), null, true) == false) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.getLocation().getWorld().getBlockAt(info.getLocation()).getType() == Material.ENDER_CHEST) { - if (!p.hasPermission("quickshop.create.enderchest")) - return; - } - - // allow-shop-without-space-for-sign check - if (plugin.getConfig().getBoolean("shop.auto-sign") - && !plugin.getConfig().getBoolean("allow-shop-without-space-for-sign")) { - if(info.getSignBlock() == null) { - p.sendMessage(MsgUtil.getMessage("failed-to-put-sign")); - return; - } - Material signType = info.getSignBlock().getType(); - if (signType != Material.AIR && signType != Material.CAVE_AIR - && signType != Material.VOID_AIR && signType != Material.WATER) { - p.sendMessage(MsgUtil.getMessage("failed-to-put-sign")); - return; - } - } - // Price per item - double price; - if (plugin.getConfig().getBoolean("whole-number-prices-only")) { - price = Integer.parseInt(message); - } else { - price = Double.parseDouble(message); - } - if (price < 0.01) { - p.sendMessage(MsgUtil.getMessage("price-too-cheap")); - return; - } - double price_limit = plugin.getConfig().getInt("shop.maximum-price"); - if(price_limit!=-1){ - if(price > price_limit){ - p.sendMessage(MsgUtil.getMessage("price-too-high",String.valueOf(price_limit))); - return; - } - } - // Check price restriction - Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); - if (priceRestriction != null) { - if (price < priceRestriction.getKey() || price > priceRestriction.getValue()) { - // p.sendMessage(ChatColor.RED+"Restricted prices for - // "+info.getItem().getType()+": min "+priceRestriction.getKey()+", max - // "+priceRestriction.getValue()); - p.sendMessage(MsgUtil.getMessage("restricted-prices", MsgUtil.getDisplayName(info.getItem()), - String.valueOf(priceRestriction.getKey()), String.valueOf(priceRestriction.getValue()))); - } - } - - double tax = plugin.getConfig().getDouble("shop.cost"); - // Tax refers to the cost to create a shop. Not actual - // tax, that would be silly - if (tax != 0 && plugin.getEcon().getBalance(p.getUniqueId()) < tax) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); - return; - } - // Create the sample shop. - Shop shop = new ContainerShop(info.getLocation(), price, info.getItem(), p.getUniqueId()); - shop.onLoad(); - ShopCreateEvent e = new ShopCreateEvent(shop, p); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) { - shop.onUnload(); - return; - } - - // This must be called after the event has been called. - // Else, if the event is cancelled, they won't get their - // money back. - if (tax != 0) { - if (!plugin.getEcon().withdraw(p.getUniqueId(), tax)) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); - shop.onUnload(); - return; - } - try { - plugin.getEcon().deposit( - Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), tax); - } catch (Exception e2) { - e2.printStackTrace(); - plugin.getLogger().log(Level.WARNING, - "QuickShop can't pay tax to account in config.yml,Please set tax account name to a exist player!"); - } - } - - /* The shop has hereforth been successfully created */ - createShop(shop, info); - Location loc = shop.getLocation(); - plugin.log(p.getName() + " created a " + MsgUtil.getDisplayName(shop.getItem()) + " shop at (" - + loc.getWorld().getName() + " - " + loc.getX() + "," + loc.getY() + "," + loc.getZ() + ")"); - if (!plugin.getConfig().getBoolean("shop.lock")) { - // Warn them if they haven't been warned since - // reboot - if (!plugin.warnings.contains(p.getName())) { - p.sendMessage(MsgUtil.getMessage("shops-arent-locked")); - plugin.warnings.add(p.getName()); - } - } - // Figures out which way we should put the sign on and - // sets its text. - - if (shop instanceof ContainerShop) { - ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) { - Shop nextTo = cs.getAttachedShop(); - if (nextTo.getPrice() > shop.getPrice()) { - // The one next to it must always be a - // buying shop. - p.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); - } - } - } - } - /* They didn't enter a number. */ - catch (NumberFormatException ex) { - p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); - return; - } - } - - /** - * Returns a new shop iterator object, allowing iteration over shops easily, - * instead of sorting through a 3D hashmap. - * - * @return a new shop iterator object. - */ - public Iterator getShopIterator() { - return new ShopIterator(); - } - - public String format(double d) { - return plugin.getEcon().format(d); - } - - public class ShopIterator implements Iterator { - private Iterator shops; - private Iterator> chunks; - private Iterator>> worlds; - private Shop current; - - public ShopIterator() { - worlds = getShops().values().iterator(); - } - - /** - * Returns true if there is still more shops to iterate over. - */ - @Override - public boolean hasNext() { - if (shops == null || !shops.hasNext()) { - if (chunks == null || !chunks.hasNext()) { - if (!worlds.hasNext()) { - return false; - } else { - chunks = worlds.next().values().iterator(); - return hasNext(); - } - } else { - shops = chunks.next().values().iterator(); - return hasNext(); - } - } - return true; - } - - /** - * Fetches the next shop. Throws NoSuchElementException if there are no - * more shops. - */ - @Override - public Shop next() { - if (shops == null || !shops.hasNext()) { - if (chunks == null || !chunks.hasNext()) { - if (!worlds.hasNext()) { - throw new NoSuchElementException("No more shops to iterate over!"); - } - chunks = worlds.next().values().iterator(); - } - shops = chunks.next().values().iterator(); - } - if (!shops.hasNext()) - return this.next(); // Skip to the next one (Empty iterator?) - current = shops.next(); - return current; - } - - /** - * Removes the current shop. This method will delete the shop from - * memory and the database. - */ - @Override - public void remove() { - current.delete(false); - shops.remove(); - } - } -} +package org.maxgamer.quickshop.Shop; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.UUID; +import java.util.logging.Level; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +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.BlockState; +import org.bukkit.block.data.Waterlogged; +import org.bukkit.entity.Player; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.Sign; +import org.bukkit.plugin.RegisteredListener; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Database.Database; +import org.maxgamer.quickshop.Database.DatabaseHelper; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Util; + +public class ShopManager { + QuickShop plugin = QuickShop.instance; + private HashMap actions = new HashMap(); + private HashMap>> shops = new HashMap>>(); + final private static ItemStack AIR = new ItemStack(Material.AIR); + + + public ShopManager(QuickShop plugin) { + this.plugin = plugin; + } + + public Database getDatabase() { + return plugin.getDB(); + } + + /** + * @return Returns the HashMap. Info contains what + * their last question etc was. + */ + public HashMap getActions() { + return this.actions; + } + + public void createShop(Shop shop,Info info) { + ShopCreateEvent ssShopCreateEvent = new ShopCreateEvent(shop, Bukkit.getPlayer(shop.getOwner())); + Bukkit.getPluginManager().callEvent(ssShopCreateEvent); + if(ssShopCreateEvent.isCancelled()) { + return; + } + Location loc = shop.getLocation(); + ItemStack item = shop.getItem(); + try { + // Write it to the database + DatabaseHelper.createShop(shop.getOwner().toString(), shop.getPrice(), item, (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID(), loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + // Add it to the world + addShop(loc.getWorld().getName(), shop); + } catch (Exception error) { + error.printStackTrace(); + plugin.getLogger().log(Level.WARNING, "Could not create shop! Changes will revert after a reboot!"); + } + //Create sign + if (info.getSignBlock() != null && plugin.getConfig().getBoolean("shop.auto-sign")) { + Material signType = info.getSignBlock().getType(); + if (signType != Material.AIR && signType != Material.CAVE_AIR && signType != Material.VOID_AIR && signType != Material.WATER) { + return; + } + boolean isWaterLogged = false; + if (info.getSignBlock().getType() == Material.WATER) + isWaterLogged = true; + final BlockState bs = info.getSignBlock().getState(); + final BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); + bs.setType(Material.OAK_WALL_SIGN); + if (isWaterLogged) { + Waterlogged waterable = (Waterlogged) bs.getBlockData(); + waterable.setWaterlogged(true); // Looks like sign directly put in water + } + Sign sign = (Sign) bs.getData(); + sign.setFacingDirection(bf); + bs.setData(sign); + bs.update(true); + shop.setSignText(); + + /* + * Block b = shop.getLocation().getBlock(); ItemFrame iFrame = (ItemFrame) + * b.getWorld().spawnEntity(b.getLocation(), EntityType.ITEM_FRAME); + * + * BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, + * BlockFace.SOUTH, BlockFace.WEST}; for(BlockFace face : faces){ if(face == bf) + * continue; //This is the sign's location iFrame.setFacingDirection(bf, true); + * //iFrame.setItem(shop.getItem()); ItemStack iStack = shop.getItem().clone(); + * iStack.setAmount(0); iFrame.setItem(iStack); /* Field handleField = + * iFrame.getClass().getField("entity"); handleField.setAccessible(true); Object + * handle = handleField.get(iFrame); + * + * ItemStack bukkitStack = shop.getItem(); + * + * Field itemStackHandle = + * + * Method setItemStack = handle.getClass().getMethod("a", Object.class); + * setItemStack. + */ + // } + } + } + + /** + * Loads the given shop into storage. This method is used for loading data + * from the database. Do not use this method to create a shop. + * + * @param world + * The world the shop is in + * @param shop + * The shop to load + */ + public void loadShop(String world, Shop shop) { + this.addShop(world, shop); + } + + /** + * Returns a hashmap of World -> Chunk -> Shop + * + * @return a hashmap of World -> Chunk -> Shop + */ + public HashMap>> getShops() { + return this.shops; + } + + /** + * Returns a hashmap of Chunk -> Shop + * + * @param world + * The name of the world (case sensitive) to get the list of + * shops from + * @return a hashmap of Chunk -> Shop + */ + public HashMap> getShops(String world) { + return this.shops.get(world); + } + + /** + * Returns a hashmap of Shops + * + * @param c + * The chunk to search. Referencing doesn't matter, only + * coordinates and world are used. + * @return + */ + public HashMap getShops(Chunk c) { + // long start = System.nanoTime(); + HashMap shops = getShops(c.getWorld().getName(), c.getX(), c.getZ()); + // long end = System.nanoTime(); + // plugin.getLogger().log(Level.WARNING, "Chunk lookup in " + ((end - start)/1000000.0) + + // "ms."); + return shops; + } + + public HashMap getShops(String world, int chunkX, int chunkZ) { + HashMap> inWorld = this.getShops(world); + if (inWorld == null) { + return null; + } + ShopChunk shopChunk = new ShopChunk(world, chunkX, chunkZ); + return inWorld.get(shopChunk); + } + + /** + * Gets a shop in a specific location + * + * @param loc + * The location to get the shop from + * @return The shop at that location + */ + public Shop getShop(Location loc) { + HashMap inChunk = getShops(loc.getChunk()); + if (inChunk == null) { + return null; + } + // We can do this because WorldListener updates the world reference so + // the world in loc is the same as world in inChunk.get(loc) + return inChunk.get(loc); + } + /** + * Adds a shop to the world. Does NOT require the chunk or world to be loaded + * + * @param world The name of the world + * @param shop The shop to add + */ + private void addShop(String world, Shop shop) { + + ShopLoadEvent shopLoadEvent = new ShopLoadEvent(shop); + Bukkit.getPluginManager().callEvent(shopLoadEvent); + if (shopLoadEvent.isCancelled()) { + return; + } + + HashMap> inWorld = this.getShops().get(world); + // There's no world storage yet. We need to create that hashmap. + if (inWorld == null) { + inWorld = new HashMap>(3); + // Put it in the data universe + this.getShops().put(world, inWorld); + } + // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT + // location rounded to the nearest 16. + int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + // Get the chunk set from the world info + ShopChunk shopChunk = new ShopChunk(world, x, z); + HashMap inChunk = inWorld.get(shopChunk); + // That chunk data hasn't been created yet - Create it! + if (inChunk == null) { + inChunk = new HashMap(1); + // Put it in the world + inWorld.put(shopChunk, inChunk); + } + // Put the shop in its location in the chunk list. + inChunk.put(shop.getLocation(), shop); + } + + /** + * Removes a shop from the world. Does NOT remove it from the database. * + * REQUIRES * the world to be loaded + * + * @param shop + * The shop to remove + */ + public void removeShop(Shop shop) { + ShopUnloadEvent shopUnloadEvent = new ShopUnloadEvent(shop); + Bukkit.getPluginManager().callEvent(shopUnloadEvent); + Location loc = shop.getLocation(); + String world = loc.getWorld().getName(); + HashMap> inWorld = this.getShops().get(world); + int x = (int) Math.floor((shop.getLocation().getBlockX()) / 16.0); + int z = (int) Math.floor((shop.getLocation().getBlockZ()) / 16.0); + ShopChunk shopChunk = new ShopChunk(world, x, z); + HashMap inChunk = inWorld.get(shopChunk); + inChunk.remove(loc); + } + + /** + * Removes all shops from memory and the world. Does not delete them from + * the database. Call this on plugin disable ONLY. + */ + public void clear() { + if (plugin.display) { + for (World world : Bukkit.getWorlds()) { + for (Chunk chunk : world.getLoadedChunks()) { + HashMap inChunk = this.getShops(chunk); + if (inChunk == null) + continue; + for (Shop shop : inChunk.values()) { + shop.onUnload(); + } + } + } + } + this.actions.clear(); + this.shops.clear(); + } + + /** + * Checks other plugins to make sure they can use the chest they're making a + * shop. + * + * @param p + * The player to check + * @param b + * The block to check + * @return True if they're allowed to place a shop there. + */ + public boolean canBuildShop(Player p, Block b, BlockFace bf) { + RegisteredListener openInvRegisteredListener = null; // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 + try { + if (plugin.openInvPlugin != null) { + for (RegisteredListener listener : PlayerInteractEvent.getHandlerList().getRegisteredListeners()) { + if (listener.getPlugin() == plugin.openInvPlugin) { + openInvRegisteredListener = listener; + PlayerInteractEvent.getHandlerList().unregister(listener); + break; + } + } + } + + + if (plugin.limit) { + int owned = 0; + if (!plugin.getConfig().getBoolean("limits.old-algorithm")) { + for (HashMap> shopmap : getShops().values()) { + for (HashMap shopLocs : shopmap.values()) { + for (Shop shop : shopLocs.values()) { + if (shop.getOwner().equals(p.getUniqueId())&&!shop.isUnlimited()) { + owned++; + } + } + } + } + }else { + Iterator it = getShopIterator(); + while (it.hasNext()) { + if (it.next().getOwner().equals(p.getUniqueId())) { + owned++; + } + } + } + + int max = plugin.getShopLimit(p); + if (owned + 1 > max) { + //p.sendMessage(ChatColor.RED + "You have already created a maximum of " + owned + "/" + max + " shops!"); + p.sendMessage(MsgUtil.getMessage("reached-maximum-can-create", String.valueOf(owned),String.valueOf(max))); + return false; + } + } + PlayerInteractEvent pie = new PlayerInteractEvent(p, Action.RIGHT_CLICK_BLOCK, AIR, b, bf); // PIE = PlayerInteractEvent - What else? + Bukkit.getPluginManager().callEvent(pie); + pie.getPlayer().closeInventory(); // If the player has chat open, this + // will close their chat. + if (pie.isCancelled()) { + return false; + } + ShopPreCreateEvent spce = new ShopPreCreateEvent(p, b.getLocation()); + Bukkit.getPluginManager().callEvent(spce); + if (spce.isCancelled()) { + return false; + } + } finally { + if (plugin.openInvPlugin != null && openInvRegisteredListener != null) { + PlayerInteractEvent.getHandlerList().register(openInvRegisteredListener); + } + } + + return true; + } + + public void handleChat(final Player p, String msg) { + final String message = ChatColor.stripColor(msg); + // Use from the main thread, because Bukkit hates life + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + HashMap actions = getActions(); + // They wanted to do something. + Info info = actions.remove(p.getUniqueId()); + if (info == null) + return; // multithreaded means this can happen + if (info.getLocation().getWorld() != p.getLocation().getWorld()) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + return; + } + if (info.getLocation().distanceSquared(p.getLocation()) > 25) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + return; + } + /* Creation handling */ + if (info.getAction() == ShopAction.CREATE) { + actionCreate(p, actions, info, message); + /* Purchase Handling */ + } else if (info.getAction() == ShopAction.BUY) { + actionTrade(p, actions, info, message); + } + /* If it was already cancelled (from destroyed) */ + else { + return; // It was cancelled, go away. + } + } + }); + } + private void actionTrade(Player p, HashMap actions, Info info, String message) { + int amount = 0; + try { + amount = Integer.parseInt(message); + } catch (NumberFormatException e) { + p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); + return; + } + // Get the shop they interacted with + Shop shop = plugin.getShopManager().getShop(info.getLocation()); + // It's not valid anymore + if (shop == null || Util.canBeShop(info.getLocation().getBlock(),null,true) == false) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.getMessage("shop-has-changed")); + return; + } + if(shop.isBuying()) { + actionBuy(p, actions, info, message,shop,amount); + }else if (shop.isSelling()) { + actionSell(p, actions, info, message,shop,amount); + }else { + p.sendMessage(MsgUtil.getMessage("shop-purchase-cancelled")); + plugin.getLogger().warning("Shop data broken? Loc:"+shop.getLocation().toString()); + return; + } + } + + @SuppressWarnings("deprecation") + private void actionBuy(Player p, HashMap actions2, Info info, String message, Shop shop, int amount) { + int space = shop.getRemainingSpace(); + if(space == -1) + space=10000; + if (space < amount) { + p.sendMessage(MsgUtil.getMessage("shop-has-no-space", "" + space, shop.getDataName())); + return; + } + int count = Util.countItems(p.getInventory(), shop.getItem()); + // Not enough items + if (amount > count) { + p.sendMessage(MsgUtil.getMessage("you-dont-have-that-many-items", "" + count, shop.getDataName())); + return; + } + if (amount == 0) { + // Dumb. + MsgUtil.sendPurchaseSuccess(p, shop, amount); + return; + } else if (amount < 0) { + // & Dumber + p.sendMessage(MsgUtil.getMessage("negative-amount")); + return; + } + ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) + return; // Cancelled + // Money handling + if (!p.getUniqueId().equals(shop.getOwner())) { + // Don't tax them if they're purchasing from + // themselves. + // Do charge an amount of tax though. + double tax = plugin.getConfig().getDouble("tax"); + if (shop.getOwner().equals(p.getUniqueId())) { + tax = 0; + } + double total = amount * shop.getPrice(); + if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { + // Tries to check their balance nicely to see if + // they can afford it. + if (plugin.getEcon().getBalance(shop.getOwner()) < amount * shop.getPrice()) { + p.sendMessage(MsgUtil.getMessage("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); + return; + } + // Check for plugins faking econ.has(amount) + if (!plugin.getEcon().withdraw(shop.getOwner(), total)) { + p.sendMessage(MsgUtil.getMessage("the-owner-cant-afford-to-buy-from-you", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(shop.getOwner())))); + return; + } + if (tax != 0) { + plugin.getEcon().deposit(Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), total * tax); + } + } + // Give them the money after we know we succeeded + plugin.getEcon().deposit(p.getUniqueId(), total * (1 - tax)); + // Notify the owner of the purchase. + String msg = MsgUtil.getMessage("player-sold-to-your-store", p.getName(), "" + amount, shop.getDataName()); + if (space == amount) + msg += "\n" + MsgUtil.getMessage("shop-out-of-space", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ()); + MsgUtil.send(shop.getOwner(), msg,shop.isUnlimited()); + } + shop.buy(p, amount); + MsgUtil.sendSellSuccess(p, shop, amount); + plugin.log(p.getName() + " sold " + amount + " for " + (shop.getPrice() * amount) + " to " + shop.toString()); + shop.setSignText(); // Update the signs count + } + @SuppressWarnings("deprecation") + private void actionSell(Player p, HashMap actions2, Info info, String message, Shop shop2, int amount) { + Shop shop = plugin.getShopManager().getShop(info.getLocation()); + // It's not valid anymore + if (shop == null || Util.canBeShop(info.getLocation().getBlock(),null,true) == false) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.getMessage("shop-has-changed")); + return; + } + int stock = shop.getRemainingStock(); + if(stock==-1) + stock=10000; + if (stock < amount) { + p.sendMessage(MsgUtil.getMessage("shop-stock-too-low", "" + shop.getRemainingStock(), shop.getDataName())); + return; + } + if (amount == 0) { + // Dumb. + MsgUtil.sendPurchaseSuccess(p, shop, amount); + return; + } else if (amount < 0) { + // & Dumber + p.sendMessage(MsgUtil.getMessage("negative-amount")); + return; + } + int pSpace = Util.countSpace(p.getInventory(), shop.getItem()); + if (amount > pSpace) { + p.sendMessage(MsgUtil.getMessage("not-enough-space", "" + pSpace)); + return; + } + ShopPurchaseEvent e = new ShopPurchaseEvent(shop, p, amount); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) + return; // Cancelled + // Money handling + if (!p.getUniqueId().equals(shop.getOwner())) { + // Check their balance. Works with *most* economy + // plugins* + if (plugin.getEcon().getBalance(p.getUniqueId()) < amount * shop.getPrice()) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getUniqueId())))); + return; + } + // Don't tax them if they're purchasing from + // themselves. + // Do charge an amount of tax though. + double tax = plugin.getConfig().getDouble("tax"); + if (shop.getOwner().equals(p.getUniqueId())) { + tax = 0; + } + + double total = amount * shop.getPrice(); + if (!plugin.getEcon().withdraw(p.getUniqueId(), total)) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getUniqueId())))); + return; + } + if (!shop.isUnlimited() || plugin.getConfig().getBoolean("shop.pay-unlimited-shop-owners")) { + plugin.getEcon().deposit(shop.getOwner(), total * (1 - tax)); + if (tax != 0) { + plugin.getEcon().deposit(Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), total * tax); + } + } + // Notify the shop owner + if (plugin.getConfig().getBoolean("show-tax")) { + String msg = MsgUtil.getMessage("player-bought-from-your-store-tax", p.getName(), "" + amount, shop.getDataName(), Util.format((tax * total))); + if (stock == amount) + msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), shop.getDataName()); + MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); + } else { + String msg = MsgUtil.getMessage("player-bought-from-your-store", p.getName(), "" + amount, shop.getDataName()); + if (stock == amount) + msg += "\n" + MsgUtil.getMessage("shop-out-of-stock", "" + shop.getLocation().getBlockX(), "" + shop.getLocation().getBlockY(), "" + shop.getLocation().getBlockZ(), shop.getDataName()); + MsgUtil.send(shop.getOwner(), msg, shop.isUnlimited()); + } + // Transfers the item from A to B + + } + shop.sell(p, amount); + MsgUtil.sendPurchaseSuccess(p, shop, amount); + plugin.log(p.getName() + " bought " + amount + " for " + (shop.getPrice() * amount) + " from " + shop.toString()); + } + + @SuppressWarnings("deprecation") + private void actionCreate(Player p, HashMap actions2, Info info, String message) { + Util.debugLog("actionCreate"); + try { + // Checking the shop can be created + Util.debugLog("calling for protection check..."); + BlockBreakEvent be = new BlockBreakEvent(info.getLocation().getBlock(), p); + Bukkit.getPluginManager().callEvent(be); + if (be.isCancelled()) { + be.getPlayer().sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + if (plugin.getShopManager().getShop(info.getLocation()) != null) { + p.sendMessage(MsgUtil.getMessage("shop-already-owned")); + return; + } + if (Util.getSecondHalf(info.getLocation().getBlock()) != null + && !p.hasPermission("quickshop.create.double")) { + p.sendMessage(MsgUtil.getMessage("no-double-chests")); + return; + } + if (Util.canBeShop(info.getLocation().getBlock(), null, true) == false) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.getLocation().getWorld().getBlockAt(info.getLocation()).getType() == Material.ENDER_CHEST) { + if (!p.hasPermission("quickshop.create.enderchest")) + return; + } + + // allow-shop-without-space-for-sign check + if (plugin.getConfig().getBoolean("shop.auto-sign") + && !plugin.getConfig().getBoolean("allow-shop-without-space-for-sign")) { + if(info.getSignBlock() == null) { + p.sendMessage(MsgUtil.getMessage("failed-to-put-sign")); + return; + } + Material signType = info.getSignBlock().getType(); + if (signType != Material.AIR && signType != Material.CAVE_AIR + && signType != Material.VOID_AIR && signType != Material.WATER) { + p.sendMessage(MsgUtil.getMessage("failed-to-put-sign")); + return; + } + } + // Price per item + double price; + if (plugin.getConfig().getBoolean("whole-number-prices-only")) { + price = Integer.parseInt(message); + } else { + price = Double.parseDouble(message); + } + if (price < 0.01) { + p.sendMessage(MsgUtil.getMessage("price-too-cheap")); + return; + } + double price_limit = plugin.getConfig().getInt("shop.maximum-price"); + if(price_limit!=-1){ + if(price > price_limit){ + p.sendMessage(MsgUtil.getMessage("price-too-high",String.valueOf(price_limit))); + return; + } + } + // Check price restriction + Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); + if (priceRestriction != null) { + if (price < priceRestriction.getKey() || price > priceRestriction.getValue()) { + // p.sendMessage(ChatColor.RED+"Restricted prices for + // "+info.getItem().getType()+": min "+priceRestriction.getKey()+", max + // "+priceRestriction.getValue()); + p.sendMessage(MsgUtil.getMessage("restricted-prices", MsgUtil.getDisplayName(info.getItem()), + String.valueOf(priceRestriction.getKey()), String.valueOf(priceRestriction.getValue()))); + } + } + + double tax = plugin.getConfig().getDouble("shop.cost"); + // Tax refers to the cost to create a shop. Not actual + // tax, that would be silly + if (tax != 0 && plugin.getEcon().getBalance(p.getUniqueId()) < tax) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); + return; + } + // Create the sample shop. + Shop shop = new ContainerShop(info.getLocation(), price, info.getItem(), p.getUniqueId()); + shop.onLoad(); + ShopCreateEvent e = new ShopCreateEvent(shop, p); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) { + shop.onUnload(); + return; + } + + // This must be called after the event has been called. + // Else, if the event is cancelled, they won't get their + // money back. + if (tax != 0) { + if (!plugin.getEcon().withdraw(p.getUniqueId(), tax)) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); + shop.onUnload(); + return; + } + try { + plugin.getEcon().deposit( + Bukkit.getOfflinePlayer(plugin.getConfig().getString("tax-account")).getUniqueId(), tax); + } catch (Exception e2) { + e2.printStackTrace(); + plugin.getLogger().log(Level.WARNING, + "QuickShop can't pay tax to account in config.yml,Please set tax account name to a exist player!"); + } + } + + /* The shop has hereforth been successfully created */ + createShop(shop, info); + Location loc = shop.getLocation(); + plugin.log(p.getName() + " created a " + MsgUtil.getDisplayName(shop.getItem()) + " shop at (" + + loc.getWorld().getName() + " - " + loc.getX() + "," + loc.getY() + "," + loc.getZ() + ")"); + if (!plugin.getConfig().getBoolean("shop.lock")) { + // Warn them if they haven't been warned since + // reboot + if (!plugin.warnings.contains(p.getName())) { + p.sendMessage(MsgUtil.getMessage("shops-arent-locked")); + plugin.warnings.add(p.getName()); + } + } + // Figures out which way we should put the sign on and + // sets its text. + + if (shop instanceof ContainerShop) { + ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) { + Shop nextTo = cs.getAttachedShop(); + if (nextTo.getPrice() > shop.getPrice()) { + // The one next to it must always be a + // buying shop. + p.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); + } + } + } + } + /* They didn't enter a number. */ + catch (NumberFormatException ex) { + p.sendMessage(MsgUtil.getMessage("shop-creation-cancelled")); + return; + } + } + + /** + * Returns a new shop iterator object, allowing iteration over shops easily, + * instead of sorting through a 3D hashmap. + * + * @return a new shop iterator object. + */ + public Iterator getShopIterator() { + return new ShopIterator(); + } + + public String format(double d) { + return plugin.getEcon().format(d); + } + + public class ShopIterator implements Iterator { + private Iterator shops; + private Iterator> chunks; + private Iterator>> worlds; + private Shop current; + + public ShopIterator() { + worlds = getShops().values().iterator(); + } + + /** + * Returns true if there is still more shops to iterate over. + */ + @Override + public boolean hasNext() { + if (shops == null || !shops.hasNext()) { + if (chunks == null || !chunks.hasNext()) { + if (!worlds.hasNext()) { + return false; + } else { + chunks = worlds.next().values().iterator(); + return hasNext(); + } + } else { + shops = chunks.next().values().iterator(); + return hasNext(); + } + } + return true; + } + + /** + * Fetches the next shop. Throws NoSuchElementException if there are no + * more shops. + */ + @Override + public Shop next() { + if (shops == null || !shops.hasNext()) { + if (chunks == null || !chunks.hasNext()) { + if (!worlds.hasNext()) { + throw new NoSuchElementException("No more shops to iterate over!"); + } + chunks = worlds.next().values().iterator(); + } + shops = chunks.next().values().iterator(); + } + if (!shops.hasNext()) + return this.next(); // Skip to the next one (Empty iterator?) + current = shops.next(); + return current; + } + + /** + * Removes the current shop. This method will delete the shop from + * memory and the database. + */ + @Override + public void remove() { + current.delete(false); + shops.remove(); + } + } +} diff --git a/src/main/java/org/maxgamer/quickshop/Util/Util.java b/src/main/java/org/maxgamer/quickshop/Util/Util.java index 30161af14..4685bf047 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Util.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Util.java @@ -1,949 +1,967 @@ -package org.maxgamer.quickshop.Util; - -import net.md_5.bungee.api.chat.ComponentBuilder; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.*; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.material.Sign; -import org.bukkit.potion.PotionEffect; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Shop.DisplayItem; -import org.maxgamer.quickshop.Shop.Shop; - -import java.io.*; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.AbstractMap.SimpleEntry; -import java.util.*; -import java.util.Map.Entry; - -/** - * @author MACHENIKE - * - */ -public class Util { - private static final EnumSet blacklist = EnumSet.noneOf(Material.class); - private static final EnumSet shoppables = EnumSet.noneOf(Material.class); - private static final EnumMap> restrictedPrices = new EnumMap>(Material.class); - private static QuickShop plugin; - private static Method storageContents; - static Map timerMap = new HashMap(); - protected static boolean devMode; - public String boolean2String(boolean bool) { - if (bool) { - return "Enabled"; - } else { - return "Disabled"; - } - } - public static void initialize() { - blacklist.clear(); - shoppables.clear(); - restrictedPrices.clear(); - - plugin = QuickShop.instance; - devMode = plugin.getConfig().getBoolean("dev-mode"); - for (String s : plugin.getConfig().getStringList("shop-blocks")) { - Material mat = Material.matchMaterial(s.toUpperCase()); - if (mat == null) { - try { - mat = Material.matchMaterial(s); - } catch (NumberFormatException e) { - } - } - if (mat == null) { - plugin.getLogger().info("Invalid shop-block: " + s); - } else { - shoppables.add(mat); - } - } - List configBlacklist = plugin.getConfig().getStringList("blacklist"); - for (String s : configBlacklist) { - Material mat = Material.getMaterial(s.toUpperCase()); - if (mat == null) { - mat = Material.matchMaterial(s); - if (mat == null) { - plugin.getLogger().info(s + " is not a valid material. Check your spelling or ID"); - continue; - } - } - blacklist.add(mat); - } - - for (String s : plugin.getConfig().getStringList("price-restriction")) { - String[] sp = s.split(";"); - if (sp.length==3) { - try { - Material mat = Material.matchMaterial(sp[0]); - if (mat == null) { - throw new Exception(); - } - - restrictedPrices.put(mat, new SimpleEntry(Double.valueOf(sp[1]), Double.valueOf(sp[2]))); - } catch (Exception e) { - plugin.getLogger().info("Invalid price restricted material: " + s); - } - } - } - - try { - storageContents = Inventory.class.getMethod("getStorageContents"); - } catch (Exception e) { - try { - storageContents = Inventory.class.getMethod("getContents"); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - } - } - - /** Return an entry with min and max prices, but null if there isn't a price restriction */ - public static Entry getPriceRestriction(Material material) { - return restrictedPrices.get(material); - } - @SuppressWarnings("deprecation") - public static boolean isTransparent(Material m) { - boolean trans = m.isTransparent(); - return trans; - } - - public static boolean isShoppables(Material material) { - if(shoppables.contains(material)) { - return true; - }else { - return false; - } - - - } - - public static void parseColours(YamlConfiguration config) { - Set keys = config.getKeys(true); - for (String key : keys) { - String filtered = config.getString(key); - if (filtered.startsWith("MemorySection")) { - continue; - } - filtered = ChatColor.translateAlternateColorCodes('&', filtered); - config.set(key, filtered); - } - } - public static String parseColours(String text) { - text = ChatColor.translateAlternateColorCodes('&', text); - return text; - } - /** - * Returns true if the given block could be used to make a shop out of. - * - * @param b The block to check, Possibly a chest, dispenser, etc. player The player, can be null if onlyCheck=true, onlyCheck The option to disable check AreaShop use player. - * @return True if it can be made into a shop, otherwise false. - */ - public static boolean canBeShop(Block b,UUID player, boolean onlyCheck) { - BlockState bs = b.getState(); - if ((bs instanceof InventoryHolder == false) && b.getState().getType() != Material.ENDER_CHEST) { - return false; - } - if (b.getState().getType() == Material.ENDER_CHEST) { - if (plugin.openInvPlugin == null) { - Util.debugLog("OpenInv not loaded"); - return false; - } else { - return shoppables.contains(bs.getType()); - } - } - return shoppables.contains(bs.getType()); - - } - - /** - * Gets the percentage (Without trailing %) damage on a tool. - * - * @param item - * The ItemStack of tools to check - * @return The percentage 'health' the tool has. (Opposite of total damage) - */ - public static String getToolPercentage(ItemStack item) { - double dura = ((Damageable)item.getItemMeta()).getDamage();; - double max = item.getType().getMaxDurability(); - DecimalFormat formatter = new DecimalFormat("0"); - return formatter.format((1 - dura / max) * 100.0); - } - - /** - * Returns the chest attached to the given chest. The given block must be a - * chest. - * - * @param b - * The chest to check. - * @return the block which is also a chest and connected to b. - */ - /** @TODO 1.13+ compatibility */ - public static Block getSecondHalf_old(Block b) { - if (b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST) - return null; - Block[] blocks = new Block[4]; - blocks[0] = b.getRelative(1, 0, 0); - blocks[1] = b.getRelative(-1, 0, 0); - blocks[2] = b.getRelative(0, 0, 1); - blocks[3] = b.getRelative(0, 0, -1); - for (Block c : blocks) { - if (c.getType() == b.getType()) { - return c; - } - } - return null; - } - - /** - * Returns the chest attached to the given chest. The given block must be a - * chest. - * - * @param b - * The chest to check. - * @return the block which is also a chest and connected to b. - */ - public static Block getSecondHalf(Block b) { - Util.debugLog("Getting Second Half of DoubleChest at "+b.getLocation().toString()); - if(b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST){ - Util.debugLog("No matched type: "+b.getType().name()); - return null; - } - Chest oneSideOfChest = (Chest)b.getState(); - InventoryHolder chestHolder = oneSideOfChest.getInventory().getHolder(); - if(chestHolder instanceof DoubleChest){ - DoubleChest doubleChest = (DoubleChest)chestHolder; - InventoryHolder left = doubleChest.getLeftSide(); - InventoryHolder right = doubleChest.getRightSide(); - - Chest leftC = (Chest)left; - Chest rightC = (Chest)right; - Util.debugLog("Double chest match checker: "); - Util.debugLog("Find args: "+b.getLocation().toString()); - Util.debugLog("Left: "+leftC.getLocation().toString()); - Util.debugLog("Right: "+rightC.getLocation().toString()); - if(equalsBlockStateLocation(oneSideOfChest, leftC)) { - Util.debugLog("Clicked left chest"); - return rightC.getBlock(); - } - if(equalsBlockStateLocation(oneSideOfChest, leftC)) { - Util.debugLog("Clicked right chest"); - return leftC.getBlock(); - } - Util.debugLog("No matched double chest check but pass the DoubleChest Inventory check"); - return null; - }else{ - Util.debugLog("No matched DoubleChest: "+b.toString()); - return null; - } - } - - private static final boolean equalsBlockStateLocation(BlockState b1, BlockState b2) { - return b1.getX() == b2.getX() && b1.getY() == b2.getY() && b1.getZ() == b2.getZ(); - } - - public static boolean location3DEqual(Location loc1, Location loc2){ - if(loc1.getWorld().getName() != loc2.getWorld().getName()) - return false; - if(loc1.getBlockX() != loc2.getBlockX()) - return false; - if(loc1.getBlockY() != loc2.getBlockY()) - return false; - if(loc1.getBlockZ() != loc2.getBlockZ()) - return false; - return true; - } - /** - * Checks whether someone else's shop is within reach of a hopper being placed by a player. - * - * @param b - * The block being placed. - * @param p - * The player performing the action. - * @return true if a nearby shop was found, false otherwise. - */ - public static boolean isOtherShopWithinHopperReach(Block b, Player p) { - // Check 5 relative positions that can be affected by a hopper: behind, in front of, to the right, - // to the left and underneath. - Block[] blocks = new Block[5]; - blocks[0] = b.getRelative(0, 0, -1); - blocks[1] = b.getRelative(0, 0, 1); - blocks[2] = b.getRelative(1, 0, 0); - blocks[3] = b.getRelative(-1, 0, 0); - blocks[4] = b.getRelative(0, 1, 0); - for (Block c : blocks) { - Shop firstShop = plugin.getShopManager().getShop(c.getLocation()); - // If firstShop is null but is container, it can be used to drain contents from a shop created - // on secondHalf. - Block secondHalf = getSecondHalf(c); - Shop secondShop = secondHalf == null ? null : plugin.getShopManager().getShop(secondHalf.getLocation()); - if (firstShop != null && !p.getUniqueId().equals(firstShop.getOwner()) - || secondShop != null && !p.getUniqueId().equals(secondShop.getOwner())) { - return true; - } - } - return false; - } - - /** - * Covert ItemStack to YAML string. - * @param ItemStack iStack - * @return String serialized itemStack - */ - public static String serialize(ItemStack iStack) { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.set("item", iStack); - return cfg.saveToString(); - } - /** - * Covert YAML string to ItemStack. - * @param String serialized itemStack - * @return ItemStack iStack - */ - public static ItemStack deserialize(String config) throws InvalidConfigurationException { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.loadFromString(config); - cfg.getString("item"); - ItemStack stack = cfg.getItemStack("item"); - return stack; - } - - /** - * Fetches an ItemStack's name - For example, converting INK_SAC:11 to - * Dandellion Yellow, or WOOL:14 to Red Wool - * - * @param itemStack - * The itemstack to fetch the name of - * @return The human readable item name. - */ - public static String getName(ItemStack itemStack) { -// if (NMS.isPotion(itemStack.getType())) { -// return CustomPotionsName.getFullName(itemStack); -// } - String vanillaName = itemStack.getType().name(); - return prettifyText(vanillaName); - } - - /** - * Converts a name like IRON_INGOT into Iron Ingot to improve readability - * - * @param ugly - * The string such as IRON_INGOT - * @return A nicer version, such as Iron Ingot - * - */ - public static String prettifyText(String ugly) { - String[] nameParts = ugly.split("_"); - if (nameParts.length==1) { - return firstUppercase(ugly); - } - - StringBuilder sb=new StringBuilder(); - for (String part : nameParts) { - sb.append(firstUppercase(part)+" "); - } - - return sb.toString(); - } - /** - * Get item's sign name for display on the sign. - * @param ItemStack itemStack - * @return String ItemOnSignName - */ - // Let's make very long names shorter for our sign - public static String getNameForSign(ItemStack itemStack) { -// if (NMS.isPotion(itemStack.getType())) { -// return CustomPotionsName.getSignName(itemStack); -// } - - ItemStack is = itemStack.clone(); - is.setAmount(1); - - if(is.hasItemMeta()) { - if(is.getItemMeta().hasDisplayName()) { - return is.getItemMeta().getDisplayName(); - } - } - - String name = MsgUtil.getItemi18n(itemStack.getType().name()).trim(); - - String[] nameParts = name.split("_"); - if (nameParts.length==1) { - return firstUppercase(nameParts[0]); - } - - for (int i=0; i16) { - nameParts[i] = nameParts[i].substring(0, 1)+"."; - } else { - nameParts[i] = firstUppercase(nameParts[i]); - } - } - - nameParts[nameParts.length-1] = firstUppercase(nameParts[nameParts.length-1]); - - return StringUtils.join(nameParts); - } - - public static String firstUppercase(String string) { - if (string.length()>1) { - return Character.toUpperCase(string.charAt(0))+string.substring(1).toLowerCase(); - } else { - return string.toUpperCase(); - } - } - - - public static String toRomain(Integer value) { - return toRoman(value.intValue()); - } - - private static final String[] ROMAN = { "X", "IX", "V", "IV", "I" }; - private static final int[] DECIMAL = { 10, 9, 5, 4, 1 }; - - /** - * Converts the given number to roman numerals. If the number is >= 40 or <= - * 0, it will just return the number as a string. - * - * @param n - * The number to convert - * @return The roman numeral representation of this number, or the number in - * decimal form as a string if n <= 0 || n >= 40. - */ - public static String toRoman(int n) { - if (n <= 0 || n >= 40) - return "" + n; - String roman = ""; - for (int i = 0; i < ROMAN.length; i++) { - while (n >= DECIMAL[i]) { - n -= DECIMAL[i]; - roman += ROMAN[i]; - } - } - return roman; - } - /** - * @param mat - * The material to check - * @return Returns true if the item is a tool (Has durability) or false if - * it doesn't. - */ - public static boolean isTool(Material mat) { - if(mat.getMaxDurability()==0){ - return false; - }else{ - return true; - } - } - - /** - * Compares two items to each other. Returns true if they match. - * - * @param stack1 - * The first item stack - * @param stack2 - * The second item stack - * @return true if the itemstacks match. (Material, durability, enchants, name) - */ - public static boolean matches(ItemStack stack1, ItemStack stack2) { - if (stack1 == stack2) - return true; // Referring to the same thing, or both are null. - if (stack1 == null || stack2 == null) - return false; // One of them is null (Can't be both, see above) - if (stack1.getType() != stack2.getType()) - return false; // Not the same material - if (((Damageable)stack1.getItemMeta()).getDamage() != ((Damageable)stack2.getItemMeta()).getDamage()) - return false; // Not the same durability - if (!stack1.getEnchantments().equals(stack2.getEnchantments())) - return false; // They have the same enchants - if (stack1.getItemMeta().hasDisplayName() || stack2.getItemMeta().hasDisplayName()) { - if (stack1.getItemMeta().hasDisplayName() && stack2.getItemMeta().hasDisplayName()) { - if (!stack1.getItemMeta().getDisplayName().equals(stack2.getItemMeta().getDisplayName())) { - return false; // items have different display name - } - } else { - return false; // one of the item stacks have a display name - } - } - try { - Class.forName("org.bukkit.inventory.meta.EnchantmentStorageMeta"); - boolean book1 = stack1.getItemMeta() instanceof EnchantmentStorageMeta; - boolean book2 = stack2.getItemMeta() instanceof EnchantmentStorageMeta; - if (book1 != book2) - return false;// One has enchantment meta, the other does not. - if (book1 == true) { // They are the same here (both true or both - // false). So if one is true, the other is - // true. - Map ench1 = ((EnchantmentStorageMeta) stack1.getItemMeta()).getStoredEnchants(); - Map ench2 = ((EnchantmentStorageMeta) stack2.getItemMeta()).getStoredEnchants(); - if (!ench1.equals(ench2)) - return false; // Enchants aren't the same. - } - } catch (ClassNotFoundException e) { - // Nothing. They dont have a build high enough to support this. - } - return true; - } - - /** - * Formats the given number according to how vault would like it. E.g. $50 or 5 - * dollars. - * - * @return The formatted string. - */ - public static String format(double n) { - if(plugin.getConfig().getBoolean("shop.disable-vault-format")) { - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; - } - try { - String formated = plugin.getEcon().format(n); - if (formated == null || formated.isEmpty()) { - Util.debugLog("Use alternate-currency-symbol cause Economy Plugin returned null"); - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; - } else { - return formated; - } - } catch (NumberFormatException e) { - Util.debugLog("Use alternate-currency-symbol cause NumberFormatException"); - return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; - // return "$" + n; - } - } - - /** - * @param m - * The material to check if it is blacklisted - * @return true if the material is black listed. False if not. - */ - public static boolean isBlacklisted(Material m) { - return blacklist.contains(m); - } - - /** - * Fetches the block which the given sign is attached to - * - * @param sign - * The sign which is attached - * @return The block the sign is attached to - */ - public static Block getAttached(Block b) { - try { - Sign sign = (Sign) b.getState().getData(); // Throws a NPE - // sometimes?? - BlockFace attached = sign.getAttachedFace(); - if (attached == null) - return null; - return b.getRelative(attached); - } catch (NullPointerException e) { - return null; // /Not sure what causes this. - } - } - - /** - * Counts the number of items in the given inventory where - * Util.matches(inventory item, item) is true. - * - * @param inv - * The inventory to search - * @param item - * The ItemStack to search for - * @return The number of items that match in this inventory. - */ - public static int countItems(Inventory inv, ItemStack item) { - int items = 0; - for (ItemStack iStack : inv.getContents()) { - if (iStack == null) - continue; - if (Util.matches(item, iStack)) { - items += iStack.getAmount(); - } - } - Util.debugLog("Items: "+items); - return items; - } - - /** - * Returns the number of items that can be given to the inventory safely. - * - * @param inv - * The inventory to count - * @param item - * The item prototype. Material, durabiltiy and enchants must - * match for 'stackability' to occur. - * @return The number of items that can be given to the inventory safely. - */ - public static int countSpace(Inventory inv, ItemStack item) { - int space = 0; - - try { - ItemStack[] contents = (ItemStack[])storageContents.invoke(inv); - for (ItemStack iStack : contents) { - if (iStack == null || iStack.getType() == Material.AIR) { - space += item.getMaxStackSize(); - } else if (matches(item, iStack)) { - space += item.getMaxStackSize() - iStack.getAmount(); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - Util.debugLog("Space:"+space); - return space; - } - - /** - * Returns true if the given location is loaded or not. - * - * @param loc - * The location - * @return true if the given location is loaded or not. - */ - public static boolean isLoaded(Location loc) { - // plugin.getLogger().log(Level.WARNING, "Checking isLoaded(Location loc)"); - if (loc.getWorld() == null) { - // plugin.getLogger().log(Level.WARNING, "Is not loaded. (No world)"); - return false; - } - // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT - // location rounded to the nearest 16. - int x = (int) Math.floor((loc.getBlockX()) / 16.0); - int z = (int) Math.floor((loc.getBlockZ()) / 16.0); - if (loc.getWorld().isChunkLoaded(x, z)) { - // plugin.getLogger().log(Level.WARNING, "Chunk is loaded " + x + ", " + z); - return true; - } else { - // plugin.getLogger().log(Level.WARNING, "Chunk is NOT loaded " + x + ", " + z); - return false; - } - } - /** - * Use yaw to calc the BlockFace - * @param float yaw - * @return BlockFace blockFace - */ - public static BlockFace getYawFace(float yaw) { - if (yaw > 315 && yaw <= 45) { - return BlockFace.NORTH; - } else if (yaw > 45 && yaw <= 135) { - return BlockFace.EAST; - } else if (yaw > 135 && yaw <= 225) { - return BlockFace.SOUTH; - } else { - return BlockFace.WEST; - } - } - - /** - * Get this class available or not - * @param String qualifiedName - * @return boolean Available - */ - public static boolean isClassAvailable(String qualifiedName) { - try { - Class.forName(qualifiedName); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - /** - * Send a message for all online Ops. - * @param String message - * @return - */ - public static void sendMessageToOps(String message) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.isOp() || player.hasPermission("quickshop.alert")) { - player.sendMessage(message); - } - } - } - //Use NMS - public static void sendItemholochat(ItemStack itemStack, Player player, String normalText) { - try { - String json = ItemNMS.saveJsonfromNMS(itemStack); - if (json == null) - return; - TextComponent normalmessage = new TextComponent(normalText+" "+MsgUtil.getMessage("menu.preview")); - ComponentBuilder cBuilder = new ComponentBuilder(json); - HoverEvent he = new HoverEvent(HoverEvent.Action.SHOW_ITEM, cBuilder.create()); - normalmessage.setHoverEvent(he); - player.spigot().sendMessage(normalmessage); - } catch (Throwable t) { - sendItemholochatAsNormaly(itemStack, player, normalText); - } - } - - // Without NMS - public static void sendItemholochatAsNormaly(ItemStack itemStack, Player player, String normalText) { - try { - String Itemname = null; - List Itemlore = new ArrayList<>(); - String finalItemdata = null; - Map enchs = new HashMap(); - Map Itemenchs = new HashMap(); - if (itemStack.hasItemMeta()) { - ItemMeta iMeta = itemStack.getItemMeta(); - if (iMeta.hasDisplayName()) { - Itemname = iMeta.getDisplayName(); - } else { - Itemname = MsgUtil.getItemi18n(itemStack.getType().name()); - } - if (iMeta.hasLore()) { - Itemlore = iMeta.getLore(); - } else { - Itemlore = new ArrayList(); - } - if (iMeta.hasEnchants()) { - enchs = iMeta.getEnchants(); - for (Entry entries : enchs.entrySet()) { - String i18n = MsgUtil.getEnchi18n(entries.getKey()); - if (i18n != null) { - Itemenchs.put(i18n, entries.getValue()); - } else { - Itemenchs = null; - } - } - } - } else { - Itemname = MsgUtil.getDisplayName(itemStack); - Itemlore = null; - Itemenchs = null; - } - if(Itemname!=MsgUtil.getItemi18n(itemStack.getType().name())) { - finalItemdata = Itemname+" "+ChatColor.GRAY+"("+MsgUtil.getItemi18n(itemStack.getType().name())+ChatColor.GRAY+")"; - }else { - finalItemdata = Itemname; - } - - finalItemdata += "\n"; - List a = new ArrayList<>(); - List b = new ArrayList<>(); - a.addAll(Itemenchs.keySet()); - b.addAll(Itemenchs.values()); - for (int i = 0; i < a.size(); i++) { - finalItemdata += ChatColor.GRAY + a.get(i) + " " + Util.formatEnchLevel(b.get(i)) + "\n"; - } - - String potionResult = getPotiondata(itemStack); - if(potionResult!=null) { - finalItemdata += potionResult; - } - - if (Itemlore != null) { - for (String string : Itemlore) { - finalItemdata += ChatColor.DARK_PURPLE +""+ ChatColor.ITALIC + string + "\n"; - } - } - TextComponent normalmessage = new TextComponent(normalText+" "+MsgUtil.getMessage("menu.preview")); - ComponentBuilder cBuilder = new ComponentBuilder(finalItemdata); - HoverEvent he = new HoverEvent(HoverEvent.Action.SHOW_TEXT, cBuilder.create()); - normalmessage.setHoverEvent(he); - player.spigot().sendMessage(normalmessage); - }catch (Exception e) { - player.sendMessage(normalText); - QuickShop.instance.getLogger().severe("QuickShop cannot send Advanced chat message, Are you using CraftBukkit? Please use Spigot or SpigotFork."); - } - } - private static String formatEnchLevel(Integer level) { - switch (level) { - case 1: - return "I"; - case 2: - return "II"; - case 3: - return "III"; - case 4: - return "IV"; - case 5: - return "V"; - default: - return String.valueOf(level); - - } - } - /** - * @param iStack - */ - public static String getPotiondata(ItemStack iStack) { - if((iStack.getType() != Material.POTION)==true && (iStack.getType() !=Material.LINGERING_POTION)==true && (iStack.getType() !=Material.SPLASH_POTION)==true){ - return null; - } - List pEffects = new ArrayList(); - PotionMeta pMeta = (PotionMeta)iStack.getItemMeta(); - if(pMeta.getBasePotionData().getType()!=null) { - if(!(pMeta.getBasePotionData().isUpgraded())){ - pEffects.add(ChatColor.BLUE+MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())); - }else { - pEffects.add(ChatColor.BLUE+MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())+" II"); - } - - } - if(pMeta.hasCustomEffects()) { - List cEffects = pMeta.getCustomEffects(); - for (PotionEffect potionEffect : cEffects) { - pEffects.add(MsgUtil.getPotioni18n(potionEffect.getType())+" "+formatEnchLevel(potionEffect.getAmplifier())); - } - } - if(pEffects != null && pEffects.isEmpty() == false) { - String result = new String(); - for (String effectString : pEffects) { - result+=effectString+"\n"; - } - return result; - }else { - return null; - } - } - /** - * Send warning message when some plugin calling deprecated method... - * @return - */ - public static void sendDeprecatedMethodWarn() { - QuickShop.instance.getLogger().warning("Some plugin calling Deprecated method, Please contact author to use new api!"); - } - /** - * Check QuickShop is running on dev mode or not. - * @return - */ - public static boolean isDevEdition() { - if(QuickShop.instance.getDescription().getVersion().contains("dev")||QuickShop.instance.getDescription().getVersion().contains("alpha")||QuickShop.instance.getDescription().getVersion().contains("beta")||QuickShop.instance.getDescription().getVersion().contains("snapshot")) { - return true; - }else { - return false; - } - } - /** - * Call this to check items in inventory and remove it. - */ - public static void inventoryCheck(Inventory inv){ - try{ - for (int i =0; i < inv.getSize(); i++) - if (DisplayItem.checkShopItem(inv.getItem(i))) { - // Found Item and remove it. - inv.setItem(i, new ItemStack(Material.AIR, 0)); - Util.debugLog("Something trying collect QuickShop displayItem, already cancelled. ("+inv.getLocation().toString()+")"); - } - }catch (Throwable t){ - } - - } - private static Object serverInstance; - private static Field tpsField; - /** - * Get MinecraftServer's TPS - * @return double TPS (e.g 19.92) - */ - public static Double getTPS() { - try { - serverInstance = getNMSClass("MinecraftServer").getMethod("getServer").invoke(null); - tpsField = serverInstance.getClass().getField("recentTps"); - } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException e) { - e.printStackTrace(); - } - try { - double[] tps = ((double[]) tpsField.get(serverInstance)); - return tps[0]; - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - - } - private static Class getNMSClass(String className) { - String name = Bukkit.getServer().getClass().getPackage().getName(); - String version = name.substring(name.lastIndexOf('.') + 1); - try { - return Class.forName("net.minecraft.server." + version + "." + className); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - /** - * Print debug log when plugin running on dev mode. - * @param String logs - */ - public static void debugLog(String logs) { - if(devMode) { - plugin.getLogger().warning("[DEBUG] "+logs); - } - - } - /** - * Create a Timer and return this timer's UUID - * @return - */ - public static UUID setTimer() { - UUID random = UUID.randomUUID(); - timerMap.put(random, System.currentTimeMillis()); - return random; - } - /** - * Return how long time running when timer set. THIS NOT WILL DESTORY AND STOP THE TIMER - * @param UUID timer's uuid - * @return long time - */ - public static long getTimer(UUID uuid) { - return System.currentTimeMillis()-timerMap.get(uuid); - } - /** - * Return how long time running when timer set and destory the timer. - * @param String logs - * @return long time - */ - public static long endTimer(UUID uuid) { - long time =System.currentTimeMillis()-timerMap.get(uuid); - timerMap.remove(uuid); - return time; - } - public static int getShopsInWorld(String worldName) { - int cost = 0; - Iterator iterator = plugin.getShopManager().getShopIterator(); - while (iterator.hasNext()) { - Shop shop = iterator.next(); - if (shop.getLocation().getWorld().getName().equals(worldName)) { - cost++; - } - } - return cost; - } - public static String readToString(String fileName) { - String encoding = "UTF-8"; - File file = new File(fileName); - Long filelength = file.length(); - byte[] filecontent = new byte[filelength.intValue()]; - try { - FileInputStream in = new FileInputStream(file); - in.read(filecontent); - in.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - try { - return new String(filecontent, encoding); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return ("The OS does not support " + encoding); - } - } -} +package org.maxgamer.quickshop.Util; + +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.*; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.material.Sign; +import org.bukkit.potion.PotionEffect; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Shop.DisplayItem; +import org.maxgamer.quickshop.Shop.Shop; + +import java.io.*; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.AbstractMap.SimpleEntry; +import java.util.*; +import java.util.Map.Entry; + +/** + * @author MACHENIKE + * + */ +public class Util { + private static final EnumSet blacklist = EnumSet.noneOf(Material.class); + private static final EnumSet shoppables = EnumSet.noneOf(Material.class); + private static final EnumMap> restrictedPrices = new EnumMap>(Material.class); + private static QuickShop plugin; + private static Method storageContents; + static Map timerMap = new HashMap(); + protected static boolean devMode; + public String boolean2String(boolean bool) { + if (bool) { + return "Enabled"; + } else { + return "Disabled"; + } + } + public static void initialize() { + blacklist.clear(); + shoppables.clear(); + restrictedPrices.clear(); + + plugin = QuickShop.instance; + devMode = plugin.getConfig().getBoolean("dev-mode"); + for (String s : plugin.getConfig().getStringList("shop-blocks")) { + Material mat = Material.matchMaterial(s.toUpperCase()); + if (mat == null) { + try { + mat = Material.matchMaterial(s); + } catch (NumberFormatException e) { + } + } + if (mat == null) { + plugin.getLogger().info("Invalid shop-block: " + s); + } else { + shoppables.add(mat); + } + } + List configBlacklist = plugin.getConfig().getStringList("blacklist"); + for (String s : configBlacklist) { + Material mat = Material.getMaterial(s.toUpperCase()); + if (mat == null) { + mat = Material.matchMaterial(s); + if (mat == null) { + plugin.getLogger().info(s + " is not a valid material. Check your spelling or ID"); + continue; + } + } + blacklist.add(mat); + } + + for (String s : plugin.getConfig().getStringList("price-restriction")) { + String[] sp = s.split(";"); + if (sp.length==3) { + try { + Material mat = Material.matchMaterial(sp[0]); + if (mat == null) { + throw new Exception(); + } + + restrictedPrices.put(mat, new SimpleEntry(Double.valueOf(sp[1]), Double.valueOf(sp[2]))); + } catch (Exception e) { + plugin.getLogger().info("Invalid price restricted material: " + s); + } + } + } + + try { + storageContents = Inventory.class.getMethod("getStorageContents"); + } catch (Exception e) { + try { + storageContents = Inventory.class.getMethod("getContents"); + } catch (Exception e1) { + throw new RuntimeException(e1); + } + } + } + + /** Return an entry with min and max prices, but null if there isn't a price restriction */ + public static Entry getPriceRestriction(Material material) { + return restrictedPrices.get(material); + } + @SuppressWarnings("deprecation") + public static boolean isTransparent(Material m) { + boolean trans = m.isTransparent(); + return trans; + } + + public static boolean isShoppables(Material material) { + if(shoppables.contains(material)) { + return true; + }else { + return false; + } + + + } + + public static void parseColours(YamlConfiguration config) { + Set keys = config.getKeys(true); + for (String key : keys) { + String filtered = config.getString(key); + if (filtered.startsWith("MemorySection")) { + continue; + } + filtered = ChatColor.translateAlternateColorCodes('&', filtered); + config.set(key, filtered); + } + } + public static String parseColours(String text) { + text = ChatColor.translateAlternateColorCodes('&', text); + return text; + } + /** + * Returns true if the given block could be used to make a shop out of. + * + * @param b The block to check, Possibly a chest, dispenser, etc. player The player, can be null if onlyCheck=true, onlyCheck The option to disable check AreaShop use player. + * @return True if it can be made into a shop, otherwise false. + */ + public static boolean canBeShop(Block b,UUID player, boolean onlyCheck) { + BlockState bs = b.getState(); + if ((bs instanceof InventoryHolder == false) && b.getState().getType() != Material.ENDER_CHEST) { + return false; + } + if (b.getState().getType() == Material.ENDER_CHEST) { + if (plugin.openInvPlugin == null) { + Util.debugLog("OpenInv not loaded"); + return false; + } else { + return shoppables.contains(bs.getType()); + } + } + return shoppables.contains(bs.getType()); + + } + + /** + * Gets the percentage (Without trailing %) damage on a tool. + * + * @param item + * The ItemStack of tools to check + * @return The percentage 'health' the tool has. (Opposite of total damage) + */ + public static String getToolPercentage(ItemStack item) { + double dura = ((Damageable)item.getItemMeta()).getDamage();; + double max = item.getType().getMaxDurability(); + DecimalFormat formatter = new DecimalFormat("0"); + return formatter.format((1 - dura / max) * 100.0); + } + + /** + * Returns the chest attached to the given chest. The given block must be a + * chest. + * + * @param b + * The chest to check. + * @return the block which is also a chest and connected to b. + */ + /** @TODO 1.13+ compatibility */ + public static Block getSecondHalf_old(Block b) { + if (b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST) + return null; + Block[] blocks = new Block[4]; + blocks[0] = b.getRelative(1, 0, 0); + blocks[1] = b.getRelative(-1, 0, 0); + blocks[2] = b.getRelative(0, 0, 1); + blocks[3] = b.getRelative(0, 0, -1); + for (Block c : blocks) { + if (c.getType() == b.getType()) { + return c; + } + } + return null; + } + + /** + * Returns the chest attached to the given chest. The given block must be a + * chest. + * + * @param b + * The chest to check. + * @return the block which is also a chest and connected to b. + */ + public static Block getSecondHalf(Block b) { + Util.debugLog("Getting Second Half of DoubleChest at "+b.getLocation().toString()); + if(b.getType() != Material.CHEST && b.getType() != Material.TRAPPED_CHEST){ + Util.debugLog("No matched type: "+b.getType().name()); + return null; + } + Chest oneSideOfChest = (Chest)b.getState(); + InventoryHolder chestHolder = oneSideOfChest.getInventory().getHolder(); + if(chestHolder instanceof DoubleChest){ + DoubleChest doubleChest = (DoubleChest)chestHolder; + InventoryHolder left = doubleChest.getLeftSide(); + InventoryHolder right = doubleChest.getRightSide(); + + Chest leftC = (Chest)left; + Chest rightC = (Chest)right; + Util.debugLog("Double chest match checker: "); + Util.debugLog("Find args: "+b.getLocation().toString()); + Util.debugLog("Left: "+leftC.getLocation().toString()); + Util.debugLog("Right: "+rightC.getLocation().toString()); + if(equalsBlockStateLocation(oneSideOfChest, leftC)) { + Util.debugLog("Clicked left chest"); + return rightC.getBlock(); + } + if(equalsBlockStateLocation(oneSideOfChest, leftC)) { + Util.debugLog("Clicked right chest"); + return leftC.getBlock(); + } + Util.debugLog("No matched double chest check but pass the DoubleChest Inventory check"); + return null; + }else{ + Util.debugLog("No matched DoubleChest: "+b.toString()); + return null; + } + } + + private static final boolean equalsBlockStateLocation(BlockState b1, BlockState b2) { + return b1.getX() == b2.getX() && b1.getY() == b2.getY() && b1.getZ() == b2.getZ(); + } + + public static boolean location3DEqual(Location loc1, Location loc2){ + if(loc1.getWorld().getName() != loc2.getWorld().getName()) + return false; + if(loc1.getBlockX() != loc2.getBlockX()) + return false; + if(loc1.getBlockY() != loc2.getBlockY()) + return false; + if(loc1.getBlockZ() != loc2.getBlockZ()) + return false; + return true; + } + /** + * Checks whether someone else's shop is within reach of a hopper being placed by a player. + * + * @param b + * The block being placed. + * @param p + * The player performing the action. + * @return true if a nearby shop was found, false otherwise. + */ + public static boolean isOtherShopWithinHopperReach(Block b, Player p) { + // Check 5 relative positions that can be affected by a hopper: behind, in front of, to the right, + // to the left and underneath. + Block[] blocks = new Block[5]; + blocks[0] = b.getRelative(0, 0, -1); + blocks[1] = b.getRelative(0, 0, 1); + blocks[2] = b.getRelative(1, 0, 0); + blocks[3] = b.getRelative(-1, 0, 0); + blocks[4] = b.getRelative(0, 1, 0); + for (Block c : blocks) { + Shop firstShop = plugin.getShopManager().getShop(c.getLocation()); + // If firstShop is null but is container, it can be used to drain contents from a shop created + // on secondHalf. + Block secondHalf = getSecondHalf(c); + Shop secondShop = secondHalf == null ? null : plugin.getShopManager().getShop(secondHalf.getLocation()); + if (firstShop != null && !p.getUniqueId().equals(firstShop.getOwner()) + || secondShop != null && !p.getUniqueId().equals(secondShop.getOwner())) { + return true; + } + } + return false; + } + + /** + * Covert ItemStack to YAML string. + * @param ItemStack iStack + * @return String serialized itemStack + */ + public static String serialize(ItemStack iStack) { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.set("item", iStack); + return cfg.saveToString(); + } + /** + * Covert YAML string to ItemStack. + * @param String serialized itemStack + * @return ItemStack iStack + */ + public static ItemStack deserialize(String config) throws InvalidConfigurationException { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.loadFromString(config); + cfg.getString("item"); + ItemStack stack = cfg.getItemStack("item"); + return stack; + } + + /** + * Fetches an ItemStack's name - For example, converting INK_SAC:11 to + * Dandellion Yellow, or WOOL:14 to Red Wool + * + * @param itemStack + * The itemstack to fetch the name of + * @return The human readable item name. + */ + public static String getName(ItemStack itemStack) { +// if (NMS.isPotion(itemStack.getType())) { +// return CustomPotionsName.getFullName(itemStack); +// } + String vanillaName = itemStack.getType().name(); + return prettifyText(vanillaName); + } + + /** + * Converts a name like IRON_INGOT into Iron Ingot to improve readability + * + * @param ugly + * The string such as IRON_INGOT + * @return A nicer version, such as Iron Ingot + * + */ + public static String prettifyText(String ugly) { + String[] nameParts = ugly.split("_"); + if (nameParts.length==1) { + return firstUppercase(ugly); + } + + StringBuilder sb=new StringBuilder(); + for (String part : nameParts) { + sb.append(firstUppercase(part)+" "); + } + + return sb.toString(); + } + /** + * Get item's sign name for display on the sign. + * @param ItemStack itemStack + * @return String ItemOnSignName + */ + // Let's make very long names shorter for our sign + public static String getNameForSign(ItemStack itemStack) { +// if (NMS.isPotion(itemStack.getType())) { +// return CustomPotionsName.getSignName(itemStack); +// } + + ItemStack is = itemStack.clone(); + is.setAmount(1); + + if(is.hasItemMeta()) { + if(is.getItemMeta().hasDisplayName()) { + return is.getItemMeta().getDisplayName(); + } + } + + String name = MsgUtil.getItemi18n(itemStack.getType().name()).trim(); + + String[] nameParts = name.split("_"); + if (nameParts.length==1) { + return firstUppercase(nameParts[0]); + } + + for (int i=0; i16) { + nameParts[i] = nameParts[i].substring(0, 1)+"."; + } else { + nameParts[i] = firstUppercase(nameParts[i]); + } + } + + nameParts[nameParts.length-1] = firstUppercase(nameParts[nameParts.length-1]); + + return StringUtils.join(nameParts); + } + + public static String firstUppercase(String string) { + if (string.length()>1) { + return Character.toUpperCase(string.charAt(0))+string.substring(1).toLowerCase(); + } else { + return string.toUpperCase(); + } + } + + + public static String toRomain(Integer value) { + return toRoman(value.intValue()); + } + + private static final String[] ROMAN = { "X", "IX", "V", "IV", "I" }; + private static final int[] DECIMAL = { 10, 9, 5, 4, 1 }; + + /** + * Converts the given number to roman numerals. If the number is >= 40 or <= + * 0, it will just return the number as a string. + * + * @param n + * The number to convert + * @return The roman numeral representation of this number, or the number in + * decimal form as a string if n <= 0 || n >= 40. + */ + public static String toRoman(int n) { + if (n <= 0 || n >= 40) + return "" + n; + String roman = ""; + for (int i = 0; i < ROMAN.length; i++) { + while (n >= DECIMAL[i]) { + n -= DECIMAL[i]; + roman += ROMAN[i]; + } + } + return roman; + } + /** + * @param mat + * The material to check + * @return Returns true if the item is a tool (Has durability) or false if + * it doesn't. + */ + public static boolean isTool(Material mat) { + if(mat.getMaxDurability()==0){ + return false; + }else{ + return true; + } + } + + /** + * Compares two items to each other. Returns true if they match. + * + * @param stack1 + * The first item stack + * @param stack2 + * The second item stack + * @return true if the itemstacks match. (Material, durability, enchants, name) + */ + public static boolean matches(ItemStack stack1, ItemStack stack2) { + if (stack1 == stack2) + return true; // Referring to the same thing, or both are null. + if (stack1 == null || stack2 == null) + return false; // One of them is null (Can't be both, see above) + if (stack1.getType() != stack2.getType()) + return false; // Not the same material + if (((Damageable)stack1.getItemMeta()).getDamage() != ((Damageable)stack2.getItemMeta()).getDamage()) + return false; // Not the same durability + if (!stack1.getEnchantments().equals(stack2.getEnchantments())) + return false; // They have the same enchants + if (stack1.getItemMeta().hasDisplayName() || stack2.getItemMeta().hasDisplayName()) { + if (stack1.getItemMeta().hasDisplayName() && stack2.getItemMeta().hasDisplayName()) { + if (!stack1.getItemMeta().getDisplayName().equals(stack2.getItemMeta().getDisplayName())) { + return false; // items have different display name + } + } else { + return false; // one of the item stacks have a display name + } + } + try { + Class.forName("org.bukkit.inventory.meta.EnchantmentStorageMeta"); + boolean book1 = stack1.getItemMeta() instanceof EnchantmentStorageMeta; + boolean book2 = stack2.getItemMeta() instanceof EnchantmentStorageMeta; + if (book1 != book2) + return false;// One has enchantment meta, the other does not. + if (book1 == true) { // They are the same here (both true or both + // false). So if one is true, the other is + // true. + Map ench1 = ((EnchantmentStorageMeta) stack1.getItemMeta()).getStoredEnchants(); + Map ench2 = ((EnchantmentStorageMeta) stack2.getItemMeta()).getStoredEnchants(); + if (!ench1.equals(ench2)) + return false; // Enchants aren't the same. + } + } catch (ClassNotFoundException e) { + // Nothing. They dont have a build high enough to support this. + } + return true; + } + + /** + * Formats the given number according to how vault would like it. E.g. $50 or 5 + * dollars. + * + * @return The formatted string. + */ + public static String format(double n) { + if(plugin.getConfig().getBoolean("shop.disable-vault-format")) { + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + } + try { + String formated = plugin.getEcon().format(n); + if (formated == null || formated.isEmpty()) { + Util.debugLog("Use alternate-currency-symbol cause Economy Plugin returned null"); + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + } else { + return formated; + } + } catch (NumberFormatException e) { + Util.debugLog("Use alternate-currency-symbol cause NumberFormatException"); + return plugin.getConfig().getString("shop.alternate-currency-symbol") + n; + // return "$" + n; + } + } + + /** + * @param m + * The material to check if it is blacklisted + * @return true if the material is black listed. False if not. + */ + public static boolean isBlacklisted(Material m) { + return blacklist.contains(m); + } + + /** + * Fetches the block which the given sign is attached to + * + * @param sign + * The sign which is attached + * @return The block the sign is attached to + */ + public static Block getAttached(Block b) { + try { + Sign sign = (Sign) b.getState().getData(); // Throws a NPE + // sometimes?? + BlockFace attached = sign.getAttachedFace(); + if (attached == null) + return null; + return b.getRelative(attached); + } catch (NullPointerException e) { + return null; // /Not sure what causes this. + } + } + + /** + * Counts the number of items in the given inventory where + * Util.matches(inventory item, item) is true. + * + * @param inv + * The inventory to search + * @param item + * The ItemStack to search for + * @return The number of items that match in this inventory. + */ + public static int countItems(Inventory inv, ItemStack item) { + int items = 0; + for (ItemStack iStack : inv.getContents()) { + if (iStack == null) + continue; + if (Util.matches(item, iStack)) { + items += iStack.getAmount(); + } + } + Util.debugLog("Items: "+items); + return items; + } + + /** + * Returns the number of items that can be given to the inventory safely. + * + * @param inv + * The inventory to count + * @param item + * The item prototype. Material, durabiltiy and enchants must + * match for 'stackability' to occur. + * @return The number of items that can be given to the inventory safely. + */ + public static int countSpace(Inventory inv, ItemStack item) { + int space = 0; + + try { + ItemStack[] contents = (ItemStack[])storageContents.invoke(inv); + for (ItemStack iStack : contents) { + if (iStack == null || iStack.getType() == Material.AIR) { + space += item.getMaxStackSize(); + } else if (matches(item, iStack)) { + space += item.getMaxStackSize() - iStack.getAmount(); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Util.debugLog("Space:"+space); + return space; + } + @SuppressWarnings("deprecation") + public static boolean isWallSign(Material material) { + if(material==Material.ACACIA_WALL_SIGN) + return true; + if(material==Material.BIRCH_WALL_SIGN) + return true; + if(material==Material.DARK_OAK_WALL_SIGN) + return true; + if(material==Material.JUNGLE_WALL_SIGN) + return true; + if(material==Material.OAK_WALL_SIGN) + return true; + if(material==Material.SPRUCE_WALL_SIGN) + return true; + if(material==Material.LEGACY_WALL_SIGN) //1.13 compatiable + return true; + return false; + } + + /** + * Returns true if the given location is loaded or not. + * + * @param loc + * The location + * @return true if the given location is loaded or not. + */ + public static boolean isLoaded(Location loc) { + // plugin.getLogger().log(Level.WARNING, "Checking isLoaded(Location loc)"); + if (loc.getWorld() == null) { + // plugin.getLogger().log(Level.WARNING, "Is not loaded. (No world)"); + return false; + } + // Calculate the chunks coordinates. These are 1,2,3 for each chunk, NOT + // location rounded to the nearest 16. + int x = (int) Math.floor((loc.getBlockX()) / 16.0); + int z = (int) Math.floor((loc.getBlockZ()) / 16.0); + if (loc.getWorld().isChunkLoaded(x, z)) { + // plugin.getLogger().log(Level.WARNING, "Chunk is loaded " + x + ", " + z); + return true; + } else { + // plugin.getLogger().log(Level.WARNING, "Chunk is NOT loaded " + x + ", " + z); + return false; + } + } + /** + * Use yaw to calc the BlockFace + * @param float yaw + * @return BlockFace blockFace + */ + public static BlockFace getYawFace(float yaw) { + if (yaw > 315 && yaw <= 45) { + return BlockFace.NORTH; + } else if (yaw > 45 && yaw <= 135) { + return BlockFace.EAST; + } else if (yaw > 135 && yaw <= 225) { + return BlockFace.SOUTH; + } else { + return BlockFace.WEST; + } + } + + /** + * Get this class available or not + * @param String qualifiedName + * @return boolean Available + */ + public static boolean isClassAvailable(String qualifiedName) { + try { + Class.forName(qualifiedName); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + /** + * Send a message for all online Ops. + * @param String message + * @return + */ + public static void sendMessageToOps(String message) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.isOp() || player.hasPermission("quickshop.alert")) { + player.sendMessage(message); + } + } + } + //Use NMS + public static void sendItemholochat(ItemStack itemStack, Player player, String normalText) { + try { + String json = ItemNMS.saveJsonfromNMS(itemStack); + if (json == null) + return; + TextComponent normalmessage = new TextComponent(normalText+" "+MsgUtil.getMessage("menu.preview")); + ComponentBuilder cBuilder = new ComponentBuilder(json); + HoverEvent he = new HoverEvent(HoverEvent.Action.SHOW_ITEM, cBuilder.create()); + normalmessage.setHoverEvent(he); + player.spigot().sendMessage(normalmessage); + } catch (Throwable t) { + sendItemholochatAsNormaly(itemStack, player, normalText); + } + } + + // Without NMS + public static void sendItemholochatAsNormaly(ItemStack itemStack, Player player, String normalText) { + try { + String Itemname = null; + List Itemlore = new ArrayList<>(); + String finalItemdata = null; + Map enchs = new HashMap(); + Map Itemenchs = new HashMap(); + if (itemStack.hasItemMeta()) { + ItemMeta iMeta = itemStack.getItemMeta(); + if (iMeta.hasDisplayName()) { + Itemname = iMeta.getDisplayName(); + } else { + Itemname = MsgUtil.getItemi18n(itemStack.getType().name()); + } + if (iMeta.hasLore()) { + Itemlore = iMeta.getLore(); + } else { + Itemlore = new ArrayList(); + } + if (iMeta.hasEnchants()) { + enchs = iMeta.getEnchants(); + for (Entry entries : enchs.entrySet()) { + String i18n = MsgUtil.getEnchi18n(entries.getKey()); + if (i18n != null) { + Itemenchs.put(i18n, entries.getValue()); + } else { + Itemenchs = null; + } + } + } + } else { + Itemname = MsgUtil.getDisplayName(itemStack); + Itemlore = null; + Itemenchs = null; + } + if(Itemname!=MsgUtil.getItemi18n(itemStack.getType().name())) { + finalItemdata = Itemname+" "+ChatColor.GRAY+"("+MsgUtil.getItemi18n(itemStack.getType().name())+ChatColor.GRAY+")"; + }else { + finalItemdata = Itemname; + } + + finalItemdata += "\n"; + List a = new ArrayList<>(); + List b = new ArrayList<>(); + a.addAll(Itemenchs.keySet()); + b.addAll(Itemenchs.values()); + for (int i = 0; i < a.size(); i++) { + finalItemdata += ChatColor.GRAY + a.get(i) + " " + Util.formatEnchLevel(b.get(i)) + "\n"; + } + + String potionResult = getPotiondata(itemStack); + if(potionResult!=null) { + finalItemdata += potionResult; + } + + if (Itemlore != null) { + for (String string : Itemlore) { + finalItemdata += ChatColor.DARK_PURPLE +""+ ChatColor.ITALIC + string + "\n"; + } + } + TextComponent normalmessage = new TextComponent(normalText+" "+MsgUtil.getMessage("menu.preview")); + ComponentBuilder cBuilder = new ComponentBuilder(finalItemdata); + HoverEvent he = new HoverEvent(HoverEvent.Action.SHOW_TEXT, cBuilder.create()); + normalmessage.setHoverEvent(he); + player.spigot().sendMessage(normalmessage); + }catch (Exception e) { + player.sendMessage(normalText); + QuickShop.instance.getLogger().severe("QuickShop cannot send Advanced chat message, Are you using CraftBukkit? Please use Spigot or SpigotFork."); + } + } + private static String formatEnchLevel(Integer level) { + switch (level) { + case 1: + return "I"; + case 2: + return "II"; + case 3: + return "III"; + case 4: + return "IV"; + case 5: + return "V"; + default: + return String.valueOf(level); + + } + } + /** + * @param iStack + */ + public static String getPotiondata(ItemStack iStack) { + if((iStack.getType() != Material.POTION)==true && (iStack.getType() !=Material.LINGERING_POTION)==true && (iStack.getType() !=Material.SPLASH_POTION)==true){ + return null; + } + List pEffects = new ArrayList(); + PotionMeta pMeta = (PotionMeta)iStack.getItemMeta(); + if(pMeta.getBasePotionData().getType()!=null) { + if(!(pMeta.getBasePotionData().isUpgraded())){ + pEffects.add(ChatColor.BLUE+MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())); + }else { + pEffects.add(ChatColor.BLUE+MsgUtil.getPotioni18n(pMeta.getBasePotionData().getType().getEffectType())+" II"); + } + + } + if(pMeta.hasCustomEffects()) { + List cEffects = pMeta.getCustomEffects(); + for (PotionEffect potionEffect : cEffects) { + pEffects.add(MsgUtil.getPotioni18n(potionEffect.getType())+" "+formatEnchLevel(potionEffect.getAmplifier())); + } + } + if(pEffects != null && pEffects.isEmpty() == false) { + String result = new String(); + for (String effectString : pEffects) { + result+=effectString+"\n"; + } + return result; + }else { + return null; + } + } + /** + * Send warning message when some plugin calling deprecated method... + * @return + */ + public static void sendDeprecatedMethodWarn() { + QuickShop.instance.getLogger().warning("Some plugin calling Deprecated method, Please contact author to use new api!"); + } + /** + * Check QuickShop is running on dev mode or not. + * @return + */ + public static boolean isDevEdition() { + if(QuickShop.instance.getDescription().getVersion().contains("dev")||QuickShop.instance.getDescription().getVersion().contains("alpha")||QuickShop.instance.getDescription().getVersion().contains("beta")||QuickShop.instance.getDescription().getVersion().contains("snapshot")) { + return true; + }else { + return false; + } + } + /** + * Call this to check items in inventory and remove it. + */ + public static void inventoryCheck(Inventory inv){ + try{ + for (int i =0; i < inv.getSize(); i++) + if (DisplayItem.checkShopItem(inv.getItem(i))) { + // Found Item and remove it. + inv.setItem(i, new ItemStack(Material.AIR, 0)); + Util.debugLog("Something trying collect QuickShop displayItem, already cancelled. ("+inv.getLocation().toString()+")"); + } + }catch (Throwable t){ + } + + } + private static Object serverInstance; + private static Field tpsField; + /** + * Get MinecraftServer's TPS + * @return double TPS (e.g 19.92) + */ + public static Double getTPS() { + try { + serverInstance = getNMSClass("MinecraftServer").getMethod("getServer").invoke(null); + tpsField = serverInstance.getClass().getField("recentTps"); + } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException e) { + e.printStackTrace(); + } + try { + double[] tps = ((double[]) tpsField.get(serverInstance)); + return tps[0]; + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + private static Class getNMSClass(String className) { + String name = Bukkit.getServer().getClass().getPackage().getName(); + String version = name.substring(name.lastIndexOf('.') + 1); + try { + return Class.forName("net.minecraft.server." + version + "." + className); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + /** + * Print debug log when plugin running on dev mode. + * @param String logs + */ + public static void debugLog(String logs) { + if(devMode) { + plugin.getLogger().warning("[DEBUG] "+logs); + } + + } + /** + * Create a Timer and return this timer's UUID + * @return + */ + public static UUID setTimer() { + UUID random = UUID.randomUUID(); + timerMap.put(random, System.currentTimeMillis()); + return random; + } + /** + * Return how long time running when timer set. THIS NOT WILL DESTORY AND STOP THE TIMER + * @param UUID timer's uuid + * @return long time + */ + public static long getTimer(UUID uuid) { + return System.currentTimeMillis()-timerMap.get(uuid); + } + /** + * Return how long time running when timer set and destory the timer. + * @param String logs + * @return long time + */ + public static long endTimer(UUID uuid) { + long time =System.currentTimeMillis()-timerMap.get(uuid); + timerMap.remove(uuid); + return time; + } + public static int getShopsInWorld(String worldName) { + int cost = 0; + Iterator iterator = plugin.getShopManager().getShopIterator(); + while (iterator.hasNext()) { + Shop shop = iterator.next(); + if (shop.getLocation().getWorld().getName().equals(worldName)) { + cost++; + } + } + return cost; + } + public static String readToString(String fileName) { + String encoding = "UTF-8"; + File file = new File(fileName); + Long filelength = file.length(); + byte[] filecontent = new byte[filelength.intValue()]; + try { + FileInputStream in = new FileInputStream(file); + in.read(filecontent); + in.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + try { + return new String(filecontent, encoding); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return ("The OS does not support " + encoding); + } + } +}