From f1f96f3abc70a77b9a86673104b2749325425fad Mon Sep 17 00:00:00 2001 From: Ghost_chu <2908803755@qq.com> Date: Thu, 26 Jul 2018 22:34:39 +0800 Subject: [PATCH] Upload code --- bin/.gitignore | 9 + bin/README.md | 26 + bin/pom.xml | 133 + bin/src/main/resources/config.yml | 129 + bin/src/main/resources/messages.yml | 108 + bin/src/main/resources/plugin.yml | 60 + pom.xml | 60 +- .../org/maxgamer/quickshop/Command/QS.java | 1336 +++++----- .../quickshop/Listeners/ChatListener.java | 57 +- .../quickshop/Listeners/HeroChatListener.java | 30 - .../quickshop/Listeners/PlayerListener.java | 456 ++-- .../org/maxgamer/quickshop/QuickShop.java | 1154 +++++---- .../maxgamer/quickshop/Shop/ShopManager.java | 1323 +++++----- .../java/org/maxgamer/quickshop/Util/NMS.java | 850 ++----- .../org/maxgamer/quickshop/Util/Util.java | 2165 +++++++++-------- src/main/resources/plugin.yml | 118 +- 16 files changed, 3993 insertions(+), 4021 deletions(-) create mode 100644 bin/.gitignore create mode 100644 bin/README.md create mode 100644 bin/pom.xml create mode 100644 bin/src/main/resources/config.yml create mode 100644 bin/src/main/resources/messages.yml create mode 100644 bin/src/main/resources/plugin.yml delete mode 100644 src/main/java/org/maxgamer/quickshop/Listeners/HeroChatListener.java diff --git a/bin/.gitignore b/bin/.gitignore new file mode 100644 index 000000000..9cb53fa1e --- /dev/null +++ b/bin/.gitignore @@ -0,0 +1,9 @@ +*.class +lib/ +src/test/ +.settings/ +target/ +.idea/ +*.iml +.classpath +.project diff --git a/bin/README.md b/bin/README.md new file mode 100644 index 000000000..875be32e4 --- /dev/null +++ b/bin/README.md @@ -0,0 +1,26 @@ +# QuickShop +QuickShop is a shop plugin, that allows players to sell items from a chest with no commands. It allows players to purchase any number of items easily. In fact, this plugin doesn't even have any commands that a player would ever need! + +## Support +Open a new issue here: https://github.com/KaiKikuchi/QuickShop/issues + +## Features +- Easy to use +- Togglable Display Item on top of chest +- NBT Data, Enchants, Tool Damage, Potion and Mob Egg support +- Unlimited chest support +- Blacklist support & bypass permissions +- Shops that buy items and sell items at the same time are possible (Using double chests) +- Herochat support +- Checks a player can open a chest before letting them create a shop! +- UUID support + +## Releases +Github projects have a "releases" link on their home page. If you still don't see it, [click here](https://github.com/KaiKikuchi/QuickShop/releases) for QuickShop releases. + +## Links +- [SpigotMC](https://www.spigotmc.org/resources/quickshop.18676/) +- [dev.bukkit.org](http://dev.bukkit.org/bukkit-plugins/quickshop-notlikeme/) (no longer maintained) + +## Contribute +If you're a developer, you can contribute to the QuickShop code! Just make a fork, then make a pull request when you're done! Please try to follow [Google Java Style](https://google.github.io/styleguide/javaguide.html). Also do not increase the plugin version number. Thank you very much! diff --git a/bin/pom.xml b/bin/pom.xml new file mode 100644 index 000000000..bc862a239 --- /dev/null +++ b/bin/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + org.maxgamer + QuickShop + 0.9.38 + + + + GPL v3 License + http://www.gnu.org/licenses/ + repo + + + + + 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 + + + + + + src/main/resources + true + + + + + + bukkit-repo + https://hub.spigotmc.org/nexus/content/groups/public/ + + + sk89q-repo + http://maven.sk89q.com/repo/ + + + vault-repo + http://nexus.hc.to/content/repositories/pub_releases + + + + + org.bukkit + bukkit + 1.9.4-R0.1-SNAPSHOT + jar + provided + + + com.sk89q + worldguard + 6.0.0-SNAPSHOT + + + net.milkbowl.vault + VaultAPI + 1.5 + provided + + + com.dthielke.herochat + herochat + 5.6.7 + system + ${basedir}/lib/HeroChat.jar + + + org.bukkit.craftbukkit.v1_7_R3 + craftbukkit + v1_7_R3 + system + ${basedir}/lib/craftbukkit-1.7.9-R0.2.jar + + + org.bukkit.craftbukkit.v1_8_R3 + craftbukkit + v1_8_R3 + system + ${basedir}/lib/craftbukkit-1.8.8-R0.1.jar + + + org.bukkit.craftbukkit.v1_9_R2 + craftbukkit + v1_9_R2 + system + ${basedir}/lib/craftbukkit-1.9.4-R0.1-SNAPSHOT-latest.jar + + + org.bukkit.craftbukkit.v1_10_R1 + spigot + v1_10_R1 + system + ${basedir}/lib/spigot-1.10.2-R0.1-SNAPSHOT-latest.jar + + + org.bukkit.craftbukkit.v1_11_R1 + spigot + v1_11_R1 + system + ${basedir}/lib/spigot-1.11.jar + + + org.bukkit.craftbukkit.v1_12_R1 + spigot + v1_12_R1 + system + ${basedir}/lib/spigot-1.12-SNAPSHOT.jar + + + + org.maxgamer.quickshop + KaiNoMood + + \ No newline at end of file diff --git a/bin/src/main/resources/config.yml b/bin/src/main/resources/config.yml new file mode 100644 index 000000000..761f4d619 --- /dev/null +++ b/bin/src/main/resources/config.yml @@ -0,0 +1,129 @@ +#Default config: https://github.com/KaiKikuchi/QuickShop/blob/master/src/main/resources/config.yml + +#Tax amount (decimal) - Eg, P1 buys $50 worth of stuff from P2. Therefore, P1 loses $50, P2 gains $(1-0.05)*50, and tax-account gains $(0.05)*50. +tax: 0.05 + +#The fake player who money from taxing people goes to +tax-account: tax + +#Whether or not to show taxes paid when selling to a shop +show-tax: false + +#Should we log transactions/creations to Bukkit\Plugins\QuickShop\qs.log? +log-actions: true + +#For item-item based economies that don't use virtual coins. +whole-number-prices-only: false + +#Force bukkit chat handler (https://github.com/KaiKikuchi/QuickShop/issues/10) +force-bukkit-chat-handler: false + +database: + mysql: false + host: localhost + port: 3306 + database: quickshop + user: root + password: passwd + +#Limits the number of shops a person can create and own at a single time. +limits: + #Disable these if you're not using them! If this is false, the rest of this section is ignored + use: false + + #The default number of shops players can make + default: 10 + + #Players with these permissions can create these amounts of shops. + ranks: + #Anyone with 'quickshop.vip' permissions, can create 20 shops instead of 10. + quickshop.vip: 20 #Players with quickshop.vip can make 20 shops. + +#A list of block (materials) which can be used to create shops. +#By default, chests are added to this list. +#This will only work for blocks which implement InventoryHolder +#in other words, no enderchest shops, no shops on dirt blocks, etc. +#May cause unexpected behaviour with some blocks... Eg don't make a +#shop on a hopper (It sucks the display item in) and furnace shops +#allow players to put whatever item they want in all 3 slots and +#dispenser shops aren't protected from redstone... Etc. +shop-blocks: + - CHEST + - TRAPPED_CHEST + +shop: + #Cost to make a stall + cost: 10 + #Should we refund when their shops are deleted/removed/broken? + refund: false + + #Is there a fee for changing prices on a shop (Help deter endless undercutting) + price-change-requires-fee: true + #If price changes require a fee, how much is the fee + fee-for-price-change: 50 + + #Should we try and lock their shops from other players, so people can't steal from them? + lock: true + + #Should we require players be sneaking to create and use shops? + sneak-to-create: false + sneak-to-trade: false + + #Should we automatically create the sign for the chest? + auto-sign: true + + #If a player owns an unlimited shop, should they receive the cash from it or not? + #If you buy from YOUR unlimited shop, you will NEVER be charged $$, regardless of this setting + pay-unlimited-shop-owners: false + + #Should we place display items on the chests? This may cause duped items, especially for modded servers. + display-items: false + + #The plugin will check if the display item is in a valid position every the specified amount of ticks. 0 to disable. + display-items-check-ticks: 0 + + #When someone uses /qs find , how far should we search in blocks? + #This command lets users shop quickly without wasting time searching + #Settings > 100 WILL cause lag. Don't do it, or don't cry when your server lags. + find-distance: 45 + +#List of items to disallow selling of. Anyone with quickshop.bypass. can bypass it +blacklist: +- 7 #Bedrock + + +#List of items with restricted prices. Format: ;; +price-restriction: +- Bedrock;100;200 + +#Custom name for items. Format: ;; +# Vanilla Material list (ItemIDs): https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html +custom-items-name: +- NETHER_STALK;Nether Wart;Nether Wart + +custom-potions-name: + sign: + format: "%variety%type" + variety: + normal: "" + splash: "Splash" + lingering: "Ling" + shopinfo: + format: "%variety %type" + variety: + normal: "" + splash: "Splash" + lingering: "Lingering" + + #Custom names for potions types. Format: ;; + # PotionType: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/potion/PotionType.html + types: + - INVISIBILITY;Invis;Invisibility + + #Custom names for potion effect type. Format: ; + # PotionEffect: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/potion/PotionEffectType.html + effects: + - FIRE_RESISTANCE;Fire resistance + - INVISIBILITY;Invisibility + + \ No newline at end of file diff --git a/bin/src/main/resources/messages.yml b/bin/src/main/resources/messages.yml new file mode 100644 index 000000000..1134e4e24 --- /dev/null +++ b/bin/src/main/resources/messages.yml @@ -0,0 +1,108 @@ +# Colors: +# &0-9, &a-f +# {0}, {1}, {2}, etc are variables. You can swap them around, but adding a new variable won't work. Removing them will work + +not-looking-at-shop: "&cNo QuickShop found. You must be looking at one." +no-permission: "&cYou do not have permission to do that." +no-creative-break: "&cYou cannot break other players shops in creative mode. Use survival instead." +no-double-chests: "&cYou don't have permission to create a double-chest shop." +shop-already-owned: "&cThat is already a shop." +chest-was-removed: "&cThat chest was removed." +price-too-cheap: "&cPrice must be greater than &e$0.01" +no-price-change: "&cThat wouldn't result in a price change!" +you-cant-afford-a-new-shop: "&cIt costs {0} to create a new shop." +player-bought-from-your-store-tax: "&c{0} purchased {1} {2} from your store, and you paid {3} in taxes." +you-cant-afford-to-change-price: "&cIt costs {0} to change the price in your shop." +success-created-shop: "&aCreated shop." +success-removed-shop: "&aShop removed." +shops-arent-locked: "&cRemember, shops are NOT protected from theft! If you want to stop thieves, lock it with LWC, Lockette, etc!" +shop-creation-cancelled: "&cCancelled Shop Creation." +shop-purchase-cancelled: "&cCancelled Shop Purchase." +shop-stock-too-low: "&cThe shop only has {0} {1} left" +you-cant-afford-to-buy: "&cThat costs {0}, but you only have {1}" +negative-amount: "&cDerp, can't trade negative amounts" +player-bought-from-your-store: "&c{0} purchased {1} {2} from your store." +shop-out-of-stock: "&5Your shop at {0}, {1}, {2}, has run out of {3}" +shop-has-no-space: "&cThe shop only has room for {0} more {1}." +you-dont-have-that-many-items: "&cYou only have {0} {1}." +the-owner-cant-afford-to-buy-from-you: "&cThat costs {0} but the owner only has {1}" +player-sold-to-your-store: "&a{0} sold {1} {2} to your store." +shop-out-of-space: "&5Your shop at {0}, {1}, {2}, is now full." +fee-charged-for-price-change: "&aYou pay &c{0}&a to change the price." +price-is-now: "&aThe shops new price is &e{0}" +thats-not-a-number: "&cInvalid number" +no-price-given: "&cPlease give a valid price." +average-price-nearby: "&aAverage Price Nearby: &e{0}" +shop-has-changed: "&cThe shop you tried to use has changed since you clicked it!" +nearby-shop-this-way: "&aShop is {0} blocks away from you." +no-nearby-shop: "&cNo shops matching {0} nearby." +buying-more-than-selling: "&cWARNING: You are buying items for more than you are selling them!" +not-enough-space: "&cYou only have room for {0} more of that!" +refill-success: "&aRefill success" +empty-success: "&aEmpty success" +admin-shop: "AdminShop" +unknown-owner: "Unknown" + +menu: + successful-purchase: "&aSuccessfully Purchased:" + successfully-sold: "&aSuccessfully Sold:" + item-name-and-price: "&e{0} {1} &afor &e{2}" + sell-tax: "&aYou paid &e{0} &ain taxes." + sell-tax-self: "&aYou own this shop so you don't pay taxes." + enchants: "&5Enchants" + stored-enchants: "&5Stored Enchants" + + shop-information: "&aShop Information:" + owner: "&aOwner: {0}" + item: "&aItem: &e{0}" + space: "&aSpace: &e{0}" + stock: "&aStock &e{0}" + price-per: "&aPrice per &e{0} &a- &e{1}" + total-value-of-chest: "&aTotal value of Chest: &e{0}" + damage-percent-remaining: "&e{0}% &aRemaining." + this-shop-is-buying: "&aThis shop is &dBUYING&a items." + this-shop-is-selling: "&aThis shop is &bSELLING&a items." + effects: "&aEffects: &e{0}" + + +bypassing-lock: "&cBypassing a QuickShop lock!" +that-is-locked: "&cThat shop is locked." + +how-many-buy: "&aEnter how many you wish to &bBUY&a in chat." +how-many-sell: "&aEnter how many you wish to &dSELL&a in chat. You have &e{0}&a available" + +not-allowed-to-create: "&cYou may not create a shop here." +blacklisted-item: "&cThat item is blacklisted. You may not sell it" +how-much-to-trade-for: "&aEnter how much you wish to trade one &e{0}&a for in chat." + +command: + #success-created-unlimited: "&aUnlimited QuickShop created." + toggle-unlimited: "&aShop is now {0}" + no-owner-given: "&cNo owner given. Use &a/qs setowner &c" + new-owner: "&aNew owner: &e{0}" + now-buying: "&aNow &dBUYING&a &e{0}" + now-selling: "&aNow &bSELLING &e{0}" + cleaning: "&aCleaning up shops with 0 stock..." + reloading: "&aReloading..." + cleaned: "&aCleaned &e{0}&a shops" + no-type-given: "&cUsage: /qs find " + description: + title: "&aQuickShop Help" + unlimited: "&eMakes a shop unlimited" + setowner: "&eChanges who owns a shop" + buy: "&eChanges a shop to &dBUY&e mode" + sell: "&eChanges a shop to &bSELL&e mode" + clean: "&eRemoves all (loaded) shops with 0 stock" + price: "&eChanges the buy/selling price of one of your shops" + find: "&eLocates the nearest shop of a specific type." + reload: "&eReloads QuickShop from config.yml" + refill: "&eAdds a given number of items to a shop" + empty: "&eRemoves all stock from a shop" + create: "&eCreates a new shop at the target chest" + +signs: + header: "&c{0}" + selling: "Selling {0}" + buying: "Buying {0}" + item: "{0}" + price: "{0} each" \ No newline at end of file diff --git a/bin/src/main/resources/plugin.yml b/bin/src/main/resources/plugin.yml new file mode 100644 index 000000000..05b908d23 --- /dev/null +++ b/bin/src/main/resources/plugin.yml @@ -0,0 +1,60 @@ +name: ${name} +main: ${package}.${name} +version: ${version} +authors: [Netherfoam, Timtower, KaiNoMood] + +description: Economy Shops plugin +softdepend: [Herochat, Vault, Essentials, OpenInv] + +commands: + qs: + description: QuickShop command + usage: /qs + aliases: [shop] + +permissions: + quickshop.create.sell: + description: Allows a player to sell from a shop + default: op + quickshop.create.buy: + description: Allows a player to buy from a shop + default: op + quickshop.create.double: + description: Allows a player to create a double shop + default: op + quickshop.use: + description: Allows a player to buy/sell using other players shops + default: true + quickshop.unlimited: + description: Allows a Staff Member to use /qs unlimited and make a shop infinite + quickshop.bypass.: + description: Allows a player to sell , even if its blacklisted + quickshop.other.destroy: + description: Allows a Staff Member to destroy other players shops if they are locked in the config + quickshop.other.open: + description: Allows a Staff Member to open someone elses shop if they are locked in the config + quickshop.other.price: + description: Allows a Staff Member to change the price of someone elses shop + quickshop.setowner: + description: Allows a Staff Member to change the owner of any shop + quickshop.find: + description: Allows a player to locate the nearest shop of a specific item type. Works in a 3 chunk radius. + default: true + quickshop.refill: + description: Allows a Staff Member to refill the shop theyre looking at with the given number of items. + default: op + quickshop.empty: + description: Allows a Staff Member to empty the shop theyre looking at of all items. + default: op + quickshop.debug: + description: Enables debug info to console + default: op + quickshop.export: + description: Allows exporting database to mysql or sqlite + default: op + quickshop.taxexemption: + description: Tax exemption + default: false + quickshop.alerts: + description: Alert the player when someone tries to cheat with the display item + default: op \ No newline at end of file diff --git a/pom.xml b/pom.xml index bc862a239..9cbadf468 100644 --- a/pom.xml +++ b/pom.xml @@ -58,72 +58,26 @@ - - org.bukkit - bukkit - 1.9.4-R0.1-SNAPSHOT - jar - provided - com.sk89q worldguard - 6.0.0-SNAPSHOT + system + 7.0.0 + ${basedir}/lib/worldguard-legacy-7.0.0-SNAPSHOT-dist.jar net.milkbowl.vault VaultAPI 1.5 - provided - - - com.dthielke.herochat - herochat - 5.6.7 system - ${basedir}/lib/HeroChat.jar + ${basedir}/lib/Vault-1.6.6.jar - org.bukkit.craftbukkit.v1_7_R3 - craftbukkit - v1_7_R3 - system - ${basedir}/lib/craftbukkit-1.7.9-R0.2.jar - - - org.bukkit.craftbukkit.v1_8_R3 - craftbukkit - v1_8_R3 - system - ${basedir}/lib/craftbukkit-1.8.8-R0.1.jar - - - org.bukkit.craftbukkit.v1_9_R2 - craftbukkit - v1_9_R2 - system - ${basedir}/lib/craftbukkit-1.9.4-R0.1-SNAPSHOT-latest.jar - - - org.bukkit.craftbukkit.v1_10_R1 + org.bukkit.craftbukkit.v1_13_R1 spigot - v1_10_R1 + v1_13_R1 system - ${basedir}/lib/spigot-1.10.2-R0.1-SNAPSHOT-latest.jar - - - org.bukkit.craftbukkit.v1_11_R1 - spigot - v1_11_R1 - system - ${basedir}/lib/spigot-1.11.jar - - - org.bukkit.craftbukkit.v1_12_R1 - spigot - v1_12_R1 - system - ${basedir}/lib/spigot-1.12-SNAPSHOT.jar + ${basedir}/lib/spigot-1.13-SNAPSHOT.jar diff --git a/src/main/java/org/maxgamer/quickshop/Command/QS.java b/src/main/java/org/maxgamer/quickshop/Command/QS.java index 2dc2be05c..b91c34661 100644 --- a/src/main/java/org/maxgamer/quickshop/Command/QS.java +++ b/src/main/java/org/maxgamer/quickshop/Command/QS.java @@ -1,669 +1,669 @@ -package org.maxgamer.quickshop.Command; - -import java.io.File; -import java.util.HashMap; -import java.util.Iterator; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.BlockIterator; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Database.Database; -import org.maxgamer.quickshop.Database.MySQLCore; -import org.maxgamer.quickshop.Database.SQLiteCore; -import org.maxgamer.quickshop.Shop.ContainerShop; -import org.maxgamer.quickshop.Shop.Info; -import org.maxgamer.quickshop.Shop.Shop; -import org.maxgamer.quickshop.Shop.ShopAction; -import org.maxgamer.quickshop.Shop.ShopChunk; -import org.maxgamer.quickshop.Shop.ShopType; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Util; - -public class QS implements CommandExecutor { - QuickShop plugin; - - public QS(QuickShop plugin) { - this.plugin = plugin; - } - - private void setUnlimited(CommandSender sender) { - if (sender instanceof Player && sender.hasPermission("quickshop.unlimited")) { - BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.setUnlimited(!shop.isUnlimited()); - shop.update(); - sender.sendMessage(MsgUtil.getMessage("command.toggle-unlimited", (shop.isUnlimited() ? "unlimited" : "limited"))); - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - - private void remove(CommandSender sender, String[] args) { - if (sender instanceof Player == false) { - sender.sendMessage(ChatColor.RED + "Only players may use that command."); - return; - } - if (!sender.hasPermission("quickshop.delete")) { - sender.sendMessage(ChatColor.RED + "You do not have permission to use that command. Try break the shop instead?"); - return; - } - Player p = (Player) sender; - BlockIterator bIt = new BlockIterator(p, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (shop.getOwner().equals(p.getUniqueId())) { - shop.delete(); - sender.sendMessage(ChatColor.GREEN + "Success. Deleted shop."); - } else { - p.sendMessage(ChatColor.RED + "That's not your shop!"); - } - return; - } - } - p.sendMessage(ChatColor.RED + "No shop found!"); - } - - private void export(CommandSender sender, String[] args) { - if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Usage: /qs export mysql|sqlite"); - return; - } - String type = args[1].toLowerCase(); - if (type.startsWith("mysql")) { - if (plugin.getDB().getCore() instanceof MySQLCore) { - sender.sendMessage(ChatColor.RED + "Database is already MySQL"); - return; - } - ConfigurationSection cfg = plugin.getConfig().getConfigurationSection("database"); - String host = cfg.getString("host"); - String port = cfg.getString("port"); - String user = cfg.getString("user"); - String pass = cfg.getString("password"); - String name = cfg.getString("database"); - MySQLCore core = new MySQLCore(host, user, pass, name, port); - Database target; - try { - target = new Database(core); - QuickShop.instance.getDB().copyTo(target); - sender.sendMessage(ChatColor.GREEN + "Success - Exported to MySQL " + user + "@" + host + "." + name); - } catch (Exception e) { - e.printStackTrace(); - sender.sendMessage(ChatColor.RED + "Failed to export to MySQL " + user + "@" + host + "." + name + ChatColor.DARK_RED + " Reason: " + e.getMessage()); - } - return; - } - if (type.startsWith("sql") || type.contains("file")) { - if (plugin.getDB().getCore() instanceof SQLiteCore) { - sender.sendMessage(ChatColor.RED + "Database is already SQLite"); - return; - } - File file = new File(plugin.getDataFolder(), "shops.db"); - if (file.exists()) { - if (file.delete() == false) { - sender.sendMessage(ChatColor.RED + "Warning: Failed to delete old shops.db file. This may cause errors."); - } - } - SQLiteCore core = new SQLiteCore(file); - try { - Database target = new Database(core); - QuickShop.instance.getDB().copyTo(target); - sender.sendMessage(ChatColor.GREEN + "Success - Exported to SQLite: " + file.toString()); - } catch (Exception e) { - e.printStackTrace(); - sender.sendMessage(ChatColor.RED + "Failed to export to SQLite: " + file.toString() + " Reason: " + e.getMessage()); - } - return; - } - sender.sendMessage(ChatColor.RED + "No target given. Usage: /qs export mysql|sqlite"); - } - - private void setOwner(CommandSender sender, String[] args) { - if (sender instanceof Player && sender.hasPermission("quickshop.setowner")) { - if (args.length < 2) { - sender.sendMessage(MsgUtil.getMessage("command.no-owner-given")); - return; - } - BlockIterator bIt = new BlockIterator((Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - @SuppressWarnings("deprecation") - OfflinePlayer p = this.plugin.getServer().getOfflinePlayer(args[1]); - shop.setOwner(p.getUniqueId()); - shop.update(); - sender.sendMessage(MsgUtil.getMessage("command.new-owner", this.plugin.getServer().getOfflinePlayer(shop.getOwner()).getName())); - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - - private void refill(CommandSender sender, String[] args) { - if (sender instanceof Player && sender.hasPermission("quickshop.refill")) { - if (args.length < 2) { - sender.sendMessage(MsgUtil.getMessage("command.no-amount-given")); - return; - } - int add; - try { - add = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { - sender.sendMessage(MsgUtil.getMessage("thats-not-a-number")); - return; - } - BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - shop.add(shop.getItem(), add); - sender.sendMessage(MsgUtil.getMessage("refill-success")); - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - - private void empty(CommandSender sender, String[] args) { - if (sender instanceof Player && sender.hasPermission("quickshop.refill")) { - BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null) { - if (shop instanceof ContainerShop) { - ContainerShop cs = (ContainerShop) shop; - cs.getInventory().clear(); - sender.sendMessage(MsgUtil.getMessage("empty-success")); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - - private void find(CommandSender sender, String[] args) { - if (sender instanceof Player && sender.hasPermission("quickshop.find")) { - if (args.length < 2) { - sender.sendMessage(MsgUtil.getMessage("command.no-type-given")); - return; - } - StringBuilder sb = new StringBuilder(args[1]); - for (int i = 2; i < args.length; i++) { - sb.append(" " + args[i]); - } - String lookFor = sb.toString(); - lookFor = lookFor.toLowerCase(); - Player p = (Player) sender; - Location loc = p.getEyeLocation().clone(); - double minDistance = plugin.getConfig().getInt("shop.find-distance"); - double minDistanceSquared = minDistance * minDistance; - int chunkRadius = (int) minDistance / 16 + 1; - Shop closest = null; - Chunk c = loc.getChunk(); - for (int x = -chunkRadius + c.getX(); x < chunkRadius + c.getX(); x++) { - for (int z = -chunkRadius + c.getZ(); z < chunkRadius + c.getZ(); z++) { - Chunk d = c.getWorld().getChunkAt(x, z); - HashMap inChunk = plugin.getShopManager().getShops(d); - if (inChunk == null) - continue; - for (Shop shop : inChunk.values()) { - if (shop.getDataName().toLowerCase().contains(lookFor) && shop.getLocation().distanceSquared(loc) < minDistanceSquared) { - closest = shop; - minDistanceSquared = shop.getLocation().distanceSquared(loc); - } - } - } - } - if (closest == null) { - sender.sendMessage(MsgUtil.getMessage("no-nearby-shop", args[1])); - return; - } - Location lookat = closest.getLocation().clone().add(0.5, 0.5, 0.5); - // Hack fix to make /qs find not used by /back - p.teleport(this.lookAt(loc, lookat).add(0, -1.62, 0), TeleportCause.UNKNOWN); - p.sendMessage(MsgUtil.getMessage("nearby-shop-this-way", "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); - return; - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - } - - @SuppressWarnings("deprecation") - private void create(CommandSender sender, String[] args) { - if (sender instanceof Player) { - Player p = (Player) sender; - ItemStack item = p.getItemInHand(); - if (item.getType()!=Material.AIR) { - if (sender.hasPermission("quickshop.create.sell")) { - BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); - - while (bIt.hasNext()) { - Block b = bIt.next(); - - if (Util.canBeShop(b)) { - PlayerInteractEvent e = new PlayerInteractEvent(p, Action.LEFT_CLICK_BLOCK, item, b, BlockFace.UP); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled()) { - return; - } - - if (!plugin.getShopManager().canBuildShop(p, b, Util.getYawFace(p.getLocation().getYaw()))) { - // 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. - 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.getTypeId())) { - p.sendMessage(MsgUtil.getMessage("blacklisted-item")); - return; - } - - if (args.length<2) { - // Send creation menu. - Info info = new Info(b.getLocation(), ShopAction.CREATE, p.getItemInHand(), b.getRelative(Util.getYawFace(p.getLocation().getYaw()))); - plugin.getShopManager().getActions().put(p.getUniqueId(), info); - p.sendMessage(MsgUtil.getMessage("how-much-to-trade-for", Util.getName(info.getItem()))); - } else { - plugin.getShopManager().handleChat(p, args[1]); - } - return; - } - } - } else { - sender.sendMessage(MsgUtil.getMessage("no-permission")); - } - } else { - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - } - } else { - sender.sendMessage("This command can't be run by console"); - } - return; - } - - private void amount(CommandSender sender, String[] args) { - if (args.length < 2) { - sender.sendMessage("Missing amount"); - return; - } - - if (sender instanceof Player) { - final Player player = (Player) sender; - if (!plugin.getShopManager().getActions().containsKey(player.getUniqueId())) { - sender.sendMessage("You do not have any pending action!"); - return; - } - plugin.getShopManager().handleChat(player, args[1]); - } else { - sender.sendMessage("This command can't be run by console"); - } - return; - } - - private void setBuy(CommandSender sender) { - if (sender instanceof Player && sender.hasPermission("quickshop.create.buy")) { - BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && shop.getOwner().equals(((Player) sender).getUniqueId())) { - shop.setShopType(ShopType.BUYING); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.getMessage("command.now-buying", shop.getDataName())); - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - - private void setSell(CommandSender sender) { - if (sender instanceof Player && sender.hasPermission("quickshop.create.sell")) { - BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && shop.getOwner().equals(((Player) sender).getUniqueId())) { - shop.setShopType(ShopType.SELLING); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.getMessage("command.now-selling", shop.getDataName())); - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - - @SuppressWarnings("deprecation") - private void setPrice(CommandSender sender, String[] args) { - if (sender instanceof Player && sender.hasPermission("quickshop.create.changeprice")) { - Player p = (Player) sender; - if (args.length < 2) { - sender.sendMessage(MsgUtil.getMessage("no-price-given")); - return; - } - double price; - try { - price = Double.parseDouble(args[1]); - } catch (NumberFormatException e) { - sender.sendMessage(MsgUtil.getMessage("thats-not-a-number")); - return; - } - if (price < 0.01) { - sender.sendMessage(MsgUtil.getMessage("price-too-cheap")); - return; - } - double fee = 0; - if (plugin.priceChangeRequiresFee) { - fee = plugin.getConfig().getDouble("shop.fee-for-price-change"); - if (fee > 0 && plugin.getEcon().getBalance(p.getUniqueId()) < fee) { - sender.sendMessage(MsgUtil.getMessage("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); - return; - } - } - BlockIterator bIt = new BlockIterator(p, 10); - // Loop through every block they're looking at upto 10 blocks away - while (bIt.hasNext()) { - Block b = bIt.next(); - Shop shop = plugin.getShopManager().getShop(b.getLocation()); - if (shop != null && (shop.getOwner().equals(((Player) sender).getUniqueId()) || sender.hasPermission("quickshop.other.price"))) { - if (shop.getPrice() == price) { - // Stop here if there isn't a price change - sender.sendMessage(MsgUtil.getMessage("no-price-change")); - return; - } - if (fee > 0) { - if (!plugin.getEcon().withdraw(p.getUniqueId(), fee)) { - sender.sendMessage(MsgUtil.getMessage("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); - return; - } - sender.sendMessage(MsgUtil.getMessage("fee-charged-for-price-change", plugin.getEcon().format(fee))); - plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), fee); - } - // Update the shop - shop.setPrice(price); - shop.setSignText(); - shop.update(); - sender.sendMessage(MsgUtil.getMessage("price-is-now", plugin.getEcon().format(shop.getPrice()))); - // Chest shops can be double shops. - if (shop instanceof ContainerShop) { - ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) { - Shop nextTo = cs.getAttachedShop(); - if (cs.isSelling()) { - if (cs.getPrice() < nextTo.getPrice()) { - sender.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); - } - } else { - // Buying - if (cs.getPrice() > nextTo.getPrice()) { - sender.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); - } - } - } - } - return; - } - } - sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); - return; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - - private void clean(CommandSender sender) { - if (sender.hasPermission("quickshop.clean")) { - sender.sendMessage(MsgUtil.getMessage("command.cleaning")); - Iterator shIt = plugin.getShopManager().getShopIterator(); - int i = 0; - while (shIt.hasNext()) { - Shop shop = shIt.next(); - - try { - if (shop.getLocation().getWorld() != null && shop.isSelling() && shop.getRemainingStock() == 0 && shop instanceof ContainerShop) { - ContainerShop cs = (ContainerShop) shop; - if (cs.isDoubleShop()) - continue; - shIt.remove(); // Is selling, but has no stock, and is a chest shop, but is not a double shop. Can be deleted safely. - i++; - } - } catch (IllegalStateException e) { - shIt.remove(); // The shop is not there anymore, remove it - } - } - MsgUtil.clean(); - sender.sendMessage(MsgUtil.getMessage("command.cleaned", "" + i)); - return; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - - private void reload(CommandSender sender) { - if (sender.hasPermission("quickshop.reload")) { - sender.sendMessage(MsgUtil.getMessage("command.reloading")); - Bukkit.getPluginManager().disablePlugin(plugin); - Bukkit.getPluginManager().enablePlugin(plugin); - return; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return; - } - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { - if (args.length > 0) { - String subArg = args[0].toLowerCase(); - if (subArg.equals("unlimited")) { - setUnlimited(sender); - return true; - } else if (subArg.equals("setowner")) { - setOwner(sender, args); - return true; - } else if (subArg.equals("find")) { - find(sender, args); - return true; - } else if (subArg.startsWith("create")) { - create(sender, args); - return true; - } else if (subArg.startsWith("amount")) { - amount(sender, args); - return true; - } else if (subArg.startsWith("buy")) { - setBuy(sender); - return true; - } else if (subArg.startsWith("sell")) { - setSell(sender); - return true; - } else if (subArg.startsWith("price")) { - setPrice(sender, args); - return true; - } else if (subArg.equals("remove")) { - remove(sender, args); - } else if (subArg.equals("refill")) { - refill(sender, args); - return true; - } else if (subArg.equals("empty")) { - empty(sender, args); - return true; - } else if (subArg.equals("clean")) { - clean(sender); - return true; - } else if (subArg.equals("reload")) { - reload(sender); - return true; - } else if (subArg.equals("export")) { - export(sender, args); - return true; - } else if (subArg.equals("info")) { - if (sender.hasPermission("quickshop.info")) { - int buying, selling, doubles, chunks, worlds; - buying = selling = doubles = chunks = worlds = 0; - int nostock = 0; - for (HashMap> inWorld : plugin.getShopManager().getShops().values()) { - worlds++; - for (HashMap inChunk : inWorld.values()) { - chunks++; - for (Shop shop : inChunk.values()) { - if (shop.isBuying()) { - buying++; - } else if (shop.isSelling()) { - selling++; - } - if (shop instanceof ContainerShop && ((ContainerShop) shop).isDoubleShop()) { - doubles++; - } else if (shop.isSelling() && shop.getRemainingStock() == 0) { - nostock++; - } - } - } - } - sender.sendMessage(ChatColor.RED + "QuickShop Statistics..."); - sender.sendMessage(ChatColor.GREEN + "" + (buying + selling) + " shops in " + chunks + " chunks spread over " + worlds + " worlds."); - sender.sendMessage(ChatColor.GREEN + "" + doubles + " double shops. "); - sender.sendMessage(ChatColor.GREEN + "" + nostock + " selling shops (excluding doubles) which will be removed by /qs clean."); - return true; - } - sender.sendMessage(MsgUtil.getMessage("no-permission")); - return true; - } - } else { - // Invalid arg given - sendHelp(sender); - return true; - } - // No args given - sendHelp(sender); - return true; - } - - /** - * Returns loc with modified pitch/yaw angles so it faces lookat - * - * @param loc - * The location a players head is - * @param lookat - * The location they should be looking - * @return The location the player should be facing to have their crosshairs - * on the location lookAt Kudos to bergerkiller for most of this - * function - */ - public Location lookAt(Location loc, Location lookat) { - // Clone the loc to prevent applied changes to the input loc - loc = loc.clone(); - // Values of change in distance (make it relative) - double dx = lookat.getX() - loc.getX(); - double dy = lookat.getY() - loc.getY(); - double dz = lookat.getZ() - loc.getZ(); - // Set yaw - if (dx != 0) { - // Set yaw start value based on dx - if (dx < 0) { - loc.setYaw((float) (1.5 * Math.PI)); - } else { - loc.setYaw((float) (0.5 * Math.PI)); - } - loc.setYaw((float) loc.getYaw() - (float) Math.atan(dz / dx)); - } else if (dz < 0) { - loc.setYaw((float) Math.PI); - } - // Get the distance from dx/dz - double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); - float pitch = (float) -Math.atan(dy / dxz); - // Set values, convert to degrees - // Minecraft yaw (vertical) angles are inverted (negative) - loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI + 360); - // But pitch angles are normal - loc.setPitch(pitch * 180f / (float) Math.PI); - return loc; - } - - public void sendHelp(CommandSender s) { - s.sendMessage(MsgUtil.getMessage("command.description.title")); - if (s.hasPermission("quickshop.unlimited")) - s.sendMessage(ChatColor.GREEN + "/qs unlimited" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.unlimited")); - if (s.hasPermission("quickshop.setowner")) - s.sendMessage(ChatColor.GREEN + "/qs setowner " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.setowner")); - if (s.hasPermission("quickshop.create.buy")) - s.sendMessage(ChatColor.GREEN + "/qs buy" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.buy")); - if (s.hasPermission("quickshop.create.sell")) { - s.sendMessage(ChatColor.GREEN + "/qs sell" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.sell")); - s.sendMessage(ChatColor.GREEN + "/qs create [price]" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.create")); - } - if (s.hasPermission("quickshop.create.changeprice")) - s.sendMessage(ChatColor.GREEN + "/qs price" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.price")); - if (s.hasPermission("quickshop.clean")) - s.sendMessage(ChatColor.GREEN + "/qs clean" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.clean")); - if (s.hasPermission("quickshop.find")) - s.sendMessage(ChatColor.GREEN + "/qs find " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.find")); - if (s.hasPermission("quickshop.refill")) - s.sendMessage(ChatColor.GREEN + "/qs refill " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.refill")); - if (s.hasPermission("quickshop.empty")) - s.sendMessage(ChatColor.GREEN + "/qs empty" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.empty")); - if (s.hasPermission("quickshop.export")) - s.sendMessage(ChatColor.GREEN + "/qs export mysql|sqlite" + ChatColor.YELLOW + " - Exports the database to SQLite or MySQL"); - } +package org.maxgamer.quickshop.Command; + +import java.io.File; +import java.util.HashMap; +import java.util.Iterator; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BlockIterator; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Database.Database; +import org.maxgamer.quickshop.Database.MySQLCore; +import org.maxgamer.quickshop.Database.SQLiteCore; +import org.maxgamer.quickshop.Shop.ContainerShop; +import org.maxgamer.quickshop.Shop.Info; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Shop.ShopAction; +import org.maxgamer.quickshop.Shop.ShopChunk; +import org.maxgamer.quickshop.Shop.ShopType; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Util; + +public class QS implements CommandExecutor { + QuickShop plugin; + + public QS(QuickShop plugin) { + this.plugin = plugin; + } + + private void setUnlimited(CommandSender sender) { + if (sender instanceof Player && sender.hasPermission("quickshop.unlimited")) { + BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.setUnlimited(!shop.isUnlimited()); + shop.update(); + sender.sendMessage(MsgUtil.getMessage("command.toggle-unlimited", (shop.isUnlimited() ? "unlimited" : "limited"))); + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + + private void remove(CommandSender sender, String[] args) { + if (sender instanceof Player == false) { + sender.sendMessage(ChatColor.RED + "Only players may use that command."); + return; + } + if (!sender.hasPermission("quickshop.delete")) { + sender.sendMessage(ChatColor.RED + "You do not have permission to use that command. Try break the shop instead?"); + return; + } + Player p = (Player) sender; + BlockIterator bIt = new BlockIterator(p, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (shop.getOwner().equals(p.getUniqueId())) { + shop.delete(); + sender.sendMessage(ChatColor.GREEN + "Success. Deleted shop."); + } else { + p.sendMessage(ChatColor.RED + "That's not your shop!"); + } + return; + } + } + p.sendMessage(ChatColor.RED + "No shop found!"); + } + + private void export(CommandSender sender, String[] args) { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: /qs export mysql|sqlite"); + return; + } + String type = args[1].toLowerCase(); + if (type.startsWith("mysql")) { + if (plugin.getDB().getCore() instanceof MySQLCore) { + sender.sendMessage(ChatColor.RED + "Database is already MySQL"); + return; + } + ConfigurationSection cfg = plugin.getConfig().getConfigurationSection("database"); + String host = cfg.getString("host"); + String port = cfg.getString("port"); + String user = cfg.getString("user"); + String pass = cfg.getString("password"); + String name = cfg.getString("database"); + MySQLCore core = new MySQLCore(host, user, pass, name, port); + Database target; + try { + target = new Database(core); + QuickShop.instance.getDB().copyTo(target); + sender.sendMessage(ChatColor.GREEN + "Success - Exported to MySQL " + user + "@" + host + "." + name); + } catch (Exception e) { + e.printStackTrace(); + sender.sendMessage(ChatColor.RED + "Failed to export to MySQL " + user + "@" + host + "." + name + ChatColor.DARK_RED + " Reason: " + e.getMessage()); + } + return; + } + if (type.startsWith("sql") || type.contains("file")) { + if (plugin.getDB().getCore() instanceof SQLiteCore) { + sender.sendMessage(ChatColor.RED + "Database is already SQLite"); + return; + } + File file = new File(plugin.getDataFolder(), "shops.db"); + if (file.exists()) { + if (file.delete() == false) { + sender.sendMessage(ChatColor.RED + "Warning: Failed to delete old shops.db file. This may cause errors."); + } + } + SQLiteCore core = new SQLiteCore(file); + try { + Database target = new Database(core); + QuickShop.instance.getDB().copyTo(target); + sender.sendMessage(ChatColor.GREEN + "Success - Exported to SQLite: " + file.toString()); + } catch (Exception e) { + e.printStackTrace(); + sender.sendMessage(ChatColor.RED + "Failed to export to SQLite: " + file.toString() + " Reason: " + e.getMessage()); + } + return; + } + sender.sendMessage(ChatColor.RED + "No target given. Usage: /qs export mysql|sqlite"); + } + + private void setOwner(CommandSender sender, String[] args) { + if (sender instanceof Player && sender.hasPermission("quickshop.setowner")) { + if (args.length < 2) { + sender.sendMessage(MsgUtil.getMessage("command.no-owner-given")); + return; + } + BlockIterator bIt = new BlockIterator((Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + @SuppressWarnings("deprecation") + OfflinePlayer p = this.plugin.getServer().getOfflinePlayer(args[1]); + shop.setOwner(p.getUniqueId()); + shop.update(); + sender.sendMessage(MsgUtil.getMessage("command.new-owner", this.plugin.getServer().getOfflinePlayer(shop.getOwner()).getName())); + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + + private void refill(CommandSender sender, String[] args) { + if (sender instanceof Player && sender.hasPermission("quickshop.refill")) { + if (args.length < 2) { + sender.sendMessage(MsgUtil.getMessage("command.no-amount-given")); + return; + } + int add; + try { + add = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(MsgUtil.getMessage("thats-not-a-number")); + return; + } + BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + shop.add(shop.getItem(), add); + sender.sendMessage(MsgUtil.getMessage("refill-success")); + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + + private void empty(CommandSender sender, String[] args) { + if (sender instanceof Player && sender.hasPermission("quickshop.refill")) { + BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null) { + if (shop instanceof ContainerShop) { + ContainerShop cs = (ContainerShop) shop; + cs.getInventory().clear(); + sender.sendMessage(MsgUtil.getMessage("empty-success")); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + + private void find(CommandSender sender, String[] args) { + if (sender instanceof Player && sender.hasPermission("quickshop.find")) { + if (args.length < 2) { + sender.sendMessage(MsgUtil.getMessage("command.no-type-given")); + return; + } + StringBuilder sb = new StringBuilder(args[1]); + for (int i = 2; i < args.length; i++) { + sb.append(" " + args[i]); + } + String lookFor = sb.toString(); + lookFor = lookFor.toLowerCase(); + Player p = (Player) sender; + Location loc = p.getEyeLocation().clone(); + double minDistance = plugin.getConfig().getInt("shop.find-distance"); + double minDistanceSquared = minDistance * minDistance; + int chunkRadius = (int) minDistance / 16 + 1; + Shop closest = null; + Chunk c = loc.getChunk(); + for (int x = -chunkRadius + c.getX(); x < chunkRadius + c.getX(); x++) { + for (int z = -chunkRadius + c.getZ(); z < chunkRadius + c.getZ(); z++) { + Chunk d = c.getWorld().getChunkAt(x, z); + HashMap inChunk = plugin.getShopManager().getShops(d); + if (inChunk == null) + continue; + for (Shop shop : inChunk.values()) { + if (shop.getDataName().toLowerCase().contains(lookFor) && shop.getLocation().distanceSquared(loc) < minDistanceSquared) { + closest = shop; + minDistanceSquared = shop.getLocation().distanceSquared(loc); + } + } + } + } + if (closest == null) { + sender.sendMessage(MsgUtil.getMessage("no-nearby-shop", args[1])); + return; + } + Location lookat = closest.getLocation().clone().add(0.5, 0.5, 0.5); + // Hack fix to make /qs find not used by /back + p.teleport(this.lookAt(loc, lookat).add(0, -1.62, 0), TeleportCause.UNKNOWN); + p.sendMessage(MsgUtil.getMessage("nearby-shop-this-way", "" + (int) Math.floor(Math.sqrt(minDistanceSquared)))); + return; + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + } + + @SuppressWarnings("deprecation") + private void create(CommandSender sender, String[] args) { + if (sender instanceof Player) { + Player p = (Player) sender; + ItemStack item = p.getItemInHand(); + if (item.getType()!=Material.AIR) { + if (sender.hasPermission("quickshop.create.sell")) { + BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); + + while (bIt.hasNext()) { + Block b = bIt.next(); + + if (Util.canBeShop(b)) { + PlayerInteractEvent e = new PlayerInteractEvent(p, Action.LEFT_CLICK_BLOCK, item, b, BlockFace.UP); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled()) { + return; + } + + if (!plugin.getShopManager().canBuildShop(p, b, Util.getYawFace(p.getLocation().getYaw()))) { + // 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. + 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 (args.length<2) { + // Send creation menu. + Info info = new Info(b.getLocation(), ShopAction.CREATE, p.getItemInHand(), b.getRelative(Util.getYawFace(p.getLocation().getYaw()))); + plugin.getShopManager().getActions().put(p.getUniqueId(), info); + p.sendMessage(MsgUtil.getMessage("how-much-to-trade-for", Util.getName(info.getItem()))); + } else { + plugin.getShopManager().handleChat(p, args[1]); + } + return; + } + } + } else { + sender.sendMessage(MsgUtil.getMessage("no-permission")); + } + } else { + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + } + } else { + sender.sendMessage("This command can't be run by console"); + } + return; + } + + private void amount(CommandSender sender, String[] args) { + if (args.length < 2) { + sender.sendMessage("Missing amount"); + return; + } + + if (sender instanceof Player) { + final Player player = (Player) sender; + if (!plugin.getShopManager().getActions().containsKey(player.getUniqueId())) { + sender.sendMessage("You do not have any pending action!"); + return; + } + plugin.getShopManager().handleChat(player, args[1]); + } else { + sender.sendMessage("This command can't be run by console"); + } + return; + } + + private void setBuy(CommandSender sender) { + if (sender instanceof Player && sender.hasPermission("quickshop.create.buy")) { + BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && shop.getOwner().equals(((Player) sender).getUniqueId())) { + shop.setShopType(ShopType.BUYING); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.getMessage("command.now-buying", shop.getDataName())); + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + + private void setSell(CommandSender sender) { + if (sender instanceof Player && sender.hasPermission("quickshop.create.sell")) { + BlockIterator bIt = new BlockIterator((LivingEntity) (Player) sender, 10); + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && shop.getOwner().equals(((Player) sender).getUniqueId())) { + shop.setShopType(ShopType.SELLING); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.getMessage("command.now-selling", shop.getDataName())); + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + + @SuppressWarnings("deprecation") + private void setPrice(CommandSender sender, String[] args) { + if (sender instanceof Player && sender.hasPermission("quickshop.create.changeprice")) { + Player p = (Player) sender; + if (args.length < 2) { + sender.sendMessage(MsgUtil.getMessage("no-price-given")); + return; + } + double price; + try { + price = Double.parseDouble(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(MsgUtil.getMessage("thats-not-a-number")); + return; + } + if (price < 0.01) { + sender.sendMessage(MsgUtil.getMessage("price-too-cheap")); + return; + } + double fee = 0; + if (plugin.priceChangeRequiresFee) { + fee = plugin.getConfig().getDouble("shop.fee-for-price-change"); + if (fee > 0 && plugin.getEcon().getBalance(p.getUniqueId()) < fee) { + sender.sendMessage(MsgUtil.getMessage("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); + return; + } + } + BlockIterator bIt = new BlockIterator(p, 10); + // Loop through every block they're looking at upto 10 blocks away + while (bIt.hasNext()) { + Block b = bIt.next(); + Shop shop = plugin.getShopManager().getShop(b.getLocation()); + if (shop != null && (shop.getOwner().equals(((Player) sender).getUniqueId()) || sender.hasPermission("quickshop.other.price"))) { + if (shop.getPrice() == price) { + // Stop here if there isn't a price change + sender.sendMessage(MsgUtil.getMessage("no-price-change")); + return; + } + if (fee > 0) { + if (!plugin.getEcon().withdraw(p.getUniqueId(), fee)) { + sender.sendMessage(MsgUtil.getMessage("you-cant-afford-to-change-price", plugin.getEcon().format(fee))); + return; + } + sender.sendMessage(MsgUtil.getMessage("fee-charged-for-price-change", plugin.getEcon().format(fee))); + plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), fee); + } + // Update the shop + shop.setPrice(price); + shop.setSignText(); + shop.update(); + sender.sendMessage(MsgUtil.getMessage("price-is-now", plugin.getEcon().format(shop.getPrice()))); + // Chest shops can be double shops. + if (shop instanceof ContainerShop) { + ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) { + Shop nextTo = cs.getAttachedShop(); + if (cs.isSelling()) { + if (cs.getPrice() < nextTo.getPrice()) { + sender.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); + } + } else { + // Buying + if (cs.getPrice() > nextTo.getPrice()) { + sender.sendMessage(MsgUtil.getMessage("buying-more-than-selling")); + } + } + } + } + return; + } + } + sender.sendMessage(MsgUtil.getMessage("not-looking-at-shop")); + return; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + + private void clean(CommandSender sender) { + if (sender.hasPermission("quickshop.clean")) { + sender.sendMessage(MsgUtil.getMessage("command.cleaning")); + Iterator shIt = plugin.getShopManager().getShopIterator(); + int i = 0; + while (shIt.hasNext()) { + Shop shop = shIt.next(); + + try { + if (shop.getLocation().getWorld() != null && shop.isSelling() && shop.getRemainingStock() == 0 && shop instanceof ContainerShop) { + ContainerShop cs = (ContainerShop) shop; + if (cs.isDoubleShop()) + continue; + shIt.remove(); // Is selling, but has no stock, and is a chest shop, but is not a double shop. Can be deleted safely. + i++; + } + } catch (IllegalStateException e) { + shIt.remove(); // The shop is not there anymore, remove it + } + } + MsgUtil.clean(); + sender.sendMessage(MsgUtil.getMessage("command.cleaned", "" + i)); + return; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + + private void reload(CommandSender sender) { + if (sender.hasPermission("quickshop.reload")) { + sender.sendMessage(MsgUtil.getMessage("command.reloading")); + Bukkit.getPluginManager().disablePlugin(plugin); + Bukkit.getPluginManager().enablePlugin(plugin); + return; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { + if (args.length > 0) { + String subArg = args[0].toLowerCase(); + if (subArg.equals("unlimited")) { + setUnlimited(sender); + return true; + } else if (subArg.equals("setowner")) { + setOwner(sender, args); + return true; + } else if (subArg.equals("find")) { + find(sender, args); + return true; + } else if (subArg.startsWith("create")) { + create(sender, args); + return true; + } else if (subArg.startsWith("amount")) { + amount(sender, args); + return true; + } else if (subArg.startsWith("buy")) { + setBuy(sender); + return true; + } else if (subArg.startsWith("sell")) { + setSell(sender); + return true; + } else if (subArg.startsWith("price")) { + setPrice(sender, args); + return true; + } else if (subArg.equals("remove")) { + remove(sender, args); + } else if (subArg.equals("refill")) { + refill(sender, args); + return true; + } else if (subArg.equals("empty")) { + empty(sender, args); + return true; + } else if (subArg.equals("clean")) { + clean(sender); + return true; + } else if (subArg.equals("reload")) { + reload(sender); + return true; + } else if (subArg.equals("export")) { + export(sender, args); + return true; + } else if (subArg.equals("info")) { + if (sender.hasPermission("quickshop.info")) { + int buying, selling, doubles, chunks, worlds; + buying = selling = doubles = chunks = worlds = 0; + int nostock = 0; + for (HashMap> inWorld : plugin.getShopManager().getShops().values()) { + worlds++; + for (HashMap inChunk : inWorld.values()) { + chunks++; + for (Shop shop : inChunk.values()) { + if (shop.isBuying()) { + buying++; + } else if (shop.isSelling()) { + selling++; + } + if (shop instanceof ContainerShop && ((ContainerShop) shop).isDoubleShop()) { + doubles++; + } else if (shop.isSelling() && shop.getRemainingStock() == 0) { + nostock++; + } + } + } + } + sender.sendMessage(ChatColor.RED + "QuickShop Statistics..."); + sender.sendMessage(ChatColor.GREEN + "" + (buying + selling) + " shops in " + chunks + " chunks spread over " + worlds + " worlds."); + sender.sendMessage(ChatColor.GREEN + "" + doubles + " double shops. "); + sender.sendMessage(ChatColor.GREEN + "" + nostock + " selling shops (excluding doubles) which will be removed by /qs clean."); + return true; + } + sender.sendMessage(MsgUtil.getMessage("no-permission")); + return true; + } + } else { + // Invalid arg given + sendHelp(sender); + return true; + } + // No args given + sendHelp(sender); + return true; + } + + /** + * Returns loc with modified pitch/yaw angles so it faces lookat + * + * @param loc + * The location a players head is + * @param lookat + * The location they should be looking + * @return The location the player should be facing to have their crosshairs + * on the location lookAt Kudos to bergerkiller for most of this + * function + */ + public Location lookAt(Location loc, Location lookat) { + // Clone the loc to prevent applied changes to the input loc + loc = loc.clone(); + // Values of change in distance (make it relative) + double dx = lookat.getX() - loc.getX(); + double dy = lookat.getY() - loc.getY(); + double dz = lookat.getZ() - loc.getZ(); + // Set yaw + if (dx != 0) { + // Set yaw start value based on dx + if (dx < 0) { + loc.setYaw((float) (1.5 * Math.PI)); + } else { + loc.setYaw((float) (0.5 * Math.PI)); + } + loc.setYaw((float) loc.getYaw() - (float) Math.atan(dz / dx)); + } else if (dz < 0) { + loc.setYaw((float) Math.PI); + } + // Get the distance from dx/dz + double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2)); + float pitch = (float) -Math.atan(dy / dxz); + // Set values, convert to degrees + // Minecraft yaw (vertical) angles are inverted (negative) + loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI + 360); + // But pitch angles are normal + loc.setPitch(pitch * 180f / (float) Math.PI); + return loc; + } + + public void sendHelp(CommandSender s) { + s.sendMessage(MsgUtil.getMessage("command.description.title")); + if (s.hasPermission("quickshop.unlimited")) + s.sendMessage(ChatColor.GREEN + "/qs unlimited" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.unlimited")); + if (s.hasPermission("quickshop.setowner")) + s.sendMessage(ChatColor.GREEN + "/qs setowner " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.setowner")); + if (s.hasPermission("quickshop.create.buy")) + s.sendMessage(ChatColor.GREEN + "/qs buy" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.buy")); + if (s.hasPermission("quickshop.create.sell")) { + s.sendMessage(ChatColor.GREEN + "/qs sell" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.sell")); + s.sendMessage(ChatColor.GREEN + "/qs create [price]" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.create")); + } + if (s.hasPermission("quickshop.create.changeprice")) + s.sendMessage(ChatColor.GREEN + "/qs price" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.price")); + if (s.hasPermission("quickshop.clean")) + s.sendMessage(ChatColor.GREEN + "/qs clean" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.clean")); + if (s.hasPermission("quickshop.find")) + s.sendMessage(ChatColor.GREEN + "/qs find " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.find")); + if (s.hasPermission("quickshop.refill")) + s.sendMessage(ChatColor.GREEN + "/qs refill " + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.refill")); + if (s.hasPermission("quickshop.empty")) + s.sendMessage(ChatColor.GREEN + "/qs empty" + ChatColor.YELLOW + " - " + MsgUtil.getMessage("command.description.empty")); + if (s.hasPermission("quickshop.export")) + s.sendMessage(ChatColor.GREEN + "/qs export mysql|sqlite" + ChatColor.YELLOW + " - Exports the database to SQLite or MySQL"); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/ChatListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/ChatListener.java index b9ae30af7..eb745169b 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/ChatListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/ChatListener.java @@ -1,29 +1,30 @@ -package org.maxgamer.quickshop.Listeners; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.maxgamer.quickshop.QuickShop; - -/** - * - * @author Netherfoam - * - */ -public class ChatListener implements Listener { - QuickShop plugin; - - public ChatListener(QuickShop plugin) { - this.plugin = plugin; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onChat(final AsyncPlayerChatEvent e) { - if (!plugin.getShopManager().getActions().containsKey(e.getPlayer().getUniqueId())) { - return; - } - plugin.getShopManager().handleChat(e.getPlayer(), e.getMessage()); - e.setCancelled(true); - } +package org.maxgamer.quickshop.Listeners; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.maxgamer.quickshop.QuickShop; + +/** + * + * @author Netherfoam + * + */ +public class ChatListener implements Listener { + QuickShop plugin; + + public ChatListener(QuickShop plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onChat(final AsyncPlayerChatEvent e) { + if (!plugin.getShopManager().getActions().containsKey(e.getPlayer().getUniqueId())) { + plugin.log(plugin.getShopManager().getActions().toString()); + return; + } + plugin.getShopManager().handleChat(e.getPlayer(), e.getMessage()); + e.setCancelled(true); + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/HeroChatListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/HeroChatListener.java deleted file mode 100644 index f19098179..000000000 --- a/src/main/java/org/maxgamer/quickshop/Listeners/HeroChatListener.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.maxgamer.quickshop.Listeners; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.maxgamer.quickshop.QuickShop; - -import com.dthielke.herochat.ChannelChatEvent; -import com.dthielke.herochat.Chatter.Result; - -/** - * - * @author Netherfoam - * - */ -public class HeroChatListener implements Listener { - QuickShop plugin; - - public HeroChatListener(QuickShop plugin) { - this.plugin = plugin; - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) - public void onHeroChat(ChannelChatEvent e) { - if (!plugin.getShopManager().getActions().containsKey(e.getSender().getPlayer().getUniqueId())) - return; - plugin.getShopManager().handleChat(e.getSender().getPlayer(), e.getMessage()); - e.setResult(Result.FAIL); - } -} diff --git a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java index ae5f579ec..9722734ef 100644 --- a/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java +++ b/src/main/java/org/maxgamer/quickshop/Listeners/PlayerListener.java @@ -1,228 +1,228 @@ -package org.maxgamer.quickshop.Listeners; - -import java.util.HashMap; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -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.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerPickupItemEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -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; - -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 - */ - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.MONITOR) - public void onClick(PlayerInteractEvent e) { - if (e.getAction() != Action.LEFT_CLICK_BLOCK) - return; - Block b = e.getClickedBlock(); - if (!Util.canBeShop(b) && b.getType() != Material.WALL_SIGN) - return; - Player p = e.getPlayer(); - if (plugin.sneak && !p.isSneaking()) { - // Sneak only - return; - } - 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") && (plugin.sneakTrade == false || p.isSneaking())) { - shop.onClick(); - // Text menu - MsgUtil.sendShopInfo(p, shop); - 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) && p.getGameMode() != GameMode.CREATIVE && (plugin.sneakCreate == false || p.isSneaking())) { - 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. - 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.getTypeId())) { - p.sendMessage(MsgUtil.getMessage("blacklisted-item")); - 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", Util.getName(info.getItem()))); - } - } - - @EventHandler(priority = EventPriority.HIGH) - /** - * 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 - public void onTeleport(PlayerTeleportEvent e) { - PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); - onMove(me); - } - - @EventHandler - public void onJoin(final PlayerJoinEvent e) { - // Notify the player any messages they were sent - Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { - @Override - public void run() { - MsgUtil.flush(e.getPlayer()); - } - }, 60); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent e) { - // Remove them from the menu - plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId()); - } - - @EventHandler - public void onPlayerPickup(PlayerPickupItemEvent e) { - ItemStack stack = e.getItem().getItemStack(); - try { - if (stack.getItemMeta().getDisplayName().startsWith(ChatColor.RED + "QuickShop ")) { - e.setCancelled(true); - // You shouldn't be able to pick up that... - } - } catch (NullPointerException ex) { - } // if meta/displayname/stack is null. We don't really care in that case. - } - - @EventHandler - public void onInventoryClose(InventoryCloseEvent e) { - try { - final Inventory inventory = e.getInventory(); - if (inventory == null) { - return; - } - - final Location location = inventory.getLocation(); - if (location == null) { - return; - } - - final Shop shop = plugin.getShopManager().getShop(location); - if (shop == null) { - return; - } - - shop.setSignText(); - } catch (Throwable t) { - - } - } -} +package org.maxgamer.quickshop.Listeners; + +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +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.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +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; + +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 + */ + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.MONITOR) + public void onClick(PlayerInteractEvent e) { + if (e.getAction() != Action.LEFT_CLICK_BLOCK) + return; + Block b = e.getClickedBlock(); + if (!Util.canBeShop(b) && b.getType() != Material.WALL_SIGN) + return; + Player p = e.getPlayer(); + if (plugin.sneak && !p.isSneaking()) { + // Sneak only + return; + } + 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") && (plugin.sneakTrade == false || p.isSneaking())) { + shop.onClick(); + // Text menu + MsgUtil.sendShopInfo(p, shop); + 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) && p.getGameMode() != GameMode.CREATIVE && (plugin.sneakCreate == false || p.isSneaking())) { + 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. + 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; + } + // 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", Util.getName(info.getItem()))); + } + } + + @EventHandler(priority = EventPriority.HIGH) + /** + * 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 + public void onTeleport(PlayerTeleportEvent e) { + PlayerMoveEvent me = new PlayerMoveEvent(e.getPlayer(), e.getFrom(), e.getTo()); + onMove(me); + } + + @EventHandler + public void onJoin(final PlayerJoinEvent e) { + // Notify the player any messages they were sent + Bukkit.getScheduler().runTaskLater(QuickShop.instance, new Runnable() { + @Override + public void run() { + MsgUtil.flush(e.getPlayer()); + } + }, 60); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent e) { + // Remove them from the menu + plugin.getShopManager().getActions().remove(e.getPlayer().getUniqueId()); + } + + @EventHandler + public void onPlayerPickup(PlayerPickupItemEvent e) { + ItemStack stack = e.getItem().getItemStack(); + try { + if (stack.getItemMeta().getDisplayName().startsWith(ChatColor.RED + "QuickShop ")) { + e.setCancelled(true); + // You shouldn't be able to pick up that... + } + } catch (NullPointerException ex) { + } // if meta/displayname/stack is null. We don't really care in that case. + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent e) { + try { + final Inventory inventory = e.getInventory(); + if (inventory == null) { + return; + } + + final Location location = inventory.getLocation(); + if (location == null) { + return; + } + + final Shop shop = plugin.getShopManager().getShop(location); + if (shop == null) { + return; + } + + shop.setSignText(); + } catch (Throwable t) { + + } + } +} diff --git a/src/main/java/org/maxgamer/quickshop/QuickShop.java b/src/main/java/org/maxgamer/quickshop/QuickShop.java index d5ba7b56a..459ba8d97 100644 --- a/src/main/java/org/maxgamer/quickshop/QuickShop.java +++ b/src/main/java/org/maxgamer/quickshop/QuickShop.java @@ -1,580 +1,574 @@ -package org.maxgamer.quickshop; - -import java.io.File; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import org.maxgamer.quickshop.Command.QS; -import org.maxgamer.quickshop.Database.Database; -import org.maxgamer.quickshop.Database.Database.ConnectionException; -import org.maxgamer.quickshop.Database.DatabaseCore; -import org.maxgamer.quickshop.Database.DatabaseHelper; -import org.maxgamer.quickshop.Database.MySQLCore; -import org.maxgamer.quickshop.Database.SQLiteCore; -import org.maxgamer.quickshop.Economy.Economy; -import org.maxgamer.quickshop.Economy.EconomyCore; -import org.maxgamer.quickshop.Economy.Economy_Vault; -import org.maxgamer.quickshop.Listeners.BlockListener; -import org.maxgamer.quickshop.Listeners.ChatListener; -import org.maxgamer.quickshop.Listeners.ChunkListener; -import org.maxgamer.quickshop.Listeners.HeroChatListener; -import org.maxgamer.quickshop.Listeners.DisplayProtectionListener; -import org.maxgamer.quickshop.Listeners.LockListener; -import org.maxgamer.quickshop.Listeners.PlayerListener; -import org.maxgamer.quickshop.Listeners.WorldListener; -import org.maxgamer.quickshop.Shop.ContainerShop; -import org.maxgamer.quickshop.Shop.Shop; -import org.maxgamer.quickshop.Shop.ShopManager; -import org.maxgamer.quickshop.Shop.ShopType; -import org.maxgamer.quickshop.Util.CustomItemName; -import org.maxgamer.quickshop.Util.CustomPotionsName; -import org.maxgamer.quickshop.Util.MsgUtil; -import org.maxgamer.quickshop.Util.NMS; -import org.maxgamer.quickshop.Util.Permissions; -import org.maxgamer.quickshop.Util.Util; -import org.maxgamer.quickshop.Watcher.ItemWatcher; -import org.maxgamer.quickshop.Watcher.LogWatcher; - - -@SuppressWarnings("deprecation") -public class QuickShop extends JavaPlugin { - /** The active instance of QuickShop */ - public static QuickShop instance; - /** The economy we hook into for transactions */ - private Economy economy; - /** The Shop Manager used to store shops */ - private ShopManager shopManager; - /** - * A set of players who have been warned - * ("Your shop isn't automatically locked") - */ - public HashSet warnings = new HashSet(); - /** The database for storing all our data for persistence */ - private Database database; - // Listeners - We decide which one to use at runtime - private ChatListener chatListener; - private HeroChatListener heroChatListener; - // Listeners (These don't) - private BlockListener blockListener; - private PlayerListener playerListener; - private DisplayProtectionListener inventoryListener; - private ChunkListener chunkListener; - private WorldListener worldListener; - private BukkitTask itemWatcherTask; - private LogWatcher logWatcher; - /** Whether players are required to sneak to create/buy from a shop */ - public boolean sneak; - /** Whether players are required to sneak to create a shop */ - public boolean sneakCreate; - /** Whether players are required to sneak to trade with a shop */ - public boolean sneakTrade; - /** Whether we should use display items or not */ - public boolean display = true; - /** - * Whether we players are charged a fee to change the price on their shop - * (To help deter endless undercutting - */ - public boolean priceChangeRequiresFee = false; - /** Whether or not to limit players shop amounts */ - public boolean limit = false; - - /** The plugin OpenInv (null if not present) */ - public Plugin openInvPlugin; - - private HashMap limits = new HashMap(); - /** Use SpoutPlugin to get item / block names */ - public boolean useSpout = false; - // private Metrics metrics; - /** Whether debug info should be shown in the console */ - public static boolean debug = false; - - private Map> customItemsName = new HashMap>(); - - private int displayItemCheckTicks; - - /** The plugin metrics from Hidendra */ - // public Metrics getMetrics(){ return metrics; } - public int getShopLimit(Player p) { - int max = getConfig().getInt("limits.default"); - for (Entry entry : limits.entrySet()) { - if (entry.getValue() > max && p.hasPermission(entry.getKey())) - max = entry.getValue(); - } - return max; - } - - public void onEnable() { - NMS.init(); - - instance = this; - saveDefaultConfig(); // Creates the config folder and copies config.yml - // (If one doesn't exist) as required. - reloadConfig(); // Reloads messages.yml too, aswell as config.yml and - // others. - getConfig().options().copyDefaults(true); // Load defaults. - if (getConfig().contains("debug")) - debug = true; - if (loadEcon() == false) - return; - - if (Permissions.init()) { - getLogger().info("Found permission provider."); - } else { - getLogger().info("Couldn't find a Vault permission provider. Some feature may be limited."); - } - - // Initialize Util - Util.initialize(); - - // Create the shop manager. - this.shopManager = new ShopManager(this); - if (this.display) { - // Display item handler thread - getLogger().info("Starting item scheduler"); - ItemWatcher itemWatcher = new ItemWatcher(this); - itemWatcherTask = Bukkit.getScheduler().runTaskTimer(this, itemWatcher, 600, 600); - } - if (this.getConfig().getBoolean("log-actions")) { - // Logger Handler - this.logWatcher = new LogWatcher(this, new File(this.getDataFolder(), "qs.log")); - logWatcher.task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, this.logWatcher, 150, 150); - } - if (getConfig().getBoolean("shop.lock")) { - LockListener ll = new LockListener(this); - getServer().getPluginManager().registerEvents(ll, this); - } - - if (this.getConfig().isSet("custom-items-name")) { - for (String s : this.getConfig().getStringList("custom-items-name")) { - try { - String[] mainVal = s.split("[;]"); - if (mainVal.length!=3) { - throw new Exception("Invalid format (main args length must be 3)"); - } - - String[] matVal = mainVal[0].split("[*]"); - Material material = Material.matchMaterial(matVal[0]); - if (material==null) { - throw new Exception("Invalid material: "+matVal[0]); - } - - ItemStack is; - if (matVal.length>1) { - try { - is = new ItemStack(material, 1, Short.valueOf(matVal[1])); - } catch (Exception e) { - throw new Exception("Invalid data value: "+matVal[1]); - } - } else { - is = new ItemStack(material, 1, (short) 0); - } - - if (mainVal[1].length()>16) { - Bukkit.getLogger().warning("Custom item name definition {"+s+"} sign name is longer than 16 characters. Only the first 16 characters will be shown."); - } - - List cinList = customItemsName.get(material); - if (cinList==null) { - cinList = new ArrayList(); - customItemsName.put(material, cinList); - } - - cinList.add(new CustomItemName(is, mainVal[1], mainVal[2])); - } catch (Exception e) { - Bukkit.getLogger().warning("Invalid custom item name definition {"+s+"} Error: "+e.getMessage()); - } - } - } - - ConfigurationSection cPotionSection = this.getConfig().getConfigurationSection("custom-potions-name"); - if (cPotionSection!=null) { - CustomPotionsName.setSignFormat(new String[]{cPotionSection.getString("sign.format"), cPotionSection.getString("sign.variety.normal"), cPotionSection.getString("sign.variety.splash"), cPotionSection.getString("sign.variety.lingering")}); - CustomPotionsName.setShopInfoFormat(new String[]{cPotionSection.getString("shopinfo.format"), cPotionSection.getString("shopinfo.variety.normal"), cPotionSection.getString("shopinfo.variety.splash"), cPotionSection.getString("shopinfo.variety.lingering")}); - - Map potionTypes = new HashMap(); - for (String s : cPotionSection.getStringList("types")) { - try { - String[] a = s.split("[;]"); - if (a.length!=3) { - throw new Exception("Invalid format (main args length must be 3)"); - } - - PotionType type = PotionType.valueOf(a[0].toUpperCase()); - if (type==null) { - throw new Exception("Invalid PotionType "+a[0]); - } - - potionTypes.put(type, new CustomPotionsName.Names(a[1], a[2])); - } catch (Exception e) { - Bukkit.getLogger().warning("Invalid potion item name definition {"+s+"} Error: "+e.getMessage()); - } - } - CustomPotionsName.setPotionTypes(potionTypes); - - Map potionEffects = new HashMap(); - for (String s : cPotionSection.getStringList("effects")) { - try { - String[] a = s.split("[;]"); - if (a.length!=2) { - throw new Exception("Invalid format (main args length must be 2)"); - } - - PotionEffectType type = PotionEffectType.getByName(a[0]); - if (type==null) { - throw new Exception("Invalid PotionEffectType "+a[0]); - } - - potionEffects.put(type, a[1]); - } catch (Exception e) { - Bukkit.getLogger().warning("Invalid potion effect type name definition {"+s+"} Error: "+e.getMessage()); - } - } - CustomPotionsName.setPotionEffects(potionEffects); - } - - ConfigurationSection limitCfg = this.getConfig().getConfigurationSection("limits"); - if (limitCfg != null) { - getLogger().info("Limit cfg found..."); - this.limit = limitCfg.getBoolean("use", false); - getLogger().info("Limits.use: " + limit); - limitCfg = limitCfg.getConfigurationSection("ranks"); - for (String key : limitCfg.getKeys(true)) { - limits.put(key, limitCfg.getInt(key)); - } - getLogger().info(limits.toString()); - } - try { - ConfigurationSection dbCfg = getConfig().getConfigurationSection("database"); - DatabaseCore dbCore; - if (dbCfg.getBoolean("mysql")) { - // MySQL database - Required database be created first. - String user = dbCfg.getString("user"); - String pass = dbCfg.getString("password"); - String host = dbCfg.getString("host"); - String port = dbCfg.getString("port"); - String database = dbCfg.getString("database"); - dbCore = new MySQLCore(host, user, pass, database, port); - } else { - // SQLite database - Doing this handles file creation - dbCore = new SQLiteCore(new File(this.getDataFolder(), "shops.db")); - } - this.database = new Database(dbCore); - // Make the database up to date - DatabaseHelper.setup(getDB()); - } catch (ConnectionException e) { - e.printStackTrace(); - getLogger().severe("Error connecting to database. Aborting plugin load."); - getServer().getPluginManager().disablePlugin(this); - return; - } catch (SQLException e) { - e.printStackTrace(); - getLogger().severe("Error setting up database. Aborting plugin load."); - getServer().getPluginManager().disablePlugin(this); - return; - } - /* Load shops from database to memory */ - int count = 0; // Shops count - Connection con; - try { - getLogger().info("Loading shops from database..."); - /*int res = Converter.convert(); - if (res < 0) { - System.out.println("Could not convert shops. Exitting."); - return; - } - if (res > 0) { - System.out.println("Conversion success. Continuing..."); - }*/ - con = database.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT * FROM shops"); - ResultSet rs = ps.executeQuery(); - int errors = 0; - while (rs.next()) { - int x = 0; - int y = 0; - int z = 0; - String worldName = null; - try { - x = rs.getInt("x"); - y = rs.getInt("y"); - z = rs.getInt("z"); - worldName = rs.getString("world"); - World world = Bukkit.getWorld(worldName); - ItemStack item = Util.deserialize(rs.getString("itemConfig")); - String owner = rs.getString("owner"); - UUID ownerUUID = null; - try { - ownerUUID = UUID.fromString(owner); - } catch (IllegalArgumentException e) { - // This could be old data to be converted... check if it's a player - OfflinePlayer player = Bukkit.getOfflinePlayer(owner); - if (player.hasPlayedBefore()) { - ownerUUID = player.getUniqueId(); - getDB().getConnection().createStatement().executeUpdate("UPDATE shops SET owner = \""+ownerUUID.toString()+"\" WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\" LIMIT 1"); - } else { - // Invalid shop owner - getDB().getConnection().createStatement().executeUpdate("DELETE FROM shops WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\""+(getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : "")); - continue; - } - } - - double price = rs.getDouble("price"); - Location loc = new Location(world, x, y, z); - /* Skip invalid shops, if we know of any */ - if (world != null && (loc.getBlock().getState() instanceof InventoryHolder) == false) { - getLogger().info("Shop is not an InventoryHolder in " + rs.getString("world") + " at: " + x + ", " + y + ", " + z + ". Deleting."); - getDB().getConnection().createStatement().executeUpdate("DELETE FROM shops WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\""+(getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : "")); - continue; - } - int type = rs.getInt("type"); - Shop shop = new ContainerShop(loc, price, item, ownerUUID); - shop.setUnlimited(rs.getBoolean("unlimited")); - shop.setShopType(ShopType.fromID(type)); - shopManager.loadShop(rs.getString("world"), shop); - if (loc.getWorld() != null && loc.getChunk().isLoaded()) { - shop.onLoad(); - } - count++; - } catch (Exception e) { - errors++; - e.printStackTrace(); - getLogger().severe("Error loading a shop! Coords: " + worldName + " (" + x + ", " + y + ", " + z + ")..."); - if (errors < 3) { - getLogger().info("Deleting the shop..."); - PreparedStatement delps = getDB().getConnection().prepareStatement("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?"); - delps.setInt(1, x); - delps.setInt(2, y); - delps.setInt(3, z); - delps.setString(4, worldName); - delps.execute(); - } else { - getLogger().severe("Multiple errors in shops - Something seems to be wrong with your shops database! Please check it out immediately!"); - e.printStackTrace(); - } - } - } - } catch (SQLException e) { - e.printStackTrace(); - getLogger().severe("Could not load shops."); - } - - getLogger().info("Loaded " + count + " shops."); - MsgUtil.loadTransactionMessages(); - MsgUtil.clean(); - // Register events - getLogger().info("Registering Listeners"); - blockListener = new BlockListener(this); - playerListener = new PlayerListener(this); - worldListener = new WorldListener(this); - - Bukkit.getServer().getPluginManager().registerEvents(blockListener, this); - Bukkit.getServer().getPluginManager().registerEvents(playerListener, this); - if (this.display) { - inventoryListener = new DisplayProtectionListener(this); - chunkListener = new ChunkListener(this); - Bukkit.getServer().getPluginManager().registerEvents(inventoryListener, this); - Bukkit.getServer().getPluginManager().registerEvents(chunkListener, this); - } - Bukkit.getServer().getPluginManager().registerEvents(worldListener, this); - if (this.getConfig().getBoolean("force-bukkit-chat-handler", false) && Bukkit.getPluginManager().getPlugin("Herochat") != null) { - this.getLogger().info("Found Herochat... Hooking!"); - this.heroChatListener = new HeroChatListener(this); - Bukkit.getServer().getPluginManager().registerEvents(heroChatListener, this); - } else { - this.chatListener = new ChatListener(this); - Bukkit.getServer().getPluginManager().registerEvents(chatListener, this); - } - // Command handlers - QS commandExecutor = new QS(this); - getCommand("qs").setExecutor(commandExecutor); - if (getConfig().getInt("shop.find-distance") > 100) { - getLogger().severe("Shop.find-distance is too high! Pick a number under 100!"); - } - - if (display && displayItemCheckTicks>0) { - new BukkitRunnable() { - @Override - public void run() { - Iterator it = getShopManager().getShopIterator(); - while (it.hasNext()) { - Shop shop = it.next(); - if (shop instanceof ContainerShop) { - ContainerShop cShop = (ContainerShop) shop; - if (cShop.checkDisplayMoved()) { - log("Display item for "+shop+" is not on the correct location and has been removed. Probably someone is trying to cheat."); - for (Player player : getServer().getOnlinePlayers()) { - if (player.hasPermission("quickshop.alerts")) { - player.sendMessage(ChatColor.RED + "[QuickShop] Display item for "+shop+" is not on the correct location and has been removed. Probably someone is trying to cheat."); - } - } - cShop.getDisplayItem().remove(); - } - } - } - } - }.runTaskTimer(this, 1L, displayItemCheckTicks); - } - - // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 - this.openInvPlugin = Bukkit.getPluginManager().getPlugin("OpenInv"); - - getLogger().info("QuickShop loaded!"); - } - - /** Reloads QuickShops config */ - @Override - public void reloadConfig() { - super.reloadConfig(); - // Load quick variables - this.display = this.getConfig().getBoolean("shop.display-items"); - this.sneak = this.getConfig().getBoolean("shop.sneak-only"); - this.sneakCreate = this.getConfig().getBoolean("shop.sneak-to-create"); - this.sneakTrade = this.getConfig().getBoolean("shop.sneak-to-trade"); - this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee"); - this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks"); - MsgUtil.loadCfgMessages(); - } - - /** - * Tries to load the economy and its core. If this fails, it will try to use - * vault. If that fails, it will return false. - * - * @return true if successful, false if the core is invalid or is not found, - * and vault cannot be used. - */ - public boolean loadEcon() { - EconomyCore core = new Economy_Vault(); - if (core == null || !core.isValid()) { - // getLogger().severe("Economy is not valid!"); - getLogger().severe("QuickShop could not hook an economy!"); - getLogger().severe("QuickShop CANNOT start!"); - this.getPluginLoader().disablePlugin(this); - // if(econ.equals("Vault")) - // getLogger().severe("(Does Vault have an Economy to hook into?!)"); - return false; - } else { - this.economy = new Economy(core); - return true; - } - } - - public void onDisable() { - if (itemWatcherTask != null) { - itemWatcherTask.cancel(); - } - if (logWatcher != null) { - logWatcher.task.cancel(); - logWatcher.close(); // Closes the file - } - /* Remove all display items, and any dupes we can find */ - shopManager.clear(); - /* Empty the buffer */ - database.close(); - try { - this.database.getConnection().close(); - } catch (SQLException e) { - e.printStackTrace(); - } - this.warnings.clear(); - this.reloadConfig(); - } - - /** - * Returns the economy for moving currency around - * - * @return The economy for moving currency around - */ - public EconomyCore getEcon() { - return economy; - } - - /** - * Logs the given string to qs.log, if QuickShop is configured to do so. - * - * @param s - * The string to log. It will be prefixed with the date and time. - */ - public void log(String s) { - if (this.logWatcher == null) - return; - Date date = Calendar.getInstance().getTime(); - Timestamp time = new Timestamp(date.getTime()); - this.logWatcher.add("[" + time.toString() + "] " + s); - } - - /** - * @return Returns the database handler for queries etc. - */ - public Database getDB() { - return this.database; - } - - /** - * Prints debug information if QuickShop is configured to do so. - * - * @param s - * The string to print. - */ - public void debug(String s) { - if (!debug) - return; - this.getLogger().info(ChatColor.YELLOW + "[Debug] " + s); - } - - /** - * Returns the ShopManager. This is used for fetching, adding and removing - * shops. - * - * @return The ShopManager. - */ - public ShopManager getShopManager() { - return this.shopManager; - } - - public Map> getCustomItemsNameMap() { - return customItemsName; - } - - public CustomItemName getCustomItemNames(ItemStack is) { - List list = customItemsName.get(is.getType()); - if (list==null) { - return null; - } - for (CustomItemName cin : list) { - if (cin.matches(is)) { - return cin; - } - } - - return null; - } -} +package org.maxgamer.quickshop; + +import java.io.File; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.maxgamer.quickshop.Command.QS; +import org.maxgamer.quickshop.Database.Database; +import org.maxgamer.quickshop.Database.Database.ConnectionException; +import org.maxgamer.quickshop.Database.DatabaseCore; +import org.maxgamer.quickshop.Database.DatabaseHelper; +import org.maxgamer.quickshop.Database.MySQLCore; +import org.maxgamer.quickshop.Database.SQLiteCore; +import org.maxgamer.quickshop.Economy.Economy; +import org.maxgamer.quickshop.Economy.EconomyCore; +import org.maxgamer.quickshop.Economy.Economy_Vault; +import org.maxgamer.quickshop.Listeners.BlockListener; +import org.maxgamer.quickshop.Listeners.ChatListener; +import org.maxgamer.quickshop.Listeners.ChunkListener; +import org.maxgamer.quickshop.Listeners.DisplayProtectionListener; +import org.maxgamer.quickshop.Listeners.LockListener; +import org.maxgamer.quickshop.Listeners.PlayerListener; +import org.maxgamer.quickshop.Listeners.WorldListener; +import org.maxgamer.quickshop.Shop.ContainerShop; +import org.maxgamer.quickshop.Shop.Shop; +import org.maxgamer.quickshop.Shop.ShopManager; +import org.maxgamer.quickshop.Shop.ShopType; +import org.maxgamer.quickshop.Util.CustomItemName; +import org.maxgamer.quickshop.Util.CustomPotionsName; +import org.maxgamer.quickshop.Util.MsgUtil; +import org.maxgamer.quickshop.Util.NMS; +import org.maxgamer.quickshop.Util.Permissions; +import org.maxgamer.quickshop.Util.Util; +import org.maxgamer.quickshop.Watcher.ItemWatcher; +import org.maxgamer.quickshop.Watcher.LogWatcher; + + +@SuppressWarnings("deprecation") +public class QuickShop extends JavaPlugin { + /** The active instance of QuickShop */ + public static QuickShop instance; + /** The economy we hook into for transactions */ + private Economy economy; + /** The Shop Manager used to store shops */ + private ShopManager shopManager; + /** + * A set of players who have been warned + * ("Your shop isn't automatically locked") + */ + public HashSet warnings = new HashSet(); + /** The database for storing all our data for persistence */ + private Database database; + // Listeners - We decide which one to use at runtime + private ChatListener chatListener; + // Listeners (These don't) + private BlockListener blockListener; + private PlayerListener playerListener; + private DisplayProtectionListener inventoryListener; + private ChunkListener chunkListener; + private WorldListener worldListener; + private BukkitTask itemWatcherTask; + private LogWatcher logWatcher; + /** Whether players are required to sneak to create/buy from a shop */ + public boolean sneak; + /** Whether players are required to sneak to create a shop */ + public boolean sneakCreate; + /** Whether players are required to sneak to trade with a shop */ + public boolean sneakTrade; + /** Whether we should use display items or not */ + public boolean display = true; + /** + * Whether we players are charged a fee to change the price on their shop + * (To help deter endless undercutting + */ + public boolean priceChangeRequiresFee = false; + /** Whether or not to limit players shop amounts */ + public boolean limit = false; + + /** The plugin OpenInv (null if not present) */ + public Plugin openInvPlugin; + + private HashMap limits = new HashMap(); + /** Use SpoutPlugin to get item / block names */ + public boolean useSpout = false; + // private Metrics metrics; + /** Whether debug info should be shown in the console */ + public static boolean debug = false; + + private Map> customItemsName = new HashMap>(); + + private int displayItemCheckTicks; + + /** The plugin metrics from Hidendra */ + // public Metrics getMetrics(){ return metrics; } + public int getShopLimit(Player p) { + int max = getConfig().getInt("limits.default"); + for (Entry entry : limits.entrySet()) { + if (entry.getValue() > max && p.hasPermission(entry.getKey())) + max = entry.getValue(); + } + return max; + } + + public void onEnable() { + getLogger().info("Quickshop Remake by Ghost_chu(Minecraft SunnySide Server)"); + getLogger().info("THIS VERSION ONLY SUPPORT 1.13 VERSION!"); + NMS.init(); + + instance = this; + saveDefaultConfig(); // Creates the config folder and copies config.yml + // (If one doesn't exist) as required. + reloadConfig(); // Reloads messages.yml too, aswell as config.yml and + // others. + getConfig().options().copyDefaults(true); // Load defaults. + if (getConfig().contains("debug")) + debug = true; + if (loadEcon() == false) + return; + + if (Permissions.init()) { + getLogger().info("Found permission provider."); + } else { + getLogger().info("Couldn't find a Vault permission provider. Some feature may be limited."); + } + + // Initialize Util + Util.initialize(); + + // Create the shop manager. + this.shopManager = new ShopManager(this); + if (this.display) { + // Display item handler thread + getLogger().info("Starting item scheduler"); + ItemWatcher itemWatcher = new ItemWatcher(this); + itemWatcherTask = Bukkit.getScheduler().runTaskTimer(this, itemWatcher, 600, 600); + } + if (this.getConfig().getBoolean("log-actions")) { + // Logger Handler + this.logWatcher = new LogWatcher(this, new File(this.getDataFolder(), "qs.log")); + logWatcher.task = Bukkit.getScheduler().runTaskTimerAsynchronously(this, this.logWatcher, 150, 150); + } + if (getConfig().getBoolean("shop.lock")) { + LockListener ll = new LockListener(this); + getServer().getPluginManager().registerEvents(ll, this); + } + + if (this.getConfig().isSet("custom-items-name")) { + for (String s : this.getConfig().getStringList("custom-items-name")) { + try { + String[] mainVal = s.split("[;]"); + if (mainVal.length!=3) { + throw new Exception("Invalid format (main args length must be 3)"); + } + + String[] matVal = mainVal[0].split("[*]"); + Material material = Material.matchMaterial(matVal[0]); + if (material==null) { + throw new Exception("Invalid material: "+matVal[0]); + } + + ItemStack is; + if (matVal.length>1) { + try { + is = new ItemStack(material, 1, Short.valueOf(matVal[1])); + } catch (Exception e) { + throw new Exception("Invalid data value: "+matVal[1]); + } + } else { + is = new ItemStack(material, 1, (short) 0); + } + + if (mainVal[1].length()>16) { + Bukkit.getLogger().warning("Custom item name definition {"+s+"} sign name is longer than 16 characters. Only the first 16 characters will be shown."); + } + + List cinList = customItemsName.get(material); + if (cinList==null) { + cinList = new ArrayList(); + customItemsName.put(material, cinList); + } + + cinList.add(new CustomItemName(is, mainVal[1], mainVal[2])); + } catch (Exception e) { + Bukkit.getLogger().warning("Invalid custom item name definition {"+s+"} Error: "+e.getMessage()); + } + } + } + + ConfigurationSection cPotionSection = this.getConfig().getConfigurationSection("custom-potions-name"); + if (cPotionSection!=null) { + CustomPotionsName.setSignFormat(new String[]{cPotionSection.getString("sign.format"), cPotionSection.getString("sign.variety.normal"), cPotionSection.getString("sign.variety.splash"), cPotionSection.getString("sign.variety.lingering")}); + CustomPotionsName.setShopInfoFormat(new String[]{cPotionSection.getString("shopinfo.format"), cPotionSection.getString("shopinfo.variety.normal"), cPotionSection.getString("shopinfo.variety.splash"), cPotionSection.getString("shopinfo.variety.lingering")}); + + Map potionTypes = new HashMap(); + for (String s : cPotionSection.getStringList("types")) { + try { + String[] a = s.split("[;]"); + if (a.length!=3) { + throw new Exception("Invalid format (main args length must be 3)"); + } + + PotionType type = PotionType.valueOf(a[0].toUpperCase()); + if (type==null) { + throw new Exception("Invalid PotionType "+a[0]); + } + + potionTypes.put(type, new CustomPotionsName.Names(a[1], a[2])); + } catch (Exception e) { + Bukkit.getLogger().warning("Invalid potion item name definition {"+s+"} Error: "+e.getMessage()); + } + } + CustomPotionsName.setPotionTypes(potionTypes); + + Map potionEffects = new HashMap(); + for (String s : cPotionSection.getStringList("effects")) { + try { + String[] a = s.split("[;]"); + if (a.length!=2) { + throw new Exception("Invalid format (main args length must be 2)"); + } + + PotionEffectType type = PotionEffectType.getByName(a[0]); + if (type==null) { + throw new Exception("Invalid PotionEffectType "+a[0]); + } + + potionEffects.put(type, a[1]); + } catch (Exception e) { + Bukkit.getLogger().warning("Invalid potion effect type name definition {"+s+"} Error: "+e.getMessage()); + } + } + CustomPotionsName.setPotionEffects(potionEffects); + } + + ConfigurationSection limitCfg = this.getConfig().getConfigurationSection("limits"); + if (limitCfg != null) { + getLogger().info("Limit cfg found..."); + this.limit = limitCfg.getBoolean("use", false); + getLogger().info("Limits.use: " + limit); + limitCfg = limitCfg.getConfigurationSection("ranks"); + for (String key : limitCfg.getKeys(true)) { + limits.put(key, limitCfg.getInt(key)); + } + getLogger().info(limits.toString()); + } + try { + ConfigurationSection dbCfg = getConfig().getConfigurationSection("database"); + DatabaseCore dbCore; + if (dbCfg.getBoolean("mysql")) { + // MySQL database - Required database be created first. + String user = dbCfg.getString("user"); + String pass = dbCfg.getString("password"); + String host = dbCfg.getString("host"); + String port = dbCfg.getString("port"); + String database = dbCfg.getString("database"); + dbCore = new MySQLCore(host, user, pass, database, port); + } else { + // SQLite database - Doing this handles file creation + dbCore = new SQLiteCore(new File(this.getDataFolder(), "shops.db")); + } + this.database = new Database(dbCore); + // Make the database up to date + DatabaseHelper.setup(getDB()); + } catch (ConnectionException e) { + e.printStackTrace(); + getLogger().severe("Error connecting to database. Aborting plugin load."); + getServer().getPluginManager().disablePlugin(this); + return; + } catch (SQLException e) { + e.printStackTrace(); + getLogger().severe("Error setting up database. Aborting plugin load."); + getServer().getPluginManager().disablePlugin(this); + return; + } + /* Load shops from database to memory */ + int count = 0; // Shops count + Connection con; + try { + getLogger().info("Loading shops from database..."); + /*int res = Converter.convert(); + if (res < 0) { + System.out.println("Could not convert shops. Exitting."); + return; + } + if (res > 0) { + System.out.println("Conversion success. Continuing..."); + }*/ + con = database.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT * FROM shops"); + ResultSet rs = ps.executeQuery(); + int errors = 0; + while (rs.next()) { + int x = 0; + int y = 0; + int z = 0; + String worldName = null; + try { + x = rs.getInt("x"); + y = rs.getInt("y"); + z = rs.getInt("z"); + worldName = rs.getString("world"); + World world = Bukkit.getWorld(worldName); + ItemStack item = Util.deserialize(rs.getString("itemConfig")); + String owner = rs.getString("owner"); + UUID ownerUUID = null; + try { + ownerUUID = UUID.fromString(owner); + } catch (IllegalArgumentException e) { + // This could be old data to be converted... check if it's a player + OfflinePlayer player = Bukkit.getOfflinePlayer(owner); + if (player.hasPlayedBefore()) { + ownerUUID = player.getUniqueId(); + getDB().getConnection().createStatement().executeUpdate("UPDATE shops SET owner = \""+ownerUUID.toString()+"\" WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\" LIMIT 1"); + } else { + // Invalid shop owner + getDB().getConnection().createStatement().executeUpdate("DELETE FROM shops WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\""+(getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : "")); + continue; + } + } + + double price = rs.getDouble("price"); + Location loc = new Location(world, x, y, z); + /* Skip invalid shops, if we know of any */ + if (world != null && (loc.getBlock().getState() instanceof InventoryHolder) == false) { + getLogger().info("Shop is not an InventoryHolder in " + rs.getString("world") + " at: " + x + ", " + y + ", " + z + ". Deleting."); + getDB().getConnection().createStatement().executeUpdate("DELETE FROM shops WHERE x = "+x+" AND y = "+y+" AND z = "+z+" AND world = \""+worldName+"\""+(getDB().getCore() instanceof MySQLCore ? " LIMIT 1" : "")); + continue; + } + int type = rs.getInt("type"); + Shop shop = new ContainerShop(loc, price, item, ownerUUID); + shop.setUnlimited(rs.getBoolean("unlimited")); + shop.setShopType(ShopType.fromID(type)); + shopManager.loadShop(rs.getString("world"), shop); + if (loc.getWorld() != null && loc.getChunk().isLoaded()) { + shop.onLoad(); + } + count++; + } catch (Exception e) { + errors++; + e.printStackTrace(); + getLogger().severe("Error loading a shop! Coords: " + worldName + " (" + x + ", " + y + ", " + z + ")..."); + if (errors < 3) { + getLogger().info("Deleting the shop..."); + PreparedStatement delps = getDB().getConnection().prepareStatement("DELETE FROM shops WHERE x = ? AND y = ? and z = ? and world = ?"); + delps.setInt(1, x); + delps.setInt(2, y); + delps.setInt(3, z); + delps.setString(4, worldName); + delps.execute(); + } else { + getLogger().severe("Multiple errors in shops - Something seems to be wrong with your shops database! Please check it out immediately!"); + e.printStackTrace(); + } + } + } + } catch (SQLException e) { + e.printStackTrace(); + getLogger().severe("Could not load shops."); + } + + getLogger().info("Loaded " + count + " shops."); + MsgUtil.loadTransactionMessages(); + MsgUtil.clean(); + // Register events + getLogger().info("Registering Listeners"); + blockListener = new BlockListener(this); + playerListener = new PlayerListener(this); + worldListener = new WorldListener(this); + chatListener = new ChatListener(this); + + Bukkit.getServer().getPluginManager().registerEvents(blockListener, this); + Bukkit.getServer().getPluginManager().registerEvents(playerListener, this); + Bukkit.getServer().getPluginManager().registerEvents(chatListener, this); + if (this.display) { + inventoryListener = new DisplayProtectionListener(this); + chunkListener = new ChunkListener(this); + Bukkit.getServer().getPluginManager().registerEvents(inventoryListener, this); + Bukkit.getServer().getPluginManager().registerEvents(chunkListener, this); + } + Bukkit.getServer().getPluginManager().registerEvents(worldListener, this); + // Command handlers + QS commandExecutor = new QS(this); + getCommand("qs").setExecutor(commandExecutor); + if (getConfig().getInt("shop.find-distance") > 100) { + getLogger().severe("Shop.find-distance is too high! Pick a number under 100!"); + } + + if (display && displayItemCheckTicks>0) { + new BukkitRunnable() { + @Override + public void run() { + Iterator it = getShopManager().getShopIterator(); + while (it.hasNext()) { + Shop shop = it.next(); + if (shop instanceof ContainerShop) { + ContainerShop cShop = (ContainerShop) shop; + if (cShop.checkDisplayMoved()) { + log("Display item for "+shop+" is not on the correct location and has been removed. Probably someone is trying to cheat."); + for (Player player : getServer().getOnlinePlayers()) { + if (player.hasPermission("quickshop.alerts")) { + player.sendMessage(ChatColor.RED + "[QuickShop] Display item for "+shop+" is not on the correct location and has been removed. Probably someone is trying to cheat."); + } + } + cShop.getDisplayItem().remove(); + } + } + } + } + }.runTaskTimer(this, 1L, displayItemCheckTicks); + } + + // added for compatibility reasons with OpenInv - see https://github.com/KaiKikuchi/QuickShop/issues/139 + this.openInvPlugin = Bukkit.getPluginManager().getPlugin("OpenInv"); + + getLogger().info("QuickShop loaded!"); + } + + /** Reloads QuickShops config */ + @Override + public void reloadConfig() { + super.reloadConfig(); + // Load quick variables + this.display = this.getConfig().getBoolean("shop.display-items"); + this.sneak = this.getConfig().getBoolean("shop.sneak-only"); + this.sneakCreate = this.getConfig().getBoolean("shop.sneak-to-create"); + this.sneakTrade = this.getConfig().getBoolean("shop.sneak-to-trade"); + this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee"); + this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks"); + MsgUtil.loadCfgMessages(); + } + + /** + * Tries to load the economy and its core. If this fails, it will try to use + * vault. If that fails, it will return false. + * + * @return true if successful, false if the core is invalid or is not found, + * and vault cannot be used. + */ + public boolean loadEcon() { + EconomyCore core = new Economy_Vault(); + if (core == null || !core.isValid()) { + // getLogger().severe("Economy is not valid!"); + getLogger().severe("QuickShop could not hook an economy!"); + getLogger().severe("QuickShop CANNOT start!"); + this.getPluginLoader().disablePlugin(this); + // if(econ.equals("Vault")) + // getLogger().severe("(Does Vault have an Economy to hook into?!)"); + return false; + } else { + this.economy = new Economy(core); + return true; + } + } + + public void onDisable() { + if (itemWatcherTask != null) { + itemWatcherTask.cancel(); + } + if (logWatcher != null) { + logWatcher.task.cancel(); + logWatcher.close(); // Closes the file + } + /* Remove all display items, and any dupes we can find */ + shopManager.clear(); + /* Empty the buffer */ + database.close(); + try { + this.database.getConnection().close(); + } catch (SQLException e) { + e.printStackTrace(); + } + this.warnings.clear(); + this.reloadConfig(); + } + + /** + * Returns the economy for moving currency around + * + * @return The economy for moving currency around + */ + public EconomyCore getEcon() { + return economy; + } + + /** + * Logs the given string to qs.log, if QuickShop is configured to do so. + * + * @param s + * The string to log. It will be prefixed with the date and time. + */ + public void log(String s) { + if (this.logWatcher == null) + return; + Date date = Calendar.getInstance().getTime(); + Timestamp time = new Timestamp(date.getTime()); + this.logWatcher.add("[" + time.toString() + "] " + s); + } + + /** + * @return Returns the database handler for queries etc. + */ + public Database getDB() { + return this.database; + } + + /** + * Prints debug information if QuickShop is configured to do so. + * + * @param s + * The string to print. + */ + public void debug(String s) { + if (!debug) + return; + this.getLogger().info(ChatColor.YELLOW + "[Debug] " + s); + } + + /** + * Returns the ShopManager. This is used for fetching, adding and removing + * shops. + * + * @return The ShopManager. + */ + public ShopManager getShopManager() { + return this.shopManager; + } + + public Map> getCustomItemsNameMap() { + return customItemsName; + } + + public CustomItemName getCustomItemNames(ItemStack is) { + List list = customItemsName.get(is.getType()); + if (list==null) { + return null; + } + for (CustomItemName cin : list) { + if (cin.matches(is)) { + return cin; + } + } + + return null; + } +} diff --git a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java index 48b340a49..2ee94765f 100644 --- a/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java +++ b/src/main/java/org/maxgamer/quickshop/Shop/ShopManager.java @@ -1,659 +1,666 @@ -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 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.entity.Player; -import org.bukkit.event.block.Action; -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.Util.MsgUtil; -import org.maxgamer.quickshop.Util.Permissions; -import org.maxgamer.quickshop.Util.Util; - -public class ShopManager { - private QuickShop plugin; - 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) { - Location loc = shop.getLocation(); - ItemStack item = shop.getItem(); - try { - // Write it to the database - String q = "INSERT INTO shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - plugin.getDB().execute(q, shop.getOwner().toString(), shop.getPrice(), Util.serialize(item), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), loc.getWorld().getName(), (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID()); - // Add it to the world - addShop(loc.getWorld().getName(), shop); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Could not create shop! Changes will revert after a reboot!"); - } - } - - /** - * 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(); - // System.out.println("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) { - 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) { - 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; - 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!"); - 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() { - @SuppressWarnings("deprecation") - @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) { - try { - // Checking the shop can be created - 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()) == false) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - 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; - } - // Check price restriction - Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); - if (priceRestriction!=null) { - if (pricepriceRestriction.getValue()) { - p.sendMessage(ChatColor.RED+"Restricted prices for "+info.getItem().getType()+": min "+priceRestriction.getKey()+", max "+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.getName()) < 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.getName(), tax)) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); - shop.onUnload(); - return; - } - plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), tax); - } - /* The shop has hereforth been successfully created */ - createShop(shop); - Location loc = shop.getLocation(); - plugin.log(p.getName() + " created a " + shop.getDataName() + " 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 (info.getSignBlock() != null && info.getSignBlock().getType() == Material.AIR && plugin.getConfig().getBoolean("shop.auto-sign")) { - BlockState bs = info.getSignBlock().getState(); - BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); - bs.setType(Material.WALL_SIGN); - Sign sign = (Sign) bs.getData(); - sign.setFacingDirection(bf); - 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. - */ - // } - } - 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; - } - } - /* Purchase Handling */ - else if (info.getAction() == ShopAction.BUY) { - 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()) == false) { - p.sendMessage(MsgUtil.getMessage("chest-was-removed")); - return; - } - if (info.hasChanged(shop)) { - p.sendMessage(MsgUtil.getMessage("shop-has-changed")); - return; - } - if (shop.isSelling()) { - int stock = shop.getRemainingStock(); - 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.getName()) < amount * shop.getPrice()) { - p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); - 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()) || Permissions.hasPermission(Bukkit.getOfflinePlayer(shop.getOwner()), "quickshop.taxexemption")) { - 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.getName())))); - 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(plugin.getConfig().getString("tax-account"), 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); - } 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); - } - } - // 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()); - } else if (shop.isBuying()) { - int space = shop.getRemainingSpace(); - 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"); - 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(plugin.getConfig().getString("tax-account"), total * tax); - } - } - // Give them the money after we know we succeeded - plugin.getEcon().deposit(p.getName(), 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.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 - } - /* If it was already cancelled (from destroyed) */ - else { - return; // It was cancelled, go away. - } - } - }); - } - - /** - * 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 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.BlockData; +import org.bukkit.entity.Player; +import org.bukkit.event.block.Action; +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.Util.MsgUtil; +import org.maxgamer.quickshop.Util.Permissions; +import org.maxgamer.quickshop.Util.Util; + +public class ShopManager { + private QuickShop plugin; + 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) { + Location loc = shop.getLocation(); + ItemStack item = shop.getItem(); + try { + // Write it to the database + String q = "INSERT INTO shops (owner, price, itemConfig, x, y, z, world, unlimited, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + plugin.getDB().execute(q, shop.getOwner().toString(), shop.getPrice(), Util.serialize(item), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), loc.getWorld().getName(), (shop.isUnlimited() ? 1 : 0), shop.getShopType().toID()); + // Add it to the world + addShop(loc.getWorld().getName(), shop); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Could not create shop! Changes will revert after a reboot!"); + } + } + + /** + * 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(); + // System.out.println("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) { + 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) { + 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; + 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!"); + 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() { + @SuppressWarnings("deprecation") + @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) { + try { + // Checking the shop can be created + 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()) == false) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + 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; + } + // Check price restriction + Entry priceRestriction = Util.getPriceRestriction(info.getItem().getType()); + if (priceRestriction!=null) { + if (pricepriceRestriction.getValue()) { + p.sendMessage(ChatColor.RED+"Restricted prices for "+info.getItem().getType()+": min "+priceRestriction.getKey()+", max "+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.getName()) < 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.getName(), tax)) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-a-new-shop", format(tax))); + shop.onUnload(); + return; + } + plugin.getEcon().deposit(plugin.getConfig().getString("tax-account"), tax); + } + /* The shop has hereforth been successfully created */ + createShop(shop); + Location loc = shop.getLocation(); + plugin.log(p.getName() + " created a " + shop.getDataName() + " 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 (info.getSignBlock() != null && info.getSignBlock().getType() == Material.AIR && plugin.getConfig().getBoolean("shop.auto-sign")) { + final BlockState bs = info.getSignBlock().getState(); + final BlockFace bf = info.getLocation().getBlock().getFace(info.getSignBlock()); + bs.setType(Material.WALL_SIGN); + final Sign sign = (Sign) bs.getData(); + sign.setFacingDirection(bf); + plugin.log(sign.getFacing().toString()); + Bukkit.getScheduler().runTask(plugin, new Runnable() { + @Override + public void run() { + 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. + */ + // } + } + 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; + } + } + /* Purchase Handling */ + else if (info.getAction() == ShopAction.BUY) { + 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()) == false) { + p.sendMessage(MsgUtil.getMessage("chest-was-removed")); + return; + } + if (info.hasChanged(shop)) { + p.sendMessage(MsgUtil.getMessage("shop-has-changed")); + return; + } + if (shop.isSelling()) { + int stock = shop.getRemainingStock(); + 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.getName()) < amount * shop.getPrice()) { + p.sendMessage(MsgUtil.getMessage("you-cant-afford-to-buy", format(amount * shop.getPrice()), format(plugin.getEcon().getBalance(p.getName())))); + 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()) || Permissions.hasPermission(Bukkit.getOfflinePlayer(shop.getOwner()), "quickshop.taxexemption")) { + 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.getName())))); + 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(plugin.getConfig().getString("tax-account"), 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); + } 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); + } + } + // 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()); + } else if (shop.isBuying()) { + int space = shop.getRemainingSpace(); + 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"); + 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(plugin.getConfig().getString("tax-account"), total * tax); + } + } + // Give them the money after we know we succeeded + plugin.getEcon().deposit(p.getName(), 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.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 + } + /* If it was already cancelled (from destroyed) */ + else { + return; // It was cancelled, go away. + } + } + }); + } + + /** + * 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(); + } + } } \ No newline at end of file diff --git a/src/main/java/org/maxgamer/quickshop/Util/NMS.java b/src/main/java/org/maxgamer/quickshop/Util/NMS.java index 1dc7aefbc..0aa013c8f 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/NMS.java +++ b/src/main/java/org/maxgamer/quickshop/Util/NMS.java @@ -1,636 +1,214 @@ -package org.maxgamer.quickshop.Util; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Item; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.Potion; -import org.bukkit.potion.Potion.Tier; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionType; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Util.CustomPotionsName.GenericPotionData; -import org.maxgamer.quickshop.Util.CustomPotionsName.GenericPotionData.Category; - -@SuppressWarnings("deprecation") -public class NMS { - private static ArrayList nmsDependencies = new ArrayList(); - private static int nextId = 0; - private static NMSDependent nms; - - static { - nmsDependencies.add(new NMSDependent("v1_7") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_7_R3.ItemStack nmsI = org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.count = 0; - iStack = org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_7_R3.ItemStack is = org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_7_R3.NBTTagCompound itemCompound = new net.minecraft.server.v1_7_R3.NBTTagCompound(); - itemCompound = is.save(itemCompound); - return net.minecraft.server.v1_7_R3.NBTCompressedStreamTools.a(itemCompound); - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - if(QuickShop.debug)System.out.println("getItemStack"); - net.minecraft.server.v1_7_R3.NBTTagCompound c = net.minecraft.server.v1_7_R3.NBTCompressedStreamTools.a(bytes, null); - net.minecraft.server.v1_7_R3.ItemStack is = net.minecraft.server.v1_7_R3.ItemStack.createStack(c); - return org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemStack.asBukkitCopy(is); - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - if (potionItemStack.getDurability()==0) { - return new GenericPotionData(PotionType.WATER, Collections.emptyList(), Category.NORMAL, false, 0, 0); - } - - Potion potion = Potion.fromItemStack(potionItemStack); - if (potion==null) { - return null; - } - - Category category; - if (potion.isSplash()) { - category = Category.SPLASH; - } else { - category = Category.NORMAL; - } - - return new GenericPotionData(potion.getType(), potion.getEffects(), category, potion.getType()==PotionType.WATER && !potion.getEffects().isEmpty(), potion.hasExtendedDuration() ? -1 : 0, potion.getTier()==Tier.TWO ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - return material==Material.POTION; - } - }); - - nmsDependencies.add(new NMSDependent("v1_8") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_8_R3.ItemStack nmsI = org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.count = 0; - iStack = org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - try{ - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_8_R3.ItemStack is = org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_8_R3.NBTTagCompound itemCompound = new net.minecraft.server.v1_8_R3.NBTTagCompound(); - itemCompound = is.save(itemCompound); - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); - DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); - try { - net.minecraft.server.v1_8_R3.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - return bytearrayoutputstream.toByteArray(); - }catch(Exception e){ - return new byte[0]; - } - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - try{ - if(QuickShop.debug)System.out.println("getItemStack"); - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))); - net.minecraft.server.v1_8_R3.NBTTagCompound nbttagcompound; - try { - nbttagcompound = net.minecraft.server.v1_8_R3.NBTCompressedStreamTools.a((DataInput) datainputstream, null); - } finally { - datainputstream.close(); - } - net.minecraft.server.v1_8_R3.ItemStack is = net.minecraft.server.v1_8_R3.ItemStack.createStack(nbttagcompound); - return org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack.asBukkitCopy(is); - }catch(Exception e){ - return new ItemStack(Material.AIR); - } - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - if (potionItemStack.getDurability()==0) { - return new GenericPotionData(PotionType.WATER, Collections.emptyList(), Category.NORMAL, false, 0, 0); - } - - Potion potion = Potion.fromItemStack(potionItemStack); - if (potion==null) { - return null; - } - - Category category; - if (potion.isSplash()) { - category = Category.SPLASH; - } else { - category = Category.NORMAL; - } - - return new GenericPotionData(potion.getType(), potion.getEffects(), category, potion.getType()==PotionType.WATER && !potion.getEffects().isEmpty(), potion.hasExtendedDuration() ? -1 : 0, potion.getTier()==Tier.TWO ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - return material==Material.POTION; - } - }); - - nmsDependencies.add(new NMSDependent("v1_9") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_9_R2.ItemStack nmsI = org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.count = 0; - iStack = org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - try{ - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_9_R2.ItemStack is = org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_9_R2.NBTTagCompound itemCompound = new net.minecraft.server.v1_9_R2.NBTTagCompound(); - itemCompound = is.save(itemCompound); - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); - DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); - try { - net.minecraft.server.v1_9_R2.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - return bytearrayoutputstream.toByteArray(); - }catch(Exception e){ - return new byte[0]; - } - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - try{ - if(QuickShop.debug)System.out.println("getItemStack"); - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))); - net.minecraft.server.v1_9_R2.NBTTagCompound nbttagcompound; - try { - nbttagcompound = net.minecraft.server.v1_9_R2.NBTCompressedStreamTools.a((DataInput) datainputstream, null); - } finally { - datainputstream.close(); - } - net.minecraft.server.v1_9_R2.ItemStack is = net.minecraft.server.v1_9_R2.ItemStack.createStack(nbttagcompound); - return org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack.asBukkitCopy(is); - }catch(Exception e){ - return new ItemStack(Material.AIR); - } - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - PotionMeta potionMeta = (PotionMeta) potionItemStack.getItemMeta(); - - Category category; - switch(potionItemStack.getType()) { - case POTION: - category = Category.NORMAL; - break; - case SPLASH_POTION: - category = Category.SPLASH; - break; - case LINGERING_POTION: - category = Category.LINGERING; - break; - default: - return null; - } - List effects = new ArrayList(potionMeta.getCustomEffects().size()+1); - - if (potionMeta.hasCustomEffects()) { - effects.addAll(potionMeta.getCustomEffects()); - } - - PotionType potionType = potionMeta.getBasePotionData().getType(); - - return new GenericPotionData(potionType, effects, category, (potionType==PotionType.WATER || potionType==PotionType.MUNDANE || potionType==PotionType.UNCRAFTABLE || potionType==PotionType.THICK || potionType==PotionType.AWKWARD) && !effects.isEmpty(), potionMeta.getBasePotionData().isExtended() ? -1 : 0, potionMeta.getBasePotionData().isUpgraded() ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - switch(material) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - return true; - default: - return false; - } - } - }); - - nmsDependencies.add(new NMSDependent("v1_10") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_10_R1.ItemStack nmsI = org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.count = 0; - iStack = org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - try{ - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_10_R1.ItemStack is = org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_10_R1.NBTTagCompound itemCompound = new net.minecraft.server.v1_10_R1.NBTTagCompound(); - itemCompound = is.save(itemCompound); - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); - DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); - try { - net.minecraft.server.v1_10_R1.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - return bytearrayoutputstream.toByteArray(); - }catch(Exception e){ - return new byte[0]; - } - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - try{ - if(QuickShop.debug)System.out.println("getItemStack"); - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))); - net.minecraft.server.v1_10_R1.NBTTagCompound nbttagcompound; - try { - nbttagcompound = net.minecraft.server.v1_10_R1.NBTCompressedStreamTools.a((DataInput) datainputstream, null); - } finally { - datainputstream.close(); - } - net.minecraft.server.v1_10_R1.ItemStack is = net.minecraft.server.v1_10_R1.ItemStack.createStack(nbttagcompound); - return org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack.asBukkitCopy(is); - }catch(Exception e){ - return new ItemStack(Material.AIR); - } - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - PotionMeta potionMeta = (PotionMeta) potionItemStack.getItemMeta(); - - Category category; - switch(potionItemStack.getType()) { - case POTION: - category = Category.NORMAL; - break; - case SPLASH_POTION: - category = Category.SPLASH; - break; - case LINGERING_POTION: - category = Category.LINGERING; - break; - default: - return null; - } - List effects = new ArrayList(potionMeta.getCustomEffects().size()+1); - - if (potionMeta.hasCustomEffects()) { - effects.addAll(potionMeta.getCustomEffects()); - } - - PotionType potionType = potionMeta.getBasePotionData().getType(); - - return new GenericPotionData(potionType, effects, category, (potionType==PotionType.WATER || potionType==PotionType.MUNDANE || potionType==PotionType.UNCRAFTABLE || potionType==PotionType.THICK || potionType==PotionType.AWKWARD) && !effects.isEmpty(), potionMeta.getBasePotionData().isExtended() ? -1 : 0, potionMeta.getBasePotionData().isUpgraded() ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - switch(material) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - return true; - default: - return false; - } - } - }); - - nmsDependencies.add(new NMSDependent("v1_11") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_11_R1.ItemStack nmsI = org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.setCount(0); - iStack = org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - try{ - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_11_R1.ItemStack is = org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_11_R1.NBTTagCompound itemCompound = new net.minecraft.server.v1_11_R1.NBTTagCompound(); - itemCompound = is.save(itemCompound); - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); - DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); - try { - net.minecraft.server.v1_11_R1.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - return bytearrayoutputstream.toByteArray(); - }catch(Exception e){ - return new byte[0]; - } - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - try{ - if(QuickShop.debug)System.out.println("getItemStack"); - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))); - net.minecraft.server.v1_11_R1.NBTTagCompound nbttagcompound; - try { - nbttagcompound = net.minecraft.server.v1_11_R1.NBTCompressedStreamTools.a((DataInput) datainputstream, null); - } finally { - datainputstream.close(); - } - net.minecraft.server.v1_11_R1.ItemStack is = new net.minecraft.server.v1_11_R1.ItemStack(nbttagcompound); - return org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack.asBukkitCopy(is); - }catch(Exception e){ - return new ItemStack(Material.AIR); - } - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - PotionMeta potionMeta = (PotionMeta) potionItemStack.getItemMeta(); - - Category category; - switch(potionItemStack.getType()) { - case POTION: - category = Category.NORMAL; - break; - case SPLASH_POTION: - category = Category.SPLASH; - break; - case LINGERING_POTION: - category = Category.LINGERING; - break; - default: - return null; - } - List effects = new ArrayList(potionMeta.getCustomEffects().size()+1); - - if (potionMeta.hasCustomEffects()) { - effects.addAll(potionMeta.getCustomEffects()); - } - - PotionType potionType = potionMeta.getBasePotionData().getType(); - - return new GenericPotionData(potionType, effects, category, (potionType==PotionType.WATER || potionType==PotionType.MUNDANE || potionType==PotionType.UNCRAFTABLE || potionType==PotionType.THICK || potionType==PotionType.AWKWARD) && !effects.isEmpty(), potionMeta.getBasePotionData().isExtended() ? -1 : 0, potionMeta.getBasePotionData().isUpgraded() ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - switch(material) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - return true; - default: - return false; - } - } - }); - - nmsDependencies.add(new NMSDependent("v1_12") { - @Override - public void safeGuard(Item item) { - if(QuickShop.debug)System.out.println("safeGuard"); - org.bukkit.inventory.ItemStack iStack = item.getItemStack(); - net.minecraft.server.v1_12_R1.ItemStack nmsI = org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asNMSCopy(iStack); - nmsI.setCount(0); - iStack = org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asBukkitCopy(nmsI); - item.setItemStack(iStack); - } - - @Override - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { - try{ - if(QuickShop.debug)System.out.println("getNBTBytes"); - net.minecraft.server.v1_12_R1.ItemStack is = org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asNMSCopy(iStack); - net.minecraft.server.v1_12_R1.NBTTagCompound itemCompound = new net.minecraft.server.v1_12_R1.NBTTagCompound(); - itemCompound = is.save(itemCompound); - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); - DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); - try { - net.minecraft.server.v1_12_R1.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - return bytearrayoutputstream.toByteArray(); - }catch(Exception e){ - return new byte[0]; - } - } - - @Override - public org.bukkit.inventory.ItemStack getItemStack(byte[] bytes) { - try{ - if(QuickShop.debug)System.out.println("getItemStack"); - DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))); - net.minecraft.server.v1_12_R1.NBTTagCompound nbttagcompound; - try { - nbttagcompound = net.minecraft.server.v1_12_R1.NBTCompressedStreamTools.a((DataInput) datainputstream, null); - } finally { - datainputstream.close(); - } - net.minecraft.server.v1_12_R1.ItemStack is = new net.minecraft.server.v1_12_R1.ItemStack(nbttagcompound); - return org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack.asBukkitCopy(is); - }catch(Exception e){ - return new ItemStack(Material.AIR); - } - } - - @Override - public GenericPotionData getPotionData(ItemStack potionItemStack) { - PotionMeta potionMeta = (PotionMeta) potionItemStack.getItemMeta(); - - Category category; - switch(potionItemStack.getType()) { - case POTION: - category = Category.NORMAL; - break; - case SPLASH_POTION: - category = Category.SPLASH; - break; - case LINGERING_POTION: - category = Category.LINGERING; - break; - default: - return null; - } - List effects = new ArrayList(potionMeta.getCustomEffects().size()+1); - - if (potionMeta.hasCustomEffects()) { - effects.addAll(potionMeta.getCustomEffects()); - } - - PotionType potionType = potionMeta.getBasePotionData().getType(); - - return new GenericPotionData(potionType, effects, category, (potionType==PotionType.WATER || potionType==PotionType.MUNDANE || potionType==PotionType.UNCRAFTABLE || potionType==PotionType.THICK || potionType==PotionType.AWKWARD) && !effects.isEmpty(), potionMeta.getBasePotionData().isExtended() ? -1 : 0, potionMeta.getBasePotionData().isUpgraded() ? 2 : 1); - } - - @Override - public boolean isPotion(Material material) { - switch(material) { - case POTION: - case SPLASH_POTION: - case LINGERING_POTION: - return true; - default: - return false; - } - } - }); - } - - public static void safeGuard(Item item) throws ClassNotFoundException { - if(QuickShop.debug)System.out.println("Renaming"); - rename(item.getItemStack()); - //if(QuickShop.debug)System.out.println("Protecting"); - //protect(item); - if(QuickShop.debug)System.out.println("Seting pickup delay"); - item.setPickupDelay(2147483647); - } - - public static void init() { - String packageName = Bukkit.getServer().getClass().getPackage().getName(); - packageName = packageName.substring(packageName.lastIndexOf(".") + 1); - //System.out.println("Package: " + packageName); - for (NMSDependent dep : nmsDependencies) { - if ((packageName.startsWith(dep.getVersion())) || ((dep.getVersion().isEmpty()) && ((packageName.equals("bukkit")) || (packageName.equals("craftbukkit"))))) { - nms = dep; - return; - } - } - throw new UnsupportedClassVersionError("This version of QuickShop is incompatible. Internal version: "+packageName); - } - - private static void rename(ItemStack iStack) { - ItemMeta meta = iStack.getItemMeta(); - meta.setDisplayName(ChatColor.RED + "QuickShop " + Util.getName(iStack) + " " + nextId++); - iStack.setItemMeta(meta); - } - - public static byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) throws ClassNotFoundException { - return nms.getNBTBytes(iStack); - } - - public static ItemStack getItemStack(byte[] bytes) throws ClassNotFoundException { - return nms.getItemStack(bytes); - } - - public static boolean isPotion(Material material) { - return nms.isPotion(material); - } - - public static GenericPotionData getPotionData(ItemStack potion) { - return nms.getPotionData(potion); - } - - /*private static void protect(Item item) { - try { - Field itemField = item.getClass().getDeclaredField("item"); - itemField.setAccessible(true); - Object nmsEntityItem = itemField.get(item); - Method getItemStack; - try { - getItemStack = nmsEntityItem.getClass().getMethod("getItemStack", new Class[0]); - } catch (NoSuchMethodException e) { - try { - getItemStack = nmsEntityItem.getClass().getMethod("d", new Class[0]); - } catch (NoSuchMethodException e2) { - return; - } - } - Object itemStack = getItemStack.invoke(nmsEntityItem, new Object[0]); - Field countField; - try { - countField = itemStack.getClass().getDeclaredField("count"); - } catch (NoSuchFieldException e) { - countField = itemStack.getClass().getDeclaredField("a"); - } - countField.setAccessible(true); - countField.set(itemStack, Integer.valueOf(0)); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - System.out.println("[QuickShop] Could not protect item from pickup properly! Dupes are now possible."); - } catch (Exception e) { - System.out.println("Other error"); - e.printStackTrace(); - } - }*/ - - private static abstract class NMSDependent { - private String version; - - public String getVersion() { - return this.version; - } - - public NMSDependent(String version) { - this.version = version; - } - - public abstract boolean isPotion(Material material); - - public abstract GenericPotionData getPotionData(ItemStack potionItemStack); - - public abstract void safeGuard(Item paramItem); - - public byte[] getNBTBytes(org.bukkit.inventory.ItemStack paramItemStack) { - throw new UnsupportedOperationException(); - } - - public org.bukkit.inventory.ItemStack getItemStack(byte[] paramArrayOfByte) { - throw new UnsupportedOperationException(); - } - } -} +package org.maxgamer.quickshop.Util; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Item; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionType; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Util.CustomPotionsName.GenericPotionData; +import org.maxgamer.quickshop.Util.CustomPotionsName.GenericPotionData.Category; + +@SuppressWarnings("deprecation") +public class NMS { + private static ArrayList nmsDependencies = new ArrayList(); + private static int nextId = 0; + private static NMSDependent nms; + + static { + nmsDependencies.add(new NMSDependent("v1_13") { + @Override + public void safeGuard(Item item) { + if(QuickShop.debug)System.out.println("safeGuard"); + org.bukkit.inventory.ItemStack iStack = item.getItemStack(); + net.minecraft.server.v1_13_R1.ItemStack nmsI = org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack.asNMSCopy(iStack); + nmsI.setCount(0); + iStack = org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack.asBukkitCopy(nmsI); + item.setItemStack(iStack); + } + + @Override + public byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) { + try{ + if(QuickShop.debug)System.out.println("getNBTBytes"); + net.minecraft.server.v1_13_R1.ItemStack is = org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack.asNMSCopy(iStack); + net.minecraft.server.v1_13_R1.NBTTagCompound itemCompound = new net.minecraft.server.v1_13_R1.NBTTagCompound(); + itemCompound = is.save(itemCompound); + ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); + DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream)); + try { + net.minecraft.server.v1_13_R1.NBTCompressedStreamTools.a(itemCompound, (DataOutput) dataoutputstream); + } finally { + dataoutputstream.close(); + } + return bytearrayoutputstream.toByteArray(); + }catch(Exception e){ + return new byte[0]; + } + } + + + @Override + public GenericPotionData getPotionData(ItemStack potionItemStack) { + PotionMeta potionMeta = (PotionMeta) potionItemStack.getItemMeta(); + + Category category; + switch(potionItemStack.getType()) { + case POTION: + category = Category.NORMAL; + break; + case SPLASH_POTION: + category = Category.SPLASH; + break; + case LINGERING_POTION: + category = Category.LINGERING; + break; + default: + return null; + } + List effects = new ArrayList(potionMeta.getCustomEffects().size()+1); + + if (potionMeta.hasCustomEffects()) { + effects.addAll(potionMeta.getCustomEffects()); + } + + PotionType potionType = potionMeta.getBasePotionData().getType(); + + return new GenericPotionData(potionType, effects, category, (potionType==PotionType.WATER || potionType==PotionType.MUNDANE || potionType==PotionType.UNCRAFTABLE || potionType==PotionType.THICK || potionType==PotionType.AWKWARD) && !effects.isEmpty(), potionMeta.getBasePotionData().isExtended() ? -1 : 0, potionMeta.getBasePotionData().isUpgraded() ? 2 : 1); + } + + @Override + public boolean isPotion(Material material) { + switch(material) { + case POTION: + case SPLASH_POTION: + case LINGERING_POTION: + return true; + default: + return false; + } + } + }); + } + + public static void safeGuard(Item item) throws ClassNotFoundException { + if(QuickShop.debug)System.out.println("Renaming"); + rename(item.getItemStack()); + //if(QuickShop.debug)System.out.println("Protecting"); + //protect(item); + if(QuickShop.debug)System.out.println("Seting pickup delay"); + item.setPickupDelay(2147483647); + } + + public static void init() { + String packageName = Bukkit.getServer().getClass().getPackage().getName(); + packageName = packageName.substring(packageName.lastIndexOf(".") + 1); + //System.out.println("Package: " + packageName); + for (NMSDependent dep : nmsDependencies) { + if ((packageName.startsWith(dep.getVersion())) || ((dep.getVersion().isEmpty()) && ((packageName.equals("bukkit")) || (packageName.equals("craftbukkit"))))) { + nms = dep; + return; + } + } + throw new UnsupportedClassVersionError("This version of QuickShop is incompatible. Internal version: "+packageName); + } + + private static void rename(ItemStack iStack) { + ItemMeta meta = iStack.getItemMeta(); + meta.setDisplayName(ChatColor.RED + "QuickShop " + Util.getName(iStack) + " " + nextId++); + iStack.setItemMeta(meta); + } + + public static byte[] getNBTBytes(org.bukkit.inventory.ItemStack iStack) throws ClassNotFoundException { + return nms.getNBTBytes(iStack); + } + + public static ItemStack getItemStack(byte[] bytes) throws ClassNotFoundException { + return nms.getItemStack(bytes); + } + + public static boolean isPotion(Material material) { + return nms.isPotion(material); + } + + public static GenericPotionData getPotionData(ItemStack potion) { + return nms.getPotionData(potion); + } + + /*private static void protect(Item item) { + try { + Field itemField = item.getClass().getDeclaredField("item"); + itemField.setAccessible(true); + Object nmsEntityItem = itemField.get(item); + Method getItemStack; + try { + getItemStack = nmsEntityItem.getClass().getMethod("getItemStack", new Class[0]); + } catch (NoSuchMethodException e) { + try { + getItemStack = nmsEntityItem.getClass().getMethod("d", new Class[0]); + } catch (NoSuchMethodException e2) { + return; + } + } + Object itemStack = getItemStack.invoke(nmsEntityItem, new Object[0]); + Field countField; + try { + countField = itemStack.getClass().getDeclaredField("count"); + } catch (NoSuchFieldException e) { + countField = itemStack.getClass().getDeclaredField("a"); + } + countField.setAccessible(true); + countField.set(itemStack, Integer.valueOf(0)); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + System.out.println("[QuickShop] Could not protect item from pickup properly! Dupes are now possible."); + } catch (Exception e) { + System.out.println("Other error"); + e.printStackTrace(); + } + }*/ + + private static abstract class NMSDependent { + private String version; + + public String getVersion() { + return this.version; + } + + public NMSDependent(String version) { + this.version = version; + } + + public abstract boolean isPotion(Material material); + + public abstract GenericPotionData getPotionData(ItemStack potionItemStack); + + public abstract void safeGuard(Item paramItem); + + public byte[] getNBTBytes(org.bukkit.inventory.ItemStack paramItemStack) { + throw new UnsupportedOperationException(); + } + + public org.bukkit.inventory.ItemStack getItemStack(byte[] paramArrayOfByte) { + throw new UnsupportedOperationException(); + } + } +} diff --git a/src/main/java/org/maxgamer/quickshop/Util/Util.java b/src/main/java/org/maxgamer/quickshop/Util/Util.java index e7e931fe9..834cb9a79 100644 --- a/src/main/java/org/maxgamer/quickshop/Util/Util.java +++ b/src/main/java/org/maxgamer/quickshop/Util/Util.java @@ -1,1081 +1,1084 @@ -package org.maxgamer.quickshop.Util; - -import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.AbstractMap.SimpleEntry; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -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.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -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.EnchantmentStorageMeta; -import org.bukkit.material.MaterialData; -import org.bukkit.material.Sign; -import org.bukkit.potion.Potion; -import org.bukkit.potion.PotionEffect; -import org.maxgamer.quickshop.QuickShop; -import org.maxgamer.quickshop.Shop.Shop; - -@SuppressWarnings("deprecation") -public class Util { - private static HashSet tools = new HashSet(); - private static HashSet blacklist = new HashSet(); - private static HashSet shoppables = new HashSet(); - private static HashSet transparent = new HashSet(); - private static Map> restrictedPrices = new HashMap>(); - private static QuickShop plugin; - private static Method storageContents; - - public static void initialize() { - tools.clear(); - blacklist.clear(); - shoppables.clear(); - transparent.clear(); - restrictedPrices.clear(); - - plugin = QuickShop.instance; - for (String s : plugin.getConfig().getStringList("shop-blocks")) { - Material mat = Material.getMaterial(s.toUpperCase()); - if (mat == null) { - try { - mat = Material.getMaterial(Integer.parseInt(s)); - } catch (NumberFormatException e) { - } - } - if (mat == null) { - plugin.getLogger().info("Invalid shop-block: " + s); - } else { - shoppables.add(mat); - } - } - tools.add(Material.BOW); - tools.add(Material.SHEARS); - tools.add(Material.FISHING_ROD); - tools.add(Material.FLINT_AND_STEEL); - tools.add(Material.CHAINMAIL_BOOTS); - tools.add(Material.CHAINMAIL_CHESTPLATE); - tools.add(Material.CHAINMAIL_HELMET); - tools.add(Material.CHAINMAIL_LEGGINGS); - tools.add(Material.WOOD_AXE); - tools.add(Material.WOOD_HOE); - tools.add(Material.WOOD_PICKAXE); - tools.add(Material.WOOD_SPADE); - tools.add(Material.WOOD_SWORD); - tools.add(Material.LEATHER_BOOTS); - tools.add(Material.LEATHER_CHESTPLATE); - tools.add(Material.LEATHER_HELMET); - tools.add(Material.LEATHER_LEGGINGS); - tools.add(Material.DIAMOND_AXE); - tools.add(Material.DIAMOND_HOE); - tools.add(Material.DIAMOND_PICKAXE); - tools.add(Material.DIAMOND_SPADE); - tools.add(Material.DIAMOND_SWORD); - tools.add(Material.DIAMOND_BOOTS); - tools.add(Material.DIAMOND_CHESTPLATE); - tools.add(Material.DIAMOND_HELMET); - tools.add(Material.DIAMOND_LEGGINGS); - tools.add(Material.STONE_AXE); - tools.add(Material.STONE_HOE); - tools.add(Material.STONE_PICKAXE); - tools.add(Material.STONE_SPADE); - tools.add(Material.STONE_SWORD); - tools.add(Material.GOLD_AXE); - tools.add(Material.GOLD_HOE); - tools.add(Material.GOLD_PICKAXE); - tools.add(Material.GOLD_SPADE); - tools.add(Material.GOLD_SWORD); - tools.add(Material.GOLD_BOOTS); - tools.add(Material.GOLD_CHESTPLATE); - tools.add(Material.GOLD_HELMET); - tools.add(Material.GOLD_LEGGINGS); - tools.add(Material.IRON_AXE); - tools.add(Material.IRON_HOE); - tools.add(Material.IRON_PICKAXE); - tools.add(Material.IRON_SPADE); - tools.add(Material.IRON_SWORD); - tools.add(Material.IRON_BOOTS); - tools.add(Material.IRON_CHESTPLATE); - tools.add(Material.IRON_HELMET); - tools.add(Material.IRON_LEGGINGS); - List configBlacklist = plugin.getConfig().getStringList("blacklist"); - for (String s : configBlacklist) { - Material mat = Material.getMaterial(s.toUpperCase()); - if (mat == null) { - mat = Material.getMaterial(Integer.parseInt(s)); - if (mat == null) { - plugin.getLogger().info(s + " is not a valid material. Check your spelling or ID"); - continue; - } - } - blacklist.add(mat); - } - - // ToDo: add extras to config file - addTransparentBlock(Material.AIR); - /* Misc */ - addTransparentBlock(Material.CAKE_BLOCK); - /* Redstone Material */ - addTransparentBlock(Material.REDSTONE_WIRE); - /* Redstone Torches */ - addTransparentBlock(Material.REDSTONE_TORCH_OFF); - addTransparentBlock(Material.REDSTONE_TORCH_ON); - /* Diodes (Repeaters) */ - addTransparentBlock(Material.DIODE_BLOCK_OFF); - addTransparentBlock(Material.DIODE_BLOCK_ON); - /* Power Sources */ - addTransparentBlock(Material.DETECTOR_RAIL); - addTransparentBlock(Material.LEVER); - addTransparentBlock(Material.STONE_BUTTON); - addTransparentBlock(Material.WOOD_BUTTON); - addTransparentBlock(Material.STONE_PLATE); - addTransparentBlock(Material.WOOD_PLATE); - /* Nature Material */ - addTransparentBlock(Material.RED_MUSHROOM); - addTransparentBlock(Material.BROWN_MUSHROOM); - addTransparentBlock(Material.RED_ROSE); - addTransparentBlock(Material.YELLOW_FLOWER); - addTransparentBlock(Material.FLOWER_POT); - /* Greens */ - addTransparentBlock(Material.LONG_GRASS); - addTransparentBlock(Material.VINE); - addTransparentBlock(Material.WATER_LILY); - /* Seedy things */ - addTransparentBlock(Material.MELON_STEM); - addTransparentBlock(Material.PUMPKIN_STEM); - addTransparentBlock(Material.CROPS); - addTransparentBlock(Material.NETHER_WARTS); - /* Semi-nature */ - addTransparentBlock(Material.SNOW); - addTransparentBlock(Material.FIRE); - addTransparentBlock(Material.WEB); - addTransparentBlock(Material.TRIPWIRE); - addTransparentBlock(Material.TRIPWIRE_HOOK); - /* Stairs */ - addTransparentBlock(Material.COBBLESTONE_STAIRS); - addTransparentBlock(Material.BRICK_STAIRS); - addTransparentBlock(Material.SANDSTONE_STAIRS); - addTransparentBlock(Material.NETHER_BRICK_STAIRS); - addTransparentBlock(Material.SMOOTH_STAIRS); - /* Wood Stairs */ - addTransparentBlock(Material.BIRCH_WOOD_STAIRS); - addTransparentBlock(Material.WOOD_STAIRS); - addTransparentBlock(Material.JUNGLE_WOOD_STAIRS); - addTransparentBlock(Material.SPRUCE_WOOD_STAIRS); - /* Lava & Water */ - addTransparentBlock(Material.LAVA); - addTransparentBlock(Material.STATIONARY_LAVA); - addTransparentBlock(Material.WATER); - addTransparentBlock(Material.STATIONARY_WATER); - /* Saplings and bushes */ - addTransparentBlock(Material.SAPLING); - addTransparentBlock(Material.DEAD_BUSH); - /* Construction Material */ - /* Fences */ - addTransparentBlock(Material.FENCE); - addTransparentBlock(Material.FENCE_GATE); - addTransparentBlock(Material.IRON_FENCE); - addTransparentBlock(Material.NETHER_FENCE); - /* Ladders, Signs */ - addTransparentBlock(Material.LADDER); - addTransparentBlock(Material.SIGN_POST); - addTransparentBlock(Material.WALL_SIGN); - /* Bed */ - addTransparentBlock(Material.BED_BLOCK); - /* Pistons */ - addTransparentBlock(Material.PISTON_EXTENSION); - addTransparentBlock(Material.PISTON_MOVING_PIECE); - addTransparentBlock(Material.RAILS); - /* Torch & Trapdoor */ - addTransparentBlock(Material.TORCH); - addTransparentBlock(Material.TRAP_DOOR); - /* New */ - addTransparentBlock(Material.BREWING_STAND); - addTransparentBlock(Material.WOODEN_DOOR); - addTransparentBlock(Material.WOOD_STEP); - - 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); - } - - public static boolean isTransparent(Material m) { - boolean trans = transparent.contains(m); - return trans; - } - - public static void addTransparentBlock(Material m) { - if (transparent.add(m) == false) { - System.out.println("Already added as transparent: " + m.toString()); - } - if (!m.isBlock()) - System.out.println(m + " is not a block!"); - } - - 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); - } - } - - /** - * 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. - * @return True if it can be made into a shop, otherwise false. - */ - public static boolean canBeShop(Block b) { - BlockState bs = b.getState(); - if (bs instanceof InventoryHolder == false) - return false; - 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 = item.getDurability(); - 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. - */ - public static Block getSecondHalf(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; - } - - /** - * 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; - } - - /** - * Converts a string into an item from the database. - * - * @param itemString - * The database string. Is the result of makeString(ItemStack - * item). - * @return A new itemstack, with the properties given in the string - */ - public static ItemStack makeItem(String itemString) { - String[] itemInfo = itemString.split(":"); - ItemStack item = new ItemStack(Material.getMaterial(itemInfo[0])); - MaterialData data = new MaterialData(Integer.parseInt(itemInfo[1])); - item.setData(data); - item.setDurability(Short.parseShort(itemInfo[2])); - item.setAmount(Integer.parseInt(itemInfo[3])); - for (int i = 4; i < itemInfo.length; i = i + 2) { - int level = Integer.parseInt(itemInfo[i + 1]); - Enchantment ench = Enchantment.getByName(itemInfo[i]); - if (ench == null) - continue; // Invalid - if (ench.canEnchantItem(item)) { - if (level <= 0) - continue; - level = Math.min(ench.getMaxLevel(), level); - item.addEnchantment(ench, level); - } - } - return item; - } - - public static String serialize(ItemStack iStack) { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.set("item", iStack); - return cfg.saveToString(); - } - - public static ItemStack deserialize(String config) throws InvalidConfigurationException { - YamlConfiguration cfg = new YamlConfiguration(); - cfg.loadFromString(config); - 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); - } - - CustomItemName customItemName = QuickShop.instance.getCustomItemNames(itemStack); - if (customItemName!=null) { - return customItemName.getFullName(); - } - - String vanillaName = getDataName(itemStack.getType(), itemStack.getDurability()); - 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(); - } - - // 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); - CustomItemName customItemName = QuickShop.instance.getCustomItemNames(is); - if (customItemName!=null) { - return customItemName.getSignName(); - } - - String name = getDataName(itemStack.getType(), itemStack.getDurability()); - - 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; - } - - /** - * Converts a given material and data value into a format similar to - * Material..toString(). Upper case, with underscores. Includes material - * name in result. - * - * @param mat - * The base material. - * @param damage - * The durability/damage of the item. - * @return A string with the name of the item. - */ - private static String getDataName(Material mat, short damage) { - int id = mat.getId(); - switch (id) { - case 35: - switch ((int) damage) { - case 0: - return "WHITE_WOOL"; - case 1: - return "ORANGE_WOOL"; - case 2: - return "MAGENTA_WOOL"; - case 3: - return "LIGHT_BLUE_WOOL"; - case 4: - return "YELLOW_WOOL"; - case 5: - return "LIME_WOOL"; - case 6: - return "PINK_WOOL"; - case 7: - return "GRAY_WOOL"; - case 8: - return "LIGHT_GRAY_WOOL"; - case 9: - return "CYAN_WOOL"; - case 10: - return "PURPLE_WOOL"; - case 11: - return "BLUE_WOOL"; - case 12: - return "BROWN_WOOL"; - case 13: - return "GREEN_WOOL"; - case 14: - return "RED_WOOL"; - case 15: - return "BLACK_WOOL"; - } - return mat.toString(); - case 351: - switch ((int) damage) { - case 0: - return "INK_SAC"; - case 1: - return "ROSE_RED"; - case 2: - return "CACTUS_GREEN"; - case 3: - return "COCOA_BEANS"; - case 4: - return "LAPIS_LAZULI"; - case 5: - return "PURPLE_DYE"; - case 6: - return "CYAN_DYE"; - case 7: - return "LIGHT_GRAY_DYE"; - case 8: - return "GRAY_DYE"; - case 9: - return "PINK_DYE"; - case 10: - return "LIME_DYE"; - case 11: - return "DANDELION_YELLOW"; - case 12: - return "LIGHT_BLUE_DYE"; - case 13: - return "MAGENTA_DYE"; - case 14: - return "ORANGE_DYE"; - case 15: - return "BONE_MEAL"; - } - return mat.toString(); - case 98: - switch ((int) damage) { - case 0: - return "STONE_BRICKS"; - case 1: - return "MOSSY_STONE_BRICKS"; - case 2: - return "CRACKED_STONE_BRICKS"; - case 3: - return "CHISELED_STONE_BRICKS"; - } - return mat.toString(); - case 373: - // Special case,.. Why? - if (damage == 0) - return "WATER_BOTTLE"; - Potion pot; - try { - pot = Potion.fromDamage(damage); - } catch (Exception e) { - return "CUSTOM_POTION"; - } - String prefix = ""; - String suffix = ""; - if (pot.getLevel() > 0) - suffix += "_" + pot.getLevel(); - if (pot.hasExtendedDuration()) - prefix += "EXTENDED_"; - if (pot.isSplash()) - prefix += "SPLASH_"; - if (pot.getEffects().isEmpty()) { - switch ((int) pot.getNameId()) { - case 0: - return prefix + "MUNDANE_POTION" + suffix; - case 7: - return prefix + "CLEAR_POTION" + suffix; - case 11: - return prefix + "DIFFUSE_POTION" + suffix; - case 13: - return prefix + "ARTLESS_POTION" + suffix; - case 15: - return prefix + "THIN_POTION" + suffix; - case 16: - return prefix + "AWKWARD_POTION" + suffix; - case 32: - return prefix + "THICK_POTION" + suffix; - } - } else { - String effects = ""; - for (PotionEffect effect : pot.getEffects()) { - effects += effect.toString().split(":")[0]; - } - return prefix + effects + suffix; - } - return mat.toString(); - case 6: - switch ((int) damage) { - case 0: - return "OAK_SAPLING"; - case 1: - return "PINE_SAPLING"; - case 2: - return "BIRCH_SAPLING"; - case 3: - return "JUNGLE_TREE_SAPLING"; - } - return mat.toString(); - case 5: - switch ((int) damage) { - case 0: - return "OAK_PLANKS"; - case 1: - return "PINE_PLANKS"; - case 2: - return "BIRCH_PLANKS"; - case 3: - return "JUNGLE_PLANKS"; - } - return mat.toString(); - case 17: - switch (damage) { - case 0: - return "OAK_LOG"; - case 1: - return "PINE_LOG"; - case 2: - return "BIRCH_LOG"; - case 3: - return "JUNGLE_LOG"; - } - return mat.toString(); - case 18: - damage = (short) (damage % 4); - switch (damage) { - case 0: - return "OAK_LEAVES"; - case 1: - return "PINE_LEAVES"; - case 2: - return "BIRCH_LEAVES"; - case 3: - return "JUNGLE_LEAVES"; - } - case 263: - switch (damage) { - case 0: - return "COAL"; - case 1: - return "CHARCOAL"; - } - return mat.toString(); - case 24: - switch ((int) damage) { - case 0: - return "SANDSTONE"; - case 1: - return "CHISELED_SANDSTONE"; - case 2: - return "SMOOTH_SANDSTONE"; - } - return mat.toString(); - case 31: - switch ((int) damage) { - case 0: - return "DEAD_SHRUB"; - case 1: - return "TALL_GRASS"; - case 2: - return "FERN"; - } - return mat.toString(); - case 44: - switch ((int) damage) { - case 0: - return "STONE_SLAB"; - case 1: - return "SANDSTONE_SLAB"; - case 2: - return "WOODEN_SLAB"; - case 3: - return "COBBLESTONE_SLAB"; - case 4: - return "BRICK_SLAB"; - case 5: - return "STONE_BRICK_SLAB"; - } - return mat.toString(); - case 383: - switch ((int) damage) { - case 50: - return "CREEPER_EGG"; - case 51: - return "SKELETON_EGG"; - case 52: - return "SPIDER_EGG"; - case 53: - return "GIANT_EGG"; - case 54: - return "ZOMBIE_EGG"; - case 55: - return "SLIME_EGG"; - case 56: - return "GHAST_EGG"; - case 57: - return "ZOMBIE_PIGMAN_EGG"; - case 58: - return "ENDERMAN_EGG"; - case 59: - return "CAVE_SPIDER_EGG"; - case 60: - return "SILVERFISH_EGG"; - case 61: - return "BLAZE_EGG"; - case 62: - return "MAGMA_CUBE_EGG"; - case 63: - return "ENDER_DRAGON_EGG"; - case 90: - return "PIG_EGG"; - case 91: - return "SHEEP_EGG"; - case 92: - return "COW_EGG"; - case 93: - return "CHICKEN_EGG"; - case 94: - return "SQUID_EGG"; - case 95: - return "WOLF_EGG"; - case 96: - return "MOOSHROOM_EGG"; - case 97: - return "SNOW_GOLEM_EGG"; - case 98: - return "OCELOT_EGG"; - case 99: - return "IRON_GOLEM_EGG"; - case 120: - return "VILLAGER_EGG"; - case 200: - return "ENDER_CRYSTAL_EGG"; - case 14: - return "PRIMED_TNT_EGG"; - case 66: - return "WITCH_EGG"; - case 65: - return "BAT_EGG"; - } - return mat.toString(); - case 397: - switch ((int) damage) { - case 0: - return "SKELETON_SKULL"; - case 1: - return "WITHER_SKULL"; - case 2: - return "ZOMBIE_HEAD"; - case 3: - return "PLAYER_HEAD"; - case 4: - return "CREEPER_HEAD"; - } - break; - case 76: - return "REDSTONE_TORCH"; - case 115: - return "NETHER_WART"; - case 30: - return "COBWEB"; - case 102: - return "GLASS_PANE"; - case 101: - return "IRON_BARS"; - case 58: - return "CRAFTING_TABLE"; - case 123: - return "REDSTONE_LAMP"; - case 392: - return "POTATO"; - case 289: - return "GUNPOWDER"; - case 391: - return "CARROT"; - case 322: - switch ((int) damage) { - case 0: - return "GOLDEN_APPLE"; - case 1: - return "ENCHANTED_GOLDEN_APPLE"; - } - break; - case 390: - return "FLOWER_POT"; - case 145: - switch ((int) damage) { - case 0: - return "ANVIL"; - case 1: - return "SLIGHTLY_DAMAGED_ANVIL"; - case 2: - return "VERY_DAMAGED:ANVIL"; - } - break; - case 384: - return "BOTTLE_O'_ENCHANTING"; - case 402: - return "FIREWORK_STAR"; - case 385: - return "FIREWORK_CHARGE"; - } - if (damage == 0 || isTool(mat)) - return mat.toString(); - return mat.toString() + ":" + damage; - } - - /** - * @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) { - return tools.contains(mat); - } - - /** - * 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 (stack1.getDurability() != stack2.getDurability()) - 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) { - try { - return plugin.getEcon().format(n); - } catch (NumberFormatException e) { - 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(); - } - } - 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); - } - 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) { - // System.out.println("Checking isLoaded(Location loc)"); - if (loc.getWorld() == null) { - // System.out.println("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)) { - // System.out.println("Chunk is loaded " + x + ", " + z); - return true; - } else { - // System.out.println("Chunk is NOT loaded " + x + ", " + z); - return false; - } - } - - 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; - } - } - - - public static boolean isClassAvailable(String qualifiedName) { - try { - Class.forName(qualifiedName); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - public static void sendMessageToOps(String message) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.isOp()) { - player.sendMessage(message); - } - } - } -} +package org.maxgamer.quickshop.Util; + +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.AbstractMap.SimpleEntry; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +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.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +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.EnchantmentStorageMeta; +import org.bukkit.material.MaterialData; +import org.bukkit.material.Sign; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionEffect; +import org.maxgamer.quickshop.QuickShop; +import org.maxgamer.quickshop.Shop.Shop; + +@SuppressWarnings("deprecation") +public class Util { + private static HashSet tools = new HashSet(); + private static HashSet blacklist = new HashSet(); + private static HashSet shoppables = new HashSet(); + private static HashSet transparent = new HashSet(); + private static Map> restrictedPrices = new HashMap>(); + private static QuickShop plugin; + private static Method storageContents; + + public static void initialize() { + tools.clear(); + blacklist.clear(); + shoppables.clear(); + transparent.clear(); + restrictedPrices.clear(); + + plugin = QuickShop.instance; + for (String s : plugin.getConfig().getStringList("shop-blocks")) { + Material mat = Material.getMaterial(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); + } + } + tools.add(Material.BOW); + tools.add(Material.SHEARS); + tools.add(Material.FISHING_ROD); + tools.add(Material.FLINT_AND_STEEL); + tools.add(Material.CHAINMAIL_BOOTS); + tools.add(Material.CHAINMAIL_CHESTPLATE); + tools.add(Material.CHAINMAIL_HELMET); + tools.add(Material.CHAINMAIL_LEGGINGS); + tools.add(Material.WOODEN_AXE); + tools.add(Material.WOODEN_HOE); + tools.add(Material.WOODEN_PICKAXE); + tools.add(Material.WOODEN_SHOVEL); + tools.add(Material.WOODEN_SWORD); + tools.add(Material.LEATHER_BOOTS); + tools.add(Material.LEATHER_CHESTPLATE); + tools.add(Material.LEATHER_HELMET); + tools.add(Material.LEATHER_LEGGINGS); + tools.add(Material.DIAMOND_AXE); + tools.add(Material.DIAMOND_HOE); + tools.add(Material.DIAMOND_PICKAXE); + tools.add(Material.DIAMOND_SHOVEL); + tools.add(Material.DIAMOND_SWORD); + tools.add(Material.DIAMOND_BOOTS); + tools.add(Material.DIAMOND_CHESTPLATE); + tools.add(Material.DIAMOND_HELMET); + tools.add(Material.DIAMOND_LEGGINGS); + tools.add(Material.STONE_AXE); + tools.add(Material.STONE_HOE); + tools.add(Material.STONE_PICKAXE); + tools.add(Material.STONE_SHOVEL); + tools.add(Material.STONE_SWORD); + tools.add(Material.GOLDEN_AXE); + tools.add(Material.GOLDEN_HOE); + tools.add(Material.GOLDEN_PICKAXE); + tools.add(Material.GOLDEN_SHOVEL); + tools.add(Material.GOLDEN_SWORD); + tools.add(Material.GOLDEN_BOOTS); + tools.add(Material.GOLDEN_CHESTPLATE); + tools.add(Material.GOLDEN_HELMET); + tools.add(Material.GOLDEN_LEGGINGS); + tools.add(Material.IRON_AXE); + tools.add(Material.IRON_HOE); + tools.add(Material.IRON_PICKAXE); + tools.add(Material.IRON_SHOVEL); + tools.add(Material.IRON_SWORD); + tools.add(Material.IRON_BOOTS); + tools.add(Material.IRON_CHESTPLATE); + tools.add(Material.IRON_HELMET); + tools.add(Material.IRON_LEGGINGS); + 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); + } + + // ToDo: add extras to config file + addTransparentBlock(Material.AIR); + /* Misc */ + addTransparentBlock(Material.CAKE); + /* Redstone Material */ + addTransparentBlock(Material.REDSTONE_WIRE); + /* Redstone Torches */ + addTransparentBlock(Material.REDSTONE_TORCH); + /* Diodes (Repeaters) */ + addTransparentBlock(Material.LEGACY_DIODE_BLOCK_OFF); + addTransparentBlock(Material.LEGACY_DIODE_BLOCK_ON); + /* Power Sources */ + addTransparentBlock(Material.DETECTOR_RAIL); + addTransparentBlock(Material.LEVER); + addTransparentBlock(Material.STONE_BUTTON); + addTransparentBlock(Material.LEGACY_WOOD_BUTTON); + addTransparentBlock(Material.LEGACY_STONE_PLATE); + addTransparentBlock(Material.LEGACY_WOOD_PLATE); + /* Nature Material */ + addTransparentBlock(Material.RED_MUSHROOM); + addTransparentBlock(Material.BROWN_MUSHROOM); + addTransparentBlock(Material.LEGACY_RED_ROSE); + addTransparentBlock(Material.LEGACY_YELLOW_FLOWER); + addTransparentBlock(Material.FLOWER_POT); + /* Greens */ + addTransparentBlock(Material.LEGACY_LONG_GRASS); + addTransparentBlock(Material.VINE); + addTransparentBlock(Material.LEGACY_WATER_LILY); + /* Seedy things */ + addTransparentBlock(Material.MELON_STEM); + addTransparentBlock(Material.PUMPKIN_STEM); + addTransparentBlock(Material.LEGACY_CROPS); + addTransparentBlock(Material.LEGACY_NETHER_WARTS); + /* Semi-nature */ + addTransparentBlock(Material.SNOW); + addTransparentBlock(Material.FIRE); + addTransparentBlock(Material.COBWEB); + addTransparentBlock(Material.TRIPWIRE); + addTransparentBlock(Material.TRIPWIRE_HOOK); + /* Stairs */ + addTransparentBlock(Material.COBBLESTONE_STAIRS); + addTransparentBlock(Material.BRICK_STAIRS); + addTransparentBlock(Material.SANDSTONE_STAIRS); + addTransparentBlock(Material.NETHER_BRICK_STAIRS); + addTransparentBlock(Material.LEGACY_SMOOTH_STAIRS); + /* Wood Stairs */ + addTransparentBlock(Material.LEGACY_BIRCH_WOOD_STAIRS); + addTransparentBlock(Material.LEGACY_WOOD_STAIRS); + addTransparentBlock(Material.LEGACY_JUNGLE_WOOD_STAIRS); + addTransparentBlock(Material.LEGACY_SPRUCE_WOOD_STAIRS); + addTransparentBlock(Material.PURPUR_STAIRS); + addTransparentBlock(Material.DARK_PRISMARINE_STAIRS); + addTransparentBlock(Material.PRISMARINE_STAIRS); + addTransparentBlock(Material.PRISMARINE_BRICK_STAIRS); + /* Lava & Water */ + addTransparentBlock(Material.LAVA); + addTransparentBlock(Material.LEGACY_STATIONARY_LAVA); + addTransparentBlock(Material.WATER); + addTransparentBlock(Material.LEGACY_STATIONARY_WATER); + /* Saplings and bushes */ + addTransparentBlock(Material.LEGACY_SAPLING); + addTransparentBlock(Material.DEAD_BUSH); + /* Construction Material */ + /* Fences */ + addTransparentBlock(Material.LEGACY_FENCE); + addTransparentBlock(Material.LEGACY_FENCE_GATE); + addTransparentBlock(Material.LEGACY_IRON_FENCE); + addTransparentBlock(Material.LEGACY_NETHER_FENCE); + /* Ladders, Signs */ + addTransparentBlock(Material.LADDER); + addTransparentBlock(Material.LEGACY_SIGN_POST); + addTransparentBlock(Material.WALL_SIGN); + /* Bed */ + addTransparentBlock(Material.LEGACY_BED_BLOCK); + /* Pistons */ + addTransparentBlock(Material.LEGACY_PISTON_EXTENSION); + addTransparentBlock(Material.LEGACY_PISTON_MOVING_PIECE); + addTransparentBlock(Material.LEGACY_RAILS); + /* Torch & Trapdoor */ + addTransparentBlock(Material.TORCH); + addTransparentBlock(Material.LEGACY_TRAP_DOOR); + /* New */ + addTransparentBlock(Material.BREWING_STAND); + addTransparentBlock(Material.LEGACY_WOODEN_DOOR); + addTransparentBlock(Material.LEGACY_WOOD_STEP); + + 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); + } + + public static boolean isTransparent(Material m) { + boolean trans = transparent.contains(m); + return trans; + } + + public static void addTransparentBlock(Material m) { + if (transparent.add(m) == false) { + System.out.println("Already added as transparent: " + m.toString()); + } + if (!m.isBlock()) + System.out.println(m + " is not a block!"); + } + + 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); + } + } + + /** + * 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. + * @return True if it can be made into a shop, otherwise false. + */ + public static boolean canBeShop(Block b) { + BlockState bs = b.getState(); + if (bs instanceof InventoryHolder == false) + return false; + 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 = item.getDurability(); + 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. + */ + public static Block getSecondHalf(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; + } + + /** + * 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; + } + + /** + * Converts a string into an item from the database. + * + * @param itemString + * The database string. Is the result of makeString(ItemStack + * item). + * @return A new itemstack, with the properties given in the string + */ + public static ItemStack makeItem(String itemString) { + String[] itemInfo = itemString.split(":"); + ItemStack item = new ItemStack(Material.getMaterial(itemInfo[0])); + MaterialData data = new MaterialData(Material.matchMaterial(itemInfo[1])); + item.setData(data); + item.setDurability(Short.parseShort(itemInfo[2])); + item.setAmount(Integer.parseInt(itemInfo[3])); + for (int i = 4; i < itemInfo.length; i = i + 2) { + int level = Integer.parseInt(itemInfo[i + 1]); + Enchantment ench = Enchantment.getByName(itemInfo[i]); + if (ench == null) + continue; // Invalid + if (ench.canEnchantItem(item)) { + if (level <= 0) + continue; + level = Math.min(ench.getMaxLevel(), level); + item.addEnchantment(ench, level); + } + } + return item; + } + + public static String serialize(ItemStack iStack) { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.set("item", iStack); + return cfg.saveToString(); + } + + public static ItemStack deserialize(String config) throws InvalidConfigurationException { + YamlConfiguration cfg = new YamlConfiguration(); + cfg.loadFromString(config); + 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); + } + + CustomItemName customItemName = QuickShop.instance.getCustomItemNames(itemStack); + if (customItemName!=null) { + return customItemName.getFullName(); + } + + String vanillaName = getDataName(itemStack.getType(), itemStack.getDurability()); + 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(); + } + + // 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); + CustomItemName customItemName = QuickShop.instance.getCustomItemNames(is); + if (customItemName!=null) { + return customItemName.getSignName(); + } + + String name = getDataName(itemStack.getType(), itemStack.getDurability()); + + 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; + } + + /** + * Converts a given material and data value into a format similar to + * Material..toString(). Upper case, with underscores. Includes material + * name in result. + * + * @param mat + * The base material. + * @param damage + * The durability/damage of the item. + * @return A string with the name of the item. + */ + private static String getDataName(Material mat, short damage) { + int id = mat.getId(); + switch (id) { + case 35: + switch ((int) damage) { + case 0: + return "WHITE_WOOL"; + case 1: + return "ORANGE_WOOL"; + case 2: + return "MAGENTA_WOOL"; + case 3: + return "LIGHT_BLUE_WOOL"; + case 4: + return "YELLOW_WOOL"; + case 5: + return "LIME_WOOL"; + case 6: + return "PINK_WOOL"; + case 7: + return "GRAY_WOOL"; + case 8: + return "LIGHT_GRAY_WOOL"; + case 9: + return "CYAN_WOOL"; + case 10: + return "PURPLE_WOOL"; + case 11: + return "BLUE_WOOL"; + case 12: + return "BROWN_WOOL"; + case 13: + return "GREEN_WOOL"; + case 14: + return "RED_WOOL"; + case 15: + return "BLACK_WOOL"; + } + return mat.toString(); + case 351: + switch ((int) damage) { + case 0: + return "INK_SAC"; + case 1: + return "ROSE_RED"; + case 2: + return "CACTUS_GREEN"; + case 3: + return "COCOA_BEANS"; + case 4: + return "LAPIS_LAZULI"; + case 5: + return "PURPLE_DYE"; + case 6: + return "CYAN_DYE"; + case 7: + return "LIGHT_GRAY_DYE"; + case 8: + return "GRAY_DYE"; + case 9: + return "PINK_DYE"; + case 10: + return "LIME_DYE"; + case 11: + return "DANDELION_YELLOW"; + case 12: + return "LIGHT_BLUE_DYE"; + case 13: + return "MAGENTA_DYE"; + case 14: + return "ORANGE_DYE"; + case 15: + return "BONE_MEAL"; + } + return mat.toString(); + case 98: + switch ((int) damage) { + case 0: + return "STONE_BRICKS"; + case 1: + return "MOSSY_STONE_BRICKS"; + case 2: + return "CRACKED_STONE_BRICKS"; + case 3: + return "CHISELED_STONE_BRICKS"; + } + return mat.toString(); + case 373: + // Special case,.. Why? + if (damage == 0) + return "WATER_BOTTLE"; + Potion pot; + try { + pot = Potion.fromDamage(damage); + } catch (Exception e) { + return "CUSTOM_POTION"; + } + String prefix = ""; + String suffix = ""; + if (pot.getLevel() > 0) + suffix += "_" + pot.getLevel(); + if (pot.hasExtendedDuration()) + prefix += "EXTENDED_"; + if (pot.isSplash()) + prefix += "SPLASH_"; + if (pot.getEffects().isEmpty()) { + switch ((int) pot.getNameId()) { + case 0: + return prefix + "MUNDANE_POTION" + suffix; + case 7: + return prefix + "CLEAR_POTION" + suffix; + case 11: + return prefix + "DIFFUSE_POTION" + suffix; + case 13: + return prefix + "ARTLESS_POTION" + suffix; + case 15: + return prefix + "THIN_POTION" + suffix; + case 16: + return prefix + "AWKWARD_POTION" + suffix; + case 32: + return prefix + "THICK_POTION" + suffix; + } + } else { + String effects = ""; + for (PotionEffect effect : pot.getEffects()) { + effects += effect.toString().split(":")[0]; + } + return prefix + effects + suffix; + } + return mat.toString(); + case 6: + switch ((int) damage) { + case 0: + return "OAK_SAPLING"; + case 1: + return "PINE_SAPLING"; + case 2: + return "BIRCH_SAPLING"; + case 3: + return "JUNGLE_TREE_SAPLING"; + } + return mat.toString(); + case 5: + switch ((int) damage) { + case 0: + return "OAK_PLANKS"; + case 1: + return "PINE_PLANKS"; + case 2: + return "BIRCH_PLANKS"; + case 3: + return "JUNGLE_PLANKS"; + } + return mat.toString(); + case 17: + switch (damage) { + case 0: + return "OAK_LOG"; + case 1: + return "PINE_LOG"; + case 2: + return "BIRCH_LOG"; + case 3: + return "JUNGLE_LOG"; + } + return mat.toString(); + case 18: + damage = (short) (damage % 4); + switch (damage) { + case 0: + return "OAK_LEAVES"; + case 1: + return "PINE_LEAVES"; + case 2: + return "BIRCH_LEAVES"; + case 3: + return "JUNGLE_LEAVES"; + } + case 263: + switch (damage) { + case 0: + return "COAL"; + case 1: + return "CHARCOAL"; + } + return mat.toString(); + case 24: + switch ((int) damage) { + case 0: + return "SANDSTONE"; + case 1: + return "CHISELED_SANDSTONE"; + case 2: + return "SMOOTH_SANDSTONE"; + } + return mat.toString(); + case 31: + switch ((int) damage) { + case 0: + return "DEAD_SHRUB"; + case 1: + return "TALL_GRASS"; + case 2: + return "FERN"; + } + return mat.toString(); + case 44: + switch ((int) damage) { + case 0: + return "STONE_SLAB"; + case 1: + return "SANDSTONE_SLAB"; + case 2: + return "WOODEN_SLAB"; + case 3: + return "COBBLESTONE_SLAB"; + case 4: + return "BRICK_SLAB"; + case 5: + return "STONE_BRICK_SLAB"; + } + return mat.toString(); + case 383: + switch ((int) damage) { + case 50: + return "CREEPER_EGG"; + case 51: + return "SKELETON_EGG"; + case 52: + return "SPIDER_EGG"; + case 53: + return "GIANT_EGG"; + case 54: + return "ZOMBIE_EGG"; + case 55: + return "SLIME_EGG"; + case 56: + return "GHAST_EGG"; + case 57: + return "ZOMBIE_PIGMAN_EGG"; + case 58: + return "ENDERMAN_EGG"; + case 59: + return "CAVE_SPIDER_EGG"; + case 60: + return "SILVERFISH_EGG"; + case 61: + return "BLAZE_EGG"; + case 62: + return "MAGMA_CUBE_EGG"; + case 63: + return "ENDER_DRAGON_EGG"; + case 90: + return "PIG_EGG"; + case 91: + return "SHEEP_EGG"; + case 92: + return "COW_EGG"; + case 93: + return "CHICKEN_EGG"; + case 94: + return "SQUID_EGG"; + case 95: + return "WOLF_EGG"; + case 96: + return "MOOSHROOM_EGG"; + case 97: + return "SNOW_GOLEM_EGG"; + case 98: + return "OCELOT_EGG"; + case 99: + return "IRON_GOLEM_EGG"; + case 120: + return "VILLAGER_EGG"; + case 200: + return "ENDER_CRYSTAL_EGG"; + case 14: + return "PRIMED_TNT_EGG"; + case 66: + return "WITCH_EGG"; + case 65: + return "BAT_EGG"; + } + return mat.toString(); + case 397: + switch ((int) damage) { + case 0: + return "SKELETON_SKULL"; + case 1: + return "WITHER_SKULL"; + case 2: + return "ZOMBIE_HEAD"; + case 3: + return "PLAYER_HEAD"; + case 4: + return "CREEPER_HEAD"; + } + break; + case 76: + return "REDSTONE_TORCH"; + case 115: + return "NETHER_WART"; + case 30: + return "COBWEB"; + case 102: + return "GLASS_PANE"; + case 101: + return "IRON_BARS"; + case 58: + return "CRAFTING_TABLE"; + case 123: + return "REDSTONE_LAMP"; + case 392: + return "POTATO"; + case 289: + return "GUNPOWDER"; + case 391: + return "CARROT"; + case 322: + switch ((int) damage) { + case 0: + return "GOLDEN_APPLE"; + case 1: + return "ENCHANTED_GOLDEN_APPLE"; + } + break; + case 390: + return "FLOWER_POT"; + case 145: + switch ((int) damage) { + case 0: + return "ANVIL"; + case 1: + return "SLIGHTLY_DAMAGED_ANVIL"; + case 2: + return "VERY_DAMAGED:ANVIL"; + } + break; + case 384: + return "BOTTLE_O'_ENCHANTING"; + case 402: + return "FIREWORK_STAR"; + case 385: + return "FIREWORK_CHARGE"; + } + if (damage == 0 || isTool(mat)) + return mat.toString(); + return mat.toString() + ":" + damage; + } + + /** + * @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) { + return tools.contains(mat); + } + + /** + * 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 (stack1.getDurability() != stack2.getDurability()) + 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) { + try { + return plugin.getEcon().format(n); + } catch (NumberFormatException e) { + 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(); + } + } + 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); + } + 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) { + // System.out.println("Checking isLoaded(Location loc)"); + if (loc.getWorld() == null) { + // System.out.println("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)) { + // System.out.println("Chunk is loaded " + x + ", " + z); + return true; + } else { + // System.out.println("Chunk is NOT loaded " + x + ", " + z); + return false; + } + } + + 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; + } + } + + + public static boolean isClassAvailable(String qualifiedName) { + try { + Class.forName(qualifiedName); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + + public static void sendMessageToOps(String message) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.isOp()) { + player.sendMessage(message); + } + } + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 972adcbe8..3a04ff79b 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,60 +1,60 @@ -name: ${name} -main: ${package}.${name} -version: ${version} -authors: [Netherfoam, Timtower, KaiNoMood] - -description: Economy Shops plugin -softdepend: [Herochat, Vault, Essentials, OpenInv] - -commands: - qs: - description: QuickShop command - usage: /qs - aliases: [shop] - -permissions: - quickshop.create.sell: - description: Allows a player to sell from a shop - default: op - quickshop.create.buy: - description: Allows a player to buy from a shop - default: op - quickshop.create.double: - description: Allows a player to create a double shop - default: op - quickshop.use: - description: Allows a player to buy/sell using other players shops - default: true - quickshop.unlimited: - description: Allows a Staff Member to use /qs unlimited and make a shop infinite - quickshop.bypass.: - description: Allows a player to sell , even if its blacklisted - quickshop.other.destroy: - description: Allows a Staff Member to destroy other players shops if they are locked in the config - quickshop.other.open: - description: Allows a Staff Member to open someone elses shop if they are locked in the config - quickshop.other.price: - description: Allows a Staff Member to change the price of someone elses shop - quickshop.setowner: - description: Allows a Staff Member to change the owner of any shop - quickshop.find: - description: Allows a player to locate the nearest shop of a specific item type. Works in a 3 chunk radius. - default: true - quickshop.refill: - description: Allows a Staff Member to refill the shop theyre looking at with the given number of items. - default: op - quickshop.empty: - description: Allows a Staff Member to empty the shop theyre looking at of all items. - default: op - quickshop.debug: - description: Enables debug info to console - default: op - quickshop.export: - description: Allows exporting database to mysql or sqlite - default: op - quickshop.taxexemption: - description: Tax exemption - default: false - quickshop.alerts: - description: Alert the player when someone tries to cheat with the display item +name: ${name} +main: ${package}.${name} +version: ${version} +authors: [Netherfoam, Timtower, KaiNoMood] + +description: Economy Shops plugin +softdepend: [Herochat, Vault, Essentials, OpenInv] +api-version: 1.13 +commands: + qs: + description: QuickShop command + usage: /qs + aliases: [shop] + +permissions: + quickshop.create.sell: + description: Allows a player to sell from a shop + default: op + quickshop.create.buy: + description: Allows a player to buy from a shop + default: op + quickshop.create.double: + description: Allows a player to create a double shop + default: op + quickshop.use: + description: Allows a player to buy/sell using other players shops + default: true + quickshop.unlimited: + description: Allows a Staff Member to use /qs unlimited and make a shop infinite + quickshop.bypass.: + description: Allows a player to sell , even if its blacklisted + quickshop.other.destroy: + description: Allows a Staff Member to destroy other players shops if they are locked in the config + quickshop.other.open: + description: Allows a Staff Member to open someone elses shop if they are locked in the config + quickshop.other.price: + description: Allows a Staff Member to change the price of someone elses shop + quickshop.setowner: + description: Allows a Staff Member to change the owner of any shop + quickshop.find: + description: Allows a player to locate the nearest shop of a specific item type. Works in a 3 chunk radius. + default: true + quickshop.refill: + description: Allows a Staff Member to refill the shop theyre looking at with the given number of items. + default: op + quickshop.empty: + description: Allows a Staff Member to empty the shop theyre looking at of all items. + default: op + quickshop.debug: + description: Enables debug info to console + default: op + quickshop.export: + description: Allows exporting database to mysql or sqlite + default: op + quickshop.taxexemption: + description: Tax exemption + default: false + quickshop.alerts: + description: Alert the player when someone tries to cheat with the display item default: op \ No newline at end of file