diff options
Diffstat (limited to 'Essentials/src/com')
100 files changed, 9046 insertions, 0 deletions
diff --git a/Essentials/src/com/earth2me/essentials/Backup.java b/Essentials/src/com/earth2me/essentials/Backup.java new file mode 100644 index 000000000..aa0cb1476 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Backup.java @@ -0,0 +1,82 @@ +package com.earth2me.essentials; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; + +public class Backup implements Runnable { + private static final Logger logger = Logger.getLogger("Minecraft"); + private CraftServer server; + private boolean running = false; + private int taskId = -1; + private boolean active = false; + + public Backup() { + server = (CraftServer)Essentials.getStatic().getServer(); + if (server.getOnlinePlayers().length > 0) { + startTask(); + } + } + + void onPlayerJoin() { + startTask(); + } + + private void startTask() { + if (!running) { + long interval = Essentials.getSettings().getBackupInterval()*1200; // minutes -> ticks + if (interval < 1200) { + return; + } + taskId = server.getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), this, interval, interval); + running = true; + } + } + + public void run() { + if (active) return; + active = true; + final String command = Essentials.getSettings().getBackupCommand(); + if (command == null || "".equals(command)) { + return; + } + logger.log(Level.INFO, "Backup started"); + final CommandSender cs = server.getServer().console; + server.dispatchCommand(cs, "save-all"); + server.dispatchCommand(cs, "save-off"); + + server.getScheduler().scheduleAsyncDelayedTask(Essentials.getStatic(), + new Runnable() { + + public void run() { + try { + Process child = Runtime.getRuntime().exec(command); + child.waitFor(); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } finally { + server.getScheduler().scheduleSyncDelayedTask(Essentials.getStatic(), + new Runnable() { + + public void run() { + server.dispatchCommand(cs, "save-on"); + if (server.getOnlinePlayers().length == 0) { + running = false; + if (taskId != -1) { + server.getScheduler().cancelTask(taskId); + } + } + active = false; + logger.log(Level.INFO, "Backup finished"); + } + }); + } + } + }); + } + +} diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java new file mode 100644 index 000000000..73c6aade9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -0,0 +1,688 @@ +package com.earth2me.essentials; + +import com.earth2me.essentials.commands.EssentialsCommand; +import java.io.*; +import java.util.*; +import java.util.logging.*; +import org.bukkit.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.commands.IEssentialsCommand; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.bukkit.command.PluginCommand; +import org.bukkit.craftbukkit.scheduler.CraftScheduler; +import org.bukkit.entity.Player; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.Event.Type; +import org.bukkit.plugin.*; +import org.bukkit.plugin.java.*; +import org.yaml.snakeyaml.*; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + + +public class Essentials extends JavaPlugin +{ + public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans."; + public static final int minBukkitBuildVersion = 556; + private static final Logger logger = Logger.getLogger("Minecraft"); + private static final Yaml yaml = new Yaml(new SafeConstructor()); + private static Map<String, Object> users; + private static Settings settings; + private static final Object usersLock = new Object(); + public static Object permissions = null; + public final Map<User, User> tpcRequests = new HashMap<User, User>(); + public final Map<User, Boolean> tpcHere = new HashMap<User, Boolean>(); + public final List<User> away = new ArrayList<User>(); + private EssentialsPlayerListener playerListener; + private EssentialsBlockListener blockListener; + private EssentialsEntityListener entityListener; + private static Essentials staticThis = null; + public Spawn spawn; + private Jail jail; + private Warps warps; + private List<IConf> confList; + public ArrayList bans = new ArrayList(); + public ArrayList bannedIps = new ArrayList(); + public Backup backup; + + public Essentials() throws IOException + { + loadClasses(); + } + + public static void ensureEnabled(Server server) + { + PluginManager pm = server.getPluginManager(); + Essentials ess = (Essentials)pm.getPlugin("Essentials"); + if (!ess.isEnabled()) + pm.enablePlugin(ess); + loadClasses(); + } + + @SuppressWarnings("CallToThreadDumpStack") + public static void loadClasses() + { + final String[] classes = new String[] + { + "commands.IEssentialsCommand", + "commands.EssentialsCommand", + "User", + "TargetBlock", + "Spawn", + "Settings", + "OfflinePlayer", + "ItemDb", + "Mob" + }; + + try + { + for (String c : classes) + Essentials.class.getClassLoader().loadClass("com.earth2me.essentials." + c); + } + catch (Throwable ex) + { + ex.printStackTrace(); + } + } + + public static Essentials getStatic() + { + return staticThis; + } + + public static Settings getSettings() + { + return settings; + } + + public void setupPermissions() + { + Plugin permPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); + if (permissions == null && permPlugin != null) permissions = permPlugin; + } + + public Player getPlayer(String[] args, int pos) + throws IndexOutOfBoundsException, NoSuchFieldException + { + if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?"); + List<Player> matches = getServer().matchPlayer(args[0]); + if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found."); + return matches.get(0); + } + + public void setStatic() + { + staticThis = this; + } + + @SuppressWarnings("LoggerStringConcat") + public void onEnable() + { + setStatic(); + confList = new ArrayList<IConf>(); + settings = new Settings(this.getDataFolder()); + confList.add(settings); + this.spawn = new Spawn(getServer(), this.getDataFolder()); + confList.add(spawn); + warps = new Warps(getServer(), this.getDataFolder()); + confList.add(warps); + reload(); + this.backup = new Backup(); + + PluginManager pm = getServer().getPluginManager(); + for (Plugin plugin : pm.getPlugins()) { + if (plugin.getDescription().getName().startsWith("Essentials")) { + if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) { + logger.log(Level.WARNING, "Version mismatch! Please update "+plugin.getDescription().getName()+" to the same version."); + } + } + } + Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion()); + if (versionMatch.matches()) { + int versionNumber = Integer.parseInt(versionMatch.group(4)); + if (versionNumber < minBukkitBuildVersion) { + logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials."); + } + } else { + logger.log(Level.INFO, "Bukkit version format changed. Version not checked."); + } + + + playerListener = new EssentialsPlayerListener(this); + pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this); + pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this); + pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Monitor, this); + if (getSettings().getNetherPortalsEnabled()) + pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this); + pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this); + pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this); + + blockListener = new EssentialsBlockListener(this); + pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_INTERACT, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_PLACED, blockListener, Priority.Monitor, this); + + entityListener = new EssentialsEntityListener(this); + pm.registerEvent(Type.ENTITY_DAMAGED, entityListener, Priority.Lowest, this); + pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this); + pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); + + jail = new Jail(this.getDataFolder()); + confList.add(jail); + pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this); + pm.registerEvent(Type.BLOCK_DAMAGED, jail, Priority.High, this); + pm.registerEvent(Type.BLOCK_INTERACT, jail, Priority.High, this); + pm.registerEvent(Type.BLOCK_PLACED, jail, Priority.High, this); + + attachEcoListeners(); + + if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2) + { + getServer().createWorld(settings.getNetherName(), World.Environment.NETHER); + } + + logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS); + } + + public void onDisable() + { + staticThis = null; + } + + public void reload() + { + loadData(); + loadBanList(); + + for (IConf iConf : confList) + { + iConf.reloadConfig(); + } + + try + { + ItemDb.load(getDataFolder(), "items.csv"); + } + catch (Exception ex) + { + logger.log(Level.WARNING, "Could not load items.csv.", ex); + } + } + + public static Map<String, Object> getData(User player) + { + return getData(player.getName()); + } + + public static Map<String, Object> getData(String player) + { + try + { + Map<String, Object> retval; + synchronized (usersLock) + { + retval = (Map<String, Object>)users.get(player.toLowerCase()); + } + return retval == null ? new HashMap<String, Object>() : retval; + } + catch (Throwable ex) + { + return new HashMap<String, Object>(); + } + } + + public static void flushData() + { + Thread run = new Thread(new Runnable() + { + @Override + public void run() + { + try + { + if (!Essentials.getStatic().getDataFolder().exists()) + Essentials.getStatic().getDataFolder().mkdirs(); + File file = new File(Essentials.getStatic().getDataFolder(), "users.yml"); + if (!file.exists()) + file.createNewFile(); + + FileWriter tx = new FileWriter(file); + synchronized (usersLock) + { + tx.write(yaml.dump(users)); + } + tx.flush(); + tx.close(); + } + catch (Throwable ex) + { + Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex); + } + } + }); + run.setDaemon(false); + run.start(); + } + + public static void loadData() + { + try + { + if (!Essentials.getStatic().getDataFolder().exists()) Essentials.getStatic().getDataFolder().mkdirs(); + File file = new File(Essentials.getStatic().getDataFolder(), "users.yml"); + if (!file.exists()) file.createNewFile(); + + FileInputStream rx = new FileInputStream(file); + synchronized (usersLock) + { + users = (Map<String, Object>)yaml.load(new UnicodeReader(rx)); + } + rx.close(); + } + catch (Exception ex) + { + Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex); + synchronized (usersLock) + { + users = new HashMap<String, Object>(); + } + } + finally + { + synchronized (usersLock) + { + if (users == null) users = new HashMap<String, Object>(); + } + } + } + + public static void setData(User player, Map<String, Object> data) + { + setData(player.getName(), data); + } + + public static void setData(String player, Map<String, Object> data) + { + synchronized (usersLock) + { + users.put(player.toLowerCase(), data); + } + } + + public static List<String> readMail(User player) + { + return readMail(player.getName()); + } + + public static List<String> readMail(String player) + { + try + { + Map<String, Object> data = getData(player); + List<String> retval = (List<String>)data.get("mail"); + return retval == null ? new ArrayList<String>() : retval; + } + catch (Throwable ex) + { + return new ArrayList<String>(); + } + } + + public static void clearMail(User player) + { + try + { + Map<String, Object> data = getData(player); + data.put("mail", new ArrayList<String>()); + setData(player, data); + flushData(); + } + catch (Throwable ex) + { + } + } + + public static void sendMail(User from, String to, String message) + throws Exception + { + try + { + Map<String, Object> data = getData(ChatColor.stripColor(to)); + List<String> mail = readMail(to); + mail.add(ChatColor.stripColor(from.getDisplayName()) + ": " + message); + data.put("mail", mail); + setData(to, data); + flushData(); + } + catch (Throwable ex) + { + throw new Exception("An error was encountered while sending the mail.", ex); + } + } + + public String readNickname(User player) + { + try + { + Map<String, Object> data = getData(player); + String nick = (String)data.get("nickname"); + if (nick == null) + return player.getName(); + if (nick.equals(player.getName())) + return player.getName(); + return getSettings().getNicknamePrefix() + nick; + } + catch (Exception ex) + { + return player.getName(); + } + } + + public void saveNickname(User player, String nickname) throws Exception + { + try + { + Map<String, Object> data = getData(player); + data.put("nickname", nickname); + setData(player, data); + flushData(); + } + catch (Throwable ex) + { + throw new Exception("An error was encountered while saving the nickname.", ex); + } + } + + public String[] getMotd(CommandSender sender, String def) + { + return getLines(sender, "motd", def); + } + + public String[] getLines(CommandSender sender, String node, String def) + { + List<String> lines = (List<String>)getConfiguration().getProperty(node); + if (lines == null) return new String[0]; + String[] retval = new String[lines.size()]; + + if (lines == null || lines.isEmpty() || lines.get(0) == null) + { + try + { + lines = new ArrayList<String>(); + // "[]" in YaML indicates empty array, so respect that + if (!getConfiguration().getString(node, def).equals("[]")) + { + lines.add(getConfiguration().getString(node, def)); + retval = new String[lines.size()]; + } + } + catch (Throwable ex2) + { + System.out.println(ChatColor.DARK_RED + "Notice: Your configuration file has a corrupt " + node + " node."); + return new String[0]; + } + } + + // if still empty, call it a day + if (lines == null || lines.isEmpty() || lines.get(0) == null) + return new String[0]; + + for (int i = 0; i < lines.size(); i++) + { + String m = lines.get(i); + if (m == null) + continue; + m = m.replace('&', '§').replace("§§", "&"); + + if (sender instanceof User || sender instanceof Player) + { + User user = User.get(sender); + m = m.replace("{PLAYER}", user.getDisplayName()); + m = m.replace("{IP}", user.getAddress().toString()); + m = m.replace("{BALANCE}", Double.toString(user.getMoney())); + } + + m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length)); + + if (m.matches(".*\\{PLAYERLIST\\}.*")) + { + StringBuilder online = new StringBuilder(); + for (Player p : getServer().getOnlinePlayers()) + { + if (online.length() > 0) + online.append(", "); + online.append(p.getDisplayName()); + } + m = m.replace("{PLAYERLIST}", online.toString()); + } + + if (sender instanceof Player) + { + try + { + Class User = getClassLoader().loadClass("bukkit.Vandolis.User"); + Object vuser = User.getConstructor(User.class).newInstance((Player)sender); + m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString()); + m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString()); + m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString()); + } + catch (Throwable ex) + { + m = m.replace("{RED:BALANCE}", "N/A"); + m = m.replace("{RED:BUYS}", "N/A"); + m = m.replace("{RED:SELLS}", "N/A"); + } + } + + retval[i] = m + " "; + } + return retval; + } + + public static String FormatTime(long Milliseconds) + { // format time into a string showing hours, minutes, or seconds + if (Milliseconds > 3600000) + { + double val = Math.round((double)Milliseconds / 360000D) / 10D; + return val + " hour" + (val > 1 ? "s" : ""); + } + else if (Milliseconds > 60000) + { + double val = Math.round((double)Milliseconds / 6000D) / 10D; + return val + " minute" + (val > 1 ? "s" : ""); + } + else if (Milliseconds <= 1000) + return "1 second"; + else + return (Milliseconds / 1000L) + " seconds"; + } + + @SuppressWarnings("LoggerStringConcat") + public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + if (sender instanceof Player) + logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); + } + + @Override + @SuppressWarnings( + { + "LoggerStringConcat", "CallToThreadDumpStack" + }) + public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + // Allow plugins to override the command via onCommand + for (Plugin p : getServer().getPluginManager().getPlugins()) + { + if (p == this) + continue; + + PluginDescriptionFile desc = p.getDescription(); + if (desc == null) + continue; + + if (desc.getName() == null) + continue; + + if (!(desc.getCommands() instanceof Map)) + continue; + + Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); + if (!cmds.containsKey(command.getName())) + continue; + + PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel); + + if (pcmd == null) + continue; + + return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args); + } + + try + { + previewCommand(sender, command, commandLabel, args); + User user = sender instanceof Player ? User.get(sender) : null; + + // New mail notification + if (user != null && !Essentials.getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail")) + { + List<String> mail = Essentials.readMail(user); + if (!mail.isEmpty()) user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); + } + + // Check for disabled commands + if (Essentials.getSettings().isCommandDisabled(commandLabel)) return true; + + IEssentialsCommand cmd; + try + { + cmd = (IEssentialsCommand)Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command.getName()).newInstance(); + } + catch (Exception ex) + { + sender.sendMessage(ChatColor.RED + "That command is improperly loaded."); + ex.printStackTrace(); + return true; + } + + // Check authorization + if (user != null && !user.isAuthorized(cmd)) + { + logger.warning(user.getName() + " was denied access to command."); + user.sendMessage(ChatColor.RED + "You do not have access to that command."); + return true; + } + + // Run the command + try + { + if (user == null) + cmd.run(getServer(), this, sender, commandLabel, command, args); + else + cmd.run(getServer(), this, user, commandLabel, command, args); + return true; + } + catch (Throwable ex) + { + sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage()); + return true; + } + } + catch (Throwable ex) + { + ex.printStackTrace(); + return true; + } + } + + public void loadBanList() + { + //I don't like this but it needs to be done until CB fixors + File file = new File("banned-players.txt"); + File ipFile = new File("banned-ips.txt"); + try + { + if (!file.exists()) throw new FileNotFoundException("banned-players.txt not found"); + + BufferedReader rx = new BufferedReader(new FileReader(file)); + bans.clear(); + try + { + for (int i = 0; rx.ready(); i++) + { + + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) continue; + bans.add(line); + + } + } + catch (IOException io) + { + logger.log(Level.SEVERE, "Error reading banned-players.txt", io); + } + } + catch (FileNotFoundException ex) + { + logger.log(Level.SEVERE, "Error reading banned-players.txt", ex); + } + + try + { + if (!ipFile.exists()) throw new FileNotFoundException("banned-ips.txt not found"); + + BufferedReader rx = new BufferedReader(new FileReader(ipFile)); + bannedIps.clear(); + try + { + for (int i = 0; rx.ready(); i++) + { + + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) continue; + bannedIps.add(line); + + } + } + catch (IOException io) + { + logger.log(Level.SEVERE, "Error reading banned-ips.txt", io); + } + } + catch (FileNotFoundException ex) + { + logger.log(Level.SEVERE, "Error reading banned-ips.txt", ex); + } + } + + private void attachEcoListeners() + { + PluginManager pm = getServer().getPluginManager(); + EssentialsEcoBlockListener blockListener = new EssentialsEcoBlockListener(); + pm.registerEvent(Type.BLOCK_INTERACT, blockListener, Priority.Lowest, this); + pm.registerEvent(Type.BLOCK_RIGHTCLICKED, blockListener, Priority.High, this); + pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.High, this); + pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Monitor, this); + } + + public CraftScheduler getScheduler() + { + return (CraftScheduler)this.getServer().getScheduler(); + } + + public static Jail getJail() + { + return getStatic().jail; + } + + public static Warps getWarps() + { + return getStatic().warps; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java new file mode 100644 index 000000000..5873b3c1e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java @@ -0,0 +1,307 @@ +package com.earth2me.essentials; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.server.InventoryPlayer; +import org.bukkit.*; +import org.bukkit.block.*; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.block.*; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsBlockListener extends BlockListener +{ + private final Essentials parent; + private final static ArrayList<Material> protectedBlocks = new ArrayList<Material>(4); + + static + { + protectedBlocks.add(Material.CHEST); + protectedBlocks.add(Material.BURNING_FURNACE); + protectedBlocks.add(Material.FURNACE); + protectedBlocks.add(Material.DISPENSER); + } + + public EssentialsBlockListener(Essentials parent) + { + this.parent = parent; + } + + @Override + public void onBlockBreak(BlockBreakEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override")) + { + if (isBlockProtected(event.getBlock(), user)) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to destroy that chest."); + return; + } + } + + if (checkProtectionSign(event.getBlock(), user) == NOT_ALLOWED) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to destroy that sign."); + } + } + + @Override + public void onBlockInteract(BlockInteractEvent event) + { + if (event.isCancelled()) return; + if (!(event.getEntity() instanceof Player)) return; + + User user = User.get((Player)event.getEntity()); + + if (!Essentials.getSettings().areSignsDisabled() && protectedBlocks.contains(event.getBlock().getType())) + { + if (!user.isAuthorized("essentials.signs.protection.override")) + { + if (isBlockProtected(event.getBlock(), user)) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to access that chest."); + return; + } + } + } + + if (Essentials.getSettings().getBedSetsHome() && event.getBlock().getType() == Material.BED_BLOCK) + { + try + { + user.setHome(); + user.sendMessage("§7Your home is now set to this bed."); + } + catch (Throwable ex) + { + } + } + } + + @Override + public void onSignChange(SignChangeEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + + try + { + if (event.getLine(0).equalsIgnoreCase("[Protection]")) + { + Block block = event.getBlock(); + if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user)) + event.setLine(0, "§1[Protection]"); + else + event.setLine(0, "§4[Protection]"); + event.setLine(3, user.getName()); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Disposal]")) + { + if (user.isAuthorized("essentials.signs.disposal.create")) + event.setLine(0, "§1[Disposal]"); + else + event.setLine(0, "§4[Disposal]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Heal]")) + { + if (user.isAuthorized("essentials.signs.heal.create")) + event.setLine(0, "§1[Heal]"); + else + event.setLine(0, "§4[Heal]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Free]")) + { + event.setLine(0, "§4[Free]"); + ItemDb.get(event.getLine(1)); + if (user.isAuthorized("essentials.signs.free.create")) + event.setLine(0, "§1[Free]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Mail]")) + { + if (user.isAuthorized("essentials.signs.mail.create")) + + event.setLine(0, "§1[Mail]"); + else + event.setLine(0, "§4[Mail]"); + return; + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + } + + @Override + public void onBlockRightClick(BlockRightClickEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getBlock()); + + try + { + if (sign.getLine(0).equals("§1[Free]") && user.isAuthorized("essentials.signs.free.use")) + { + ItemStack item = ItemDb.get(sign.getLine(1)); + CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle())); + inv.clear(); + item.setAmount(9 * 4 * 64); + inv.addItem(item); + user.showInventory(inv); + return; + } + if (sign.getLine(0).equals("§1[Disposal]") && user.isAuthorized("essentials.signs.disposal.use")) + { + CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle())); + inv.clear(); + user.showInventory(inv); + return; + } + if (sign.getLine(0).equals("§1[Heal]") && user.isAuthorized("essentials.signs.heal.use")) + { + user.setHealth(20); + user.sendMessage("§7You have been healed."); + return; + } + if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail")) + { + List<String> mail = Essentials.readMail(user); + if (mail.isEmpty()) + { + user.sendMessage("§cYou do not have any mail!"); + return; + } + for (String s : mail) user.sendMessage(s); + user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); + return; + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + } + + @Override + public void onBlockPlace(BlockPlaceEvent event) { + Block signBlock = event.getBlockAgainst(); + if (signBlock.getType() == Material.WALL_SIGN || signBlock.getType() == Material.SIGN_POST) { + Sign sign = new CraftSign(signBlock); + if (sign.getLine(0).matches("§1\\[[a-zA-Z]+\\]")) { + event.setCancelled(true); + return; + } + } + } + + + + public boolean hasAdjacentChest(Block block) + { + Block[] faces = getAdjacentBlocks(block); + for (Block b : faces) + { + if (protectedBlocks.contains(b.getType())) + { + return true; + } + } + return false; + } + private static final int NOT_ALLOWED = 0; + private static final int ALLOWED = 1; + private static final int NOSIGN = 2; + + private int checkProtectionSign(Block block, User user) + { + if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) + { + Sign sign = new CraftSign(block); + if (sign.getLine(0).equalsIgnoreCase("§1[Protection]") && !user.isAuthorized("essentials.signs.protection.override")) + { + if (sign.getLine(1).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + if (sign.getLine(2).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + if (sign.getLine(3).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + return NOT_ALLOWED; + } + } + return NOSIGN; + } + + private Block[] getAdjacentBlocks(Block block) + { + return new Block[] + { + block.getFace(BlockFace.NORTH), + block.getFace(BlockFace.SOUTH), + block.getFace(BlockFace.EAST), + block.getFace(BlockFace.WEST), + block.getFace(BlockFace.DOWN), + block.getFace(BlockFace.UP) + }; + } + + private boolean isBlockProtected(Block block, User user) + { + Block[] faces = getAdjacentBlocks(block); + boolean protect = false; + for (Block b : faces) + { + int check = checkProtectionSign(b, user); + if (check == NOT_ALLOWED) + { + protect = true; + } + if (check == ALLOWED) + { + return false; + } + + if (protectedBlocks.contains(b.getType())) + { + Block[] faceChest = getAdjacentBlocks(b); + + for (Block a : faceChest) + { + check = checkProtectionSign(a, user); + if (check == NOT_ALLOWED) + { + protect = true; + } + if (check == ALLOWED) + { + return false; + } + } + } + } + return protect; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java new file mode 100644 index 000000000..616f39a6c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsConf.java @@ -0,0 +1,120 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.util.config.Configuration; + + +public class EssentialsConf extends Configuration +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private File configFile; + private String templateName = null; + private Class<?> resourceClass = EssentialsConf.class; + + public EssentialsConf(File configFile) + { + super(configFile); + this.configFile = configFile; + if (this.root == null) { + this.root = new HashMap<String, Object>(); + } + } + + @Override + public void load() + { + configFile = configFile.getAbsoluteFile(); + if (!configFile.getParentFile().exists()) + { + configFile.getParentFile().mkdirs(); + } + if (!configFile.exists()) + { + if (templateName != null) + { + logger.log(Level.INFO, "Creating config from template: " + configFile.toString()); + createFromTemplate(); + } + else + { + try + { + logger.log(Level.INFO, "Creating empty config: " + configFile.toString()); + configFile.createNewFile(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to create config " + configFile.toString(), ex); + } + } + } + super.load(); + if (this.root == null) { + this.root = new HashMap<String, Object>(); + } + } + + private void createFromTemplate() + { + OutputStream ostr = null; + try + { + InputStream istr = resourceClass.getResourceAsStream(templateName); + if (istr == null) + { + logger.log(Level.SEVERE, "Could not find template " + templateName); + return; + } + ostr = new FileOutputStream(configFile); + byte[] buffer = new byte[1024]; + int length = 0; + length = istr.read(buffer); + while (length > 0) + { + ostr.write(buffer, 0, length); + length = istr.read(buffer); + } + ostr.close(); + istr.close(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to write config " + configFile.toString(), ex); + return; + } + finally + { + try + { + ostr.close(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to close config " + configFile.toString(), ex); + return; + } + } + } + + public void setTemplateName(String templateName) + { + this.templateName = templateName; + } + + public File getFile() + { + return configFile; + } + + public void setTemplateName(String templateName, Class<?> resClass) { + this.templateName = templateName; + this.resourceClass = resClass; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java new file mode 100644 index 000000000..907b836e2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java @@ -0,0 +1,289 @@ +package com.earth2me.essentials; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import org.bukkit.Material; +import org.bukkit.block.Sign; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockRightClickEvent; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsEcoBlockListener extends BlockListener +{ + @Override + public void onBlockBreak(BlockBreakEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getBlock()); + + if (sign.getLine(0).equals("§1[Trade]")) + { + if (!sign.getLine(3).substring(2).equals(user.getName())) { + if (!user.isOp()) { + event.setCancelled(true); + } + return; + } + try + { + String[] l1 = sign.getLines()[1].split("[ :-]+"); + String[] l2 = sign.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r1 = Integer.parseInt(l1[m1 ? 1 : 2]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); + + ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1); + ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], r2); + + if (m1) + user.giveMoney(r1); + else if (i1 != null) + user.getWorld().dropItem(user.getLocation(), i1); + + if (m2) + user.giveMoney(r2); + else if (i2 != null) + user.getWorld().dropItem(user.getLocation(), i2); + + sign.setType(Material.AIR); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + } + + @Override + public void onBlockRightClick(BlockRightClickEvent event) + { + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getBlock()); + + if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use")) + { + try + { + int amount = Integer.parseInt(sign.getLine(1)); + ItemStack item = ItemDb.get(sign.getLine(2), amount); + int cost = Integer.parseInt(sign.getLine(3).substring(1)); + if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds."); + user.takeMoney(cost); + user.getInventory().addItem(item); + user.updateInventory(); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use")) + { + try + { + int amount = Integer.parseInt(sign.getLine(1)); + ItemStack item = ItemDb.get(sign.getLine(2), amount); + int cost = Integer.parseInt(sign.getLine(3).substring(1)); + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell."); + user.giveMoney(cost); + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, item); + user.updateInventory(); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use")) + { + try + { + String[] l1 = sign.getLines()[1].split("[ :-]+"); + String[] l2 = sign.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r1 = Integer.parseInt(l1[m1 ? 1 : 2]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + r1 = r1 - r1 % q1; + r2 = r2 - r2 % q2; + if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); + + ItemStack i1 = m1 || r1 <= 0? null : ItemDb.get(l1[1], r1); + ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1); + ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2); + + if (user.getName().equals(sign.getLines()[3].substring(2))) + { + if (m1) + { + user.giveMoney(r1); + } + else if (i1 != null) + { + user.getInventory().addItem(i1); + user.updateInventory(); + } + r1 = 0; + sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1); + } + else + { + if (m1) + { + if (user.getMoney() < q1) + throw new Exception("You do not have sufficient funds."); + } + else + { + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, qi1)) + throw new Exception("You do not have " + q1 + "x " + l1[1] + "."); + } + + if (r2 < q2) throw new Exception("The trade sign does not have enough supply left."); + + if (m1) + user.takeMoney(q1); + else + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, qi1); + + if (m2) + user.giveMoney(q2); + else + user.getInventory().addItem(qi2); + + user.updateInventory(); + + r1 += q1; + r2 -= q2; + + sign.setLine(0, "§1[Trade]"); + sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1); + sign.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2); + + user.sendMessage("§7Trade completed."); + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + } + + @Override + public void onSignChange(SignChangeEvent event) + { + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + + if (event.getLine(0).equalsIgnoreCase("[Buy]") && user.isAuthorized("essentials.signs.buy.create")) + { + try + { + event.setLine(0, "§1[Buy]"); + event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); + ItemDb.get(event.getLine(2)); + event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Buy]"); + event.setLine(1, "#"); + event.setLine(2, "Item"); + event.setLine(3, "$Price"); + } + return; + } + + if (event.getLine(0).equalsIgnoreCase("[Sell]") && user.isAuthorized("essentials.signs.sell.create")) + { + try + { + event.setLine(0, "§1[Sell]"); + event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); + ItemDb.get(event.getLine(2)); + event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Sell]"); + event.setLine(1, "#"); + event.setLine(2, "Item"); + event.setLine(3, "$Price"); + } + return; + } + + if (event.getLine(0).equalsIgnoreCase("[Trade]") && user.isAuthorized("essentials.signs.trade.create")) + { + try + { + String[] l1 = event.getLines()[1].split("[ :-]+"); + String[] l2 = event.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + r2 = r2 - r2 % q2; + if (q1 < 1 || q2 < 1 || r2 < 1) throw new Exception("Quantities must be greater than 0."); + if (!m1) ItemDb.get(l1[1]); + + if (m2) + { + if (user.getMoney() < r2) throw new Exception("You do not have sufficient funds."); + user.takeMoney(r2); + user.sendMessage("r2: " + r2 + " q2: " + q2); + } + else + { + ItemStack i2 = ItemDb.get(l2[1], r2); + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, i2)) throw new Exception("You do not have " + r2 + "x " + l2[1] + "."); + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, i2); + user.updateInventory(); + } + + event.setLine(0, "§1[Trade]"); + event.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":0"); + event.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2); + event.setLine(3, "§8" + user.getName()); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Trade]"); + event.setLine(1, "# ItemOr$"); + event.setLine(2, "# ItemOr$:#"); + event.setLine(3, "§8" + user.getName()); + } + return; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java new file mode 100644 index 000000000..15355021a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java @@ -0,0 +1,65 @@ +package com.earth2me.essentials; + +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.EntityDamageByBlockEvent; +import org.bukkit.event.entity.EntityDamageByProjectileEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityListener; + + +public class EssentialsEntityListener extends EntityListener +{ + private final Server server; + private final Essentials parent; + + public EssentialsEntityListener(Essentials parent) + { + this.parent = parent; + this.server = parent.getServer(); + } + + @Override + public void onEntityDamage(EntityDamageEvent event) + { + if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent) + { + + if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) + { + CraftPlayer player = (CraftPlayer)event.getEntity(); + player.getHandle().fireTicks = 0; + player.setRemainingAir(player.getMaximumAir()); + event.setCancelled(true); + } + } + } + + + @Override + public void onEntityCombust(EntityCombustEvent event) + { + if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @Override + public void onEntityDeath(EntityDeathEvent event) + { + if (event.getEntity() instanceof Player) + { + User user = User.get(event.getEntity()); + if(user.isAuthorized("essentials.back.ondeath")) + { + user.lastLocation = user.getLocation(); + user.sendMessage("§7Use the /back command to return to your death point"); + } + } + } + +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java new file mode 100644 index 000000000..e4f743ddd --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java @@ -0,0 +1,226 @@ +package com.earth2me.essentials; + +import java.util.List; +import java.util.logging.Logger; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerLoginEvent.Result; + + +public class EssentialsPlayerListener extends PlayerListener +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private final Server server; + private final Essentials parent; + + public EssentialsPlayerListener(Essentials parent) + { + this.parent = parent; + this.server = parent.getServer(); + } + + @Override + public void onPlayerRespawn(PlayerRespawnEvent event) + { + User user = User.get(event.getPlayer()); + user.setDisplayName(user.getNick()); + updateCompass(user); + } + + @Override + public void onPlayerChat(PlayerChatEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isMuted()) + { + event.setCancelled(true); + logger.info(user.getName() + " tried to speak, but is muted."); + } + } + + @Override + public void onPlayerMove(PlayerMoveEvent event) + { + if (event.isCancelled()) return; + final User user = User.get(event.getPlayer()); + + if (!Essentials.getSettings().getNetherPortalsEnabled()) return; + + final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ()); + List<World> worlds = server.getWorlds(); + + if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal")) + { + if (user.getJustPortaled()) return; + + Location loc = event.getTo(); + final World world = worlds.get(user.getWorld() == worlds.get(0) ? 1 : 0); + + double factor; + if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) + factor = 16.0; + else if (user.getWorld().getEnvironment() != world.getEnvironment()) + factor = 1.0 / 16.0; + else + factor = 1.0; + + int x = loc.getBlockX(); + int y = loc.getBlockY(); + int z = loc.getBlockZ(); + + if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL) + z--; + if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL) + x--; + + x = (int)(x * factor); + z = (int)(z * factor); + loc = new Location(world, x + .5, y, z + .5); + + Block dest = world.getBlockAt(x, y, z); + NetherPortal portal = NetherPortal.findPortal(dest); + if (portal == null) + { + if (world.getEnvironment() == World.Environment.NETHER || Essentials.getSettings().getGenerateExitPortals()) + { + portal = NetherPortal.createPortal(dest); + logger.info(event.getPlayer().getName() + " used a portal and generated an exit portal."); + user.sendMessage("§7Generating an exit portal."); + loc = portal.getSpawn(); + } + } + else + { + logger.info(event.getPlayer().getName() + " used a portal and used an existing exit portal."); + user.sendMessage("§7Teleporting via portal to an existing portal."); + loc = portal.getSpawn(); + } + + event.setFrom(loc); + event.setTo(loc); + try { + user.teleportToNow(loc); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + } + user.setJustPortaled(true); + user.sendMessage("§7Teleporting via portal."); + + event.setCancelled(true); + return; + } + + user.setJustPortaled(false); + } + + @Override + public void onPlayerQuit(PlayerEvent event) + { + if (!Essentials.getSettings().getReclaimSetting()) + { + return; + } + User.get(event.getPlayer()).dispose(); + Thread thread = new Thread(new Runnable() + { + @SuppressWarnings("LoggerStringConcat") + public void run() + { + try + { + Thread.sleep(1000); + Runtime rt = Runtime.getRuntime(); + double mem = rt.freeMemory(); + rt.runFinalization(); + rt.gc(); + mem = rt.freeMemory() - mem; + mem /= 1024 * 1024; + logger.info("Freed " + mem + " MB."); + } + catch (InterruptedException ex) + { + return; + } + } + }); + thread.setPriority(Thread.MIN_PRIORITY); + thread.start(); + } + + @Override + public void onPlayerJoin(PlayerEvent event) + { + Essentials.getStatic().backup.onPlayerJoin(); + User user = User.get(event.getPlayer()); + + //we do not know the ip address on playerlogin so we need to do this here. + if (user.isIpBanned()) + { + user.kickPlayer("The Ban Hammer has spoken!"); + return; + } + + user.setDisplayName(user.getNick()); + + if (!Essentials.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) + { + for (String m : parent.getMotd(user, null)) + { + if (m == null) continue; + user.sendMessage(m); + } + } + + if (!Essentials.getSettings().isCommandDisabled("mail")) + { + List<String> mail = Essentials.readMail(user); + if (mail.isEmpty()) user.sendMessage("§7You have no new mail."); + else user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); + } + } + + @Override + public void onPlayerLogin(PlayerLoginEvent event) + { + User user = User.get(event.getPlayer()); + if (event.getResult() != Result.ALLOWED) + return; + + if (user.isBanned()) + { + event.disallow(Result.KICK_BANNED, "The Ban Hammer has spoken!"); + return; + } + + if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isOp()) + { + event.disallow(Result.KICK_FULL, "Server is full"); + return; + } + + updateCompass(user); + } + + private void updateCompass(User user) + { + try + { + if (server.getPluginManager().isPluginEnabled("EssentialsHome")) + user.setCompassTarget(user.getHome()); + } + catch (Throwable ex) + { + } + } + + @Override + public void onPlayerTeleport(PlayerMoveEvent event) + { + User user = User.get(event.getPlayer()); + if (user.currentJail == null || user.currentJail.isEmpty()) + return; + event.setCancelled(true); + user.sendMessage(ChatColor.RED + "You do the crime, you do the time."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/IConf.java b/Essentials/src/com/earth2me/essentials/IConf.java new file mode 100644 index 000000000..a523f8638 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/IConf.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials; + +public interface IConf { + public void reloadConfig(); +} diff --git a/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java new file mode 100644 index 000000000..aabd7b02b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java @@ -0,0 +1,136 @@ +package com.earth2me.essentials; + +import java.util.HashMap; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.inventory.ItemStack; + +/* + * This class can be removed when + * https://github.com/Bukkit/CraftBukkit/pull/193 + * is accepted to CraftBukkit + */ +public class InventoryWorkaround { + + public static int first(CraftInventory ci, ItemStack item, boolean forceDurability, boolean forceAmount) { + return next(ci, item, 0, forceDurability, forceAmount); + } + + public static int next(CraftInventory ci, ItemStack item, int start, boolean forceDurability, boolean forceAmount) { + CraftItemStack[] inventory = ci.getContents(); + for (int i = start; i < inventory.length; i++) { + CraftItemStack cItem = inventory[i]; + if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability())) { + return i; + } + } + return -1; + } + + public static HashMap<Integer, ItemStack> removeItem(CraftInventory ci, boolean forceDurability, ItemStack... items) { + HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>(); + + // TODO: optimization + + for (int i = 0; i < items.length; i++) { + ItemStack item = items[i]; + if (item == null) { + continue; + } + int toDelete = item.getAmount(); + + while (true) { + + // Bail when done + if (toDelete <= 0) { + break; + } + + // get first Item, ignore the amount + int first = first(ci, item, forceDurability, false); + + // Drat! we don't have this type in the inventory + if (first == -1) { + item.setAmount(toDelete); + leftover.put(i, item); + break; + } else { + CraftItemStack itemStack = ci.getItem(first); + int amount = itemStack.getAmount(); + + if (amount <= toDelete) { + toDelete -= amount; + // clear the slot, all used up + ci.clear(first); + } else { + // split the stack and store + itemStack.setAmount(amount - toDelete); + ci.setItem(first, itemStack); + toDelete = 0; + } + } + } + } + return leftover; + } + + public static boolean containsItem(CraftInventory ci, boolean forceDurability, ItemStack... items) { + HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>(); + + // TODO: optimization + + // combine items + + ItemStack[] combined = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) { + if (items[i] == null) { + continue; + } + for (int j = 0; j < combined.length; j++) { + if (combined[j] == null) { + combined[j] = new ItemStack(items[i].getType(), items[i].getAmount(), items[i].getDurability()); + break; + } + if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability())) { + combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); + break; + } + } + } + + for (int i = 0; i < combined.length; i++) { + ItemStack item = combined[i]; + if (item == null) { + continue; + } + int mustHave = item.getAmount(); + int position = 0; + + while (true) { + // Bail when done + if (mustHave <= 0) { + break; + } + + int slot = next(ci, item, position, forceDurability, false); + + // Drat! we don't have this type in the inventory + if (slot == -1) { + leftover.put(i, item); + break; + } else { + CraftItemStack itemStack = ci.getItem(slot); + int amount = itemStack.getAmount(); + + if (amount <= mustHave) { + mustHave -= amount; + } else { + mustHave = 0; + } + position = slot + 1; + } + } + } + return leftover.isEmpty(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/ItemDb.java b/Essentials/src/com/earth2me/essentials/ItemDb.java new file mode 100644 index 000000000..8c3c47bab --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ItemDb.java @@ -0,0 +1,110 @@ +package com.earth2me.essentials; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.logging.Logger; +import org.bukkit.inventory.ItemStack; + + +public class ItemDb +{ + private final static Logger logger = Logger.getLogger("Minecraft"); + private static Map<String, Integer> items = new HashMap<String, Integer>(); + private static Map<String, Short> durabilities = new HashMap<String, Short>(); + + @SuppressWarnings("LoggerStringConcat") + public static void load(File folder, String fname) throws IOException + { + folder.mkdirs(); + File file = new File(folder, fname); + + if (!file.exists()) + { + file.createNewFile(); + InputStream res = ItemDb.class.getResourceAsStream("/items.csv"); + FileWriter tx = new FileWriter(file); + try + { + for (int i = 0; (i = res.read()) > 0;) tx.write(i); + } + finally + { + try + { + tx.flush(); + tx.close(); + res.close(); + } + catch (Exception ex) + { + } + } + } + + BufferedReader rx = new BufferedReader(new FileReader(file)); + try + { + items.clear(); + + for (int i = 0; rx.ready(); i++) + { + try + { + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) + continue; + + String[] parts = line.split("[^a-z0-9]"); + if (parts.length < 2) + continue; + + int numeric = Integer.parseInt(parts[1]); + + durabilities.put(parts[0], parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0); + items.put(parts[0], numeric); + } + catch (Exception ex) + { + logger.warning("Error parsing " + fname + " on line " + i); + } + } + } + finally + { + rx.close(); + } + } + + public static ItemStack get(String id, int quantity) throws Exception { + ItemStack retval = get(id); + retval.setAmount(quantity); + return retval; + } + + public static ItemStack get(String id) throws Exception + { + ItemStack retval = new ItemStack(getUnsafe(id)); + retval.setAmount(Essentials.getSettings().getDefaultStackSize()); + retval.setDurability(durabilities.containsKey(id) ? durabilities.get(id) : 0); + if (items.containsValue(retval.getTypeId()) || true) return retval; + throw new Exception("Unknown item numeric: " + retval); + } + + private static int getUnsafe(String id) throws Exception + { + try + { + return Integer.parseInt(id); + } + catch (NumberFormatException ex) + { + if (items.containsKey(id)) return items.get(id); + throw new Exception("Unknown item name: " + id); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/Jail.java b/Essentials/src/com/earth2me/essentials/Jail.java new file mode 100644 index 000000000..0ed2774e2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Jail.java @@ -0,0 +1,115 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockInteractEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockPlaceEvent; + +public class Jail extends BlockListener implements IConf { + private static final Logger logger = Logger.getLogger("Minecraft"); + private EssentialsConf config; + + public Jail(File dataFolder) { + config = new EssentialsConf(new File(dataFolder, "jail.yml")); + config.load(); + } + + public void setJail(Location loc, String jailName) throws Exception { + Map<String, Object> map = new HashMap<String, Object>(); + map.put("world", loc.getWorld().getName()); + map.put("x", loc.getX()); + map.put("y", loc.getY()); + map.put("z", loc.getZ()); + map.put("yaw", loc.getYaw()); + map.put("pitch", loc.getPitch()); + config.setProperty(jailName.toLowerCase(), map); + config.save(); + } + + public Location getJail(String jailName) throws Exception { + if (config.getProperty(jailName.toLowerCase()) == null) { + throw new Exception("That jail does not exist"); + } + + World jWorld = null; + String world = config.getString(jailName + ".world", ""); // wh.spawnX + double x = config.getDouble(jailName + ".x", 0); // wh.spawnX + double y = config.getDouble(jailName + ".y", 0); // wh.spawnY + double z = config.getDouble(jailName + ".z", 0); // wh.spawnZ + float yaw = (float) config.getDouble(jailName + ".yaw", 0); + float pitch = (float) config.getDouble(jailName + ".pitch", 0); + for (World w : Essentials.getStatic().getServer().getWorlds()) { + if (w.getName().equalsIgnoreCase(world)) { + jWorld = w; + break; + } + + } + return new Location(jWorld, x, y, z, yaw, pitch); + } + + public void sendToJail(User user, String jail) throws Exception { + user.teleportTo(getJail(jail)); + user.currentJail = jail; + } + + public void delJail(String jail) throws Exception { + config.removeProperty(jail.toLowerCase()); + config.save(); + } + + public List<String> getJails() throws Exception { + return config.getKeys(null); + } + + public void reloadConfig() { + config.load(); + } + + @Override + public void onBlockBreak(BlockBreakEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @Override + public void onBlockInteract(BlockInteractEvent event) + { + if (!event.isPlayer()) { + return; + } + User user = User.get((Player)event.getEntity()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @Override + public void onBlockPlace(BlockPlaceEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @Override + public void onBlockDamage(BlockDamageEvent event) { + User user = User.get(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/Mob.java b/Essentials/src/com/earth2me/essentials/Mob.java new file mode 100644 index 000000000..3c0d9bd1e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Mob.java @@ -0,0 +1,122 @@ +package com.earth2me.essentials; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.logging.Logger; +import net.minecraft.server.Entity; +import net.minecraft.server.WorldServer; +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Player; + + +public enum Mob +{ + CHICKEN("Chicken", Enemies.FRIENDLY), + COW("Cow", Enemies.FRIENDLY), + CREEPER("Creeper", Enemies.ENEMY), + GHAST("Ghast", Enemies.ENEMY), + GIANT("Giant", "GiantZombie", Enemies.ENEMY), + PIG("Pig", Enemies.FRIENDLY), + PIGZOMB("PigZombie", Enemies.NEUTRAL), + SHEEP("Sheep", Enemies.FRIENDLY, ""), + SKELETON("Skeleton", Enemies.ENEMY), + SLIME("Slime", Enemies.ENEMY), + SPIDER("Spider", Enemies.ENEMY), + SQUID("Squid", Enemies.FRIENDLY), + ZOMBIE("Zombie", Enemies.ENEMY), + MONSTER("Monster", Enemies.ENEMY); + + public static final Logger logger = Logger.getLogger("Minecraft"); + + private Mob(String n, Enemies en, String s) + { + this.s = s; + this.name = n; + this.craftClass = n; + this.entityClass = n; + this.type = en; + } + + private Mob(String n, Enemies en) + { + this.name = n; + this.craftClass = n; + this.entityClass = n; + this.type = en; + } + + private Mob(String n, String ec, Enemies en) + { + this.name = n; + this.craftClass = n; + this.entityClass = ec; + this.type = en; + } + + private Mob(String n, String ec, String cc, Enemies en) + { + this.name = n; + this.entityClass = ec; + this.craftClass = cc; + this.type = en; + } + public String s = "s"; + public String name; + public Enemies type; + private String entityClass; + private String craftClass; + private static final HashMap<String, Mob> hashMap = new HashMap<String, Mob>(); + + static + { + for (Mob mob : Mob.values()) + { + hashMap.put(mob.name, mob); + } + } + + @SuppressWarnings({"unchecked", "CallToThreadDumpStack"}) + public CraftEntity spawn(Player player, Server server) throws MobException + { + try + { + WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)player.getWorld()).getHandle(); + Constructor<CraftEntity> craft = (Constructor<CraftEntity>)ClassLoader.getSystemClassLoader().loadClass("org.bukkit.craftbukkit.entity.Craft" + craftClass).getConstructors()[0]; + Constructor<Entity> entity = (Constructor<Entity>)ClassLoader.getSystemClassLoader().loadClass("net.minecraft.server.Entity" + entityClass).getConstructors()[0]; + return craft.newInstance((CraftServer)server, entity.newInstance(world)); + } + catch (Exception ex) + { + logger.warning("Unable to spawn mob."); + ex.printStackTrace(); + throw new MobException(); + } + } + + + public enum Enemies + { + FRIENDLY("friendly"), + NEUTRAL("neutral"), + ENEMY("enemy"); + + private Enemies(String t) + { + this.type = t; + } + protected String type; + } + + + public class MobException extends Exception + { + private static final long serialVersionUID = 1L; + } + + public static Mob fromName(String n) + { + return hashMap.get(n); + } +} diff --git a/Essentials/src/com/earth2me/essentials/NetherPortal.java b/Essentials/src/com/earth2me/essentials/NetherPortal.java new file mode 100644 index 000000000..25ebe5e23 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/NetherPortal.java @@ -0,0 +1,167 @@ +/** + * @author SpaceManiac + * @licent MIT + * @origin https://github.com/SpaceManiac/Nether/blob/master/org/innectis/Nether/NetherPortal.java + */ +package com.earth2me.essentials; + +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.Location; +import org.bukkit.Material; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NetherPortal +{ + private Block block; + + public NetherPortal(Block b) + { + block = b; + } + + public Block getBlock() + { + return block; + } + + public void setBlock(Block b) + { + block = b; + } + + // Return a random spawnable location + public Location getSpawn() + { + if (block.getWorld().getBlockAt(block.getX() + 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL) + || block.getWorld().getBlockAt(block.getX() - 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL)) + { + // portal is in X direction + return new Location(block.getWorld(), block.getX() + 1, + block.getY(), block.getZ() + 1.5 - 2 * Math.round(Math.random())); + } + else + { + // portal is in Z direction + return new Location(block.getWorld(), block.getX() + 1.5 - 2 * Math.round(Math.random()), + block.getY(), block.getZ() + 1); + } + } + + // ============================== + // Find a nearby portal within 16 blocks of the given block + // Not guaranteed to be the nearest + public static NetherPortal findPortal(Block dest) + { + World world = dest.getWorld(); + + // Get list of columns in a circle around the block + ArrayList<Block> columns = new ArrayList<Block>(); + for (int x = dest.getX() - 16; x <= dest.getX() + 16; ++x) + { + for (int z = dest.getZ() - 16; z <= dest.getZ() + 16; ++z) + { + int dx = dest.getX() - x, dz = dest.getZ() - z; + if (dx * dx + dz * dz <= 256) + { + columns.add(world.getBlockAt(x, 0, z)); + } + } + } + + // For each column try to find a portal block + for (Block col : columns) + { + for (int y = 127; y >= 0; --y) + { + Block b = world.getBlockAt(col.getX(), y, col.getZ()); + if (b.getType().equals(Material.PORTAL) && Math.abs(dest.getY() - y) <= 16) + { + // Huzzah! + return new NetherPortal(b); + } + } + } + + // Nope! + return null; + } + + // Create a new portal at the specified block, fudging position if needed + // Will occasionally end up making portals in bad places, but let's hope not + public static NetherPortal createPortal(Block dest) + { + World world = dest.getWorld(); + + // Try not to spawn within water or lava + Material m = dest.getType(); + while (((m.equals(Material.LAVA) || m.equals(Material.WATER) || m.equals(Material.STATIONARY_LAVA) + || m.equals(Material.STATIONARY_WATER) || m.equals(Material.SAND) || m.equals(Material.GRAVEL))) && + dest.getY() < 120) + { + dest = world.getBlockAt(dest.getX(), dest.getY() + 4, dest.getZ()); + m = dest.getType(); + } + + // Not too high or too low overall + if (dest.getY() > 120) + { + dest = world.getBlockAt(dest.getX(), 120, dest.getZ()); + } + else if (dest.getY() < 8) + { + dest = world.getBlockAt(dest.getX(), 8, dest.getZ()); + } + + // Create the physical portal + // For now, don't worry about direction + + int x = dest.getX(), y = dest.getY(), z = dest.getZ(); + Logger.getLogger("Minecraft").log(Level.INFO, "Creating portal at "+x+","+y+","+z+"."); + + // Clear area around portal + ArrayList<Block> columns = new ArrayList<Block>(); + for (int x2 = x - 4; x2 <= x + 4; ++x2) + { + for (int z2 = z - 4; z2 <= z + 4; ++z2) + { + double dx = x + 0.5f - x2, dz = z - z2; + if (dx * dx + dz * dz <= 13) + { + columns.add(world.getBlockAt(x2, 0, z2)); + } + } + } + + // Clear area around portal + for (Block col : columns) + { + // Stone platform + world.getBlockAt(col.getX(), y - 1, col.getZ()).setType(Material.STONE); + for (int yd = 0; yd < 4; ++yd) + { + world.getBlockAt(col.getX(), y + yd, col.getZ()).setType(Material.AIR); + } + } + + // Build obsidian frame + for (int xd = -1; xd < 3; ++xd) + { + for (int yd = -1; yd < 4; ++yd) + { + if (xd == -1 || yd == -1 || xd == 2 || yd == 3) + { + world.getBlockAt(x + xd, y + yd, z).setType(Material.OBSIDIAN); + } + } + } + + // Set it alight! + dest.setType(Material.FIRE); + + return new NetherPortal(dest); + } +} diff --git a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java new file mode 100644 index 000000000..f1bac2ae4 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java @@ -0,0 +1,286 @@ +package com.earth2me.essentials; + +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Egg; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Snowball; +import org.bukkit.entity.Vehicle; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.util.Vector; + + +public class OfflinePlayer implements Player +{ + private final String name; + private Location location = new Location(null, 0, 0, 0, 0, 0); + + public OfflinePlayer(String name) + { + this.name = name; + } + + public boolean isOnline() + { + return false; + } + + public boolean isOp() + { + return false; + } + + public void sendMessage(String string) + { + } + + public String getDisplayName() + { + return name; + } + + public void setDisplayName(String string) + { + } + + public void setCompassTarget(Location lctn) + { + } + + public InetSocketAddress getAddress() + { + return null; + } + + public void kickPlayer(String string) + { + } + + public String getName() + { + return name; + } + + public PlayerInventory getInventory() + { + return null; + } + + public ItemStack getItemInHand() + { + return null; + } + + public void setItemInHand(ItemStack is) + { + } + + public int getHealth() + { + return 0; + } + + public void setHealth(int i) + { + } + + public Egg throwEgg() + { + return null; + } + + public Snowball throwSnowball() + { + return null; + } + + public Arrow shootArrow() + { + return null; + } + + public boolean isInsideVehicle() + { + return false; + } + + public boolean leaveVehicle() + { + return false; + } + + public Vehicle getVehicle() + { + return null; + } + + public Location getLocation() + { + return location; + } + + public World getWorld() + { + return null; + } + + public void teleportTo(Location lctn) + { + } + + public void teleportTo(Entity entity) + { + } + + public int getEntityId() + { + return -1; + } + + public boolean performCommand(String string) + { + return false; + } + + public boolean isPlayer() + { + return false; + } + + public int getRemainingAir() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setRemainingAir(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getMaximumAir() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setMaximumAir(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean isSneaking() + { + return false; + } + + public void setSneaking(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void updateInventory() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void chat(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public double getEyeHeight() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public double getEyeHeight(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public List<Block> getLineOfSight(HashSet<Byte> hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Block getTargetBlock(HashSet<Byte> hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getFireTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getMaxFireTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setFireTicks(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void remove() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Server getServer() + { + return Essentials.getStatic() == null ? null : Essentials.getStatic().getServer(); + } + + public Vector getMomentum() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setMomentum(Vector vector) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setVelocity(Vector vector) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Vector getVelocity() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void damage(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void damage(int i, Entity entity) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Location getEyeLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void sendRawMessage(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/PlayerExtension.java b/Essentials/src/com/earth2me/essentials/PlayerExtension.java new file mode 100644 index 000000000..758f8076d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/PlayerExtension.java @@ -0,0 +1,141 @@ +package com.earth2me.essentials; + +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.IInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; +import org.bukkit.entity.*; + + +public class PlayerExtension extends PlayerWrapper +{ + public PlayerExtension(Player base) + { + super(base); + } + + public boolean isBanned() + { + return Essentials.getStatic().bans.contains(getName()); + } + + public boolean isIpBanned() + { + return Essentials.getStatic().bannedIps.contains(getAddress().getAddress().toString().replace("/", "")); + } + + public float getCorrectedYaw() + { + float angle = (getLocation().getYaw() - 90) % 360; + if (angle < 0) angle += 360.0F; + return angle; + } + + public void showInventory(IInventory inventory) + { + getHandle().a(inventory); + } + + public void showInventory(CraftInventoryPlayer inventory) + { + showInventory((IInventory)inventory.getInventory()); + } + + public Location getSafeDestination(Location loc) throws Exception + { + World world = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + while (isBlockAboveAir(world, x, y, z)) + { + y -= 1.0D; + if (y < 0) { + throw new Exception("Hole in floor"); + } + } + + while (isBlockUnsafe(world, x, y, z)) + { + y += 1.0D; + if (y >= 110.0D) { + x += 1.0D; + break; + } + } + while (isBlockUnsafe(world, x, y, z)) + { + y -= 1.0D; + if (y <= 1.0D) + { + y = 110.0D; + x += 1.0D; + } + } + return new Location(world, x, y, z, loc.getYaw(), loc.getPitch()); + } + + private boolean isBlockAboveAir(World world, double x, double y, double z) + { + return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR; + } + + public boolean isBlockUnsafe(World world, double x, double y, double z) + { + Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)); + if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) + return true; + + if (below.getType() == Material.FIRE) + return true; + + if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR) + || (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR)) + { + return true; + } + return isBlockAboveAir(world, x, y, z); + } + + public TargetBlock getTarget() + { + return new TargetBlock(getBase()); + } + + public String getGroup() + { + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.getGroup(getWorld().getName(), getName()); + } + catch (Throwable ex) + { + return "default"; + } + } + + public boolean canBuild() + { + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.canGroupBuild(getWorld().getName(), getGroup()); + } + catch (Throwable ex) + { + return true; + } + } + + public EntityPlayer getHandle() + { + return (EntityPlayer)getCraftPlayer().getHandle(); + } + + public CraftPlayer getCraftPlayer() + { + return (CraftPlayer)base; + } +} diff --git a/Essentials/src/com/earth2me/essentials/PlayerWrapper.java b/Essentials/src/com/earth2me/essentials/PlayerWrapper.java new file mode 100644 index 000000000..cf3a6db58 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/PlayerWrapper.java @@ -0,0 +1,335 @@ +package com.earth2me.essentials; + +import java.net.InetSocketAddress; +import java.util.*; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.util.Vector; + +public class PlayerWrapper implements Player +{ + protected Player base; + + public PlayerWrapper(Player base) + { + this.base = base; + } + + public final Player getBase() + { + return base; + } + + public final Player setBase(Player base) + { + return this.base = base; + } + + @Override + public void setDisplayName(String string) + { + base.setDisplayName(string); + } + + @Override + public void setCompassTarget(Location lctn) + { + base.setCompassTarget(lctn); + } + + @Override + public InetSocketAddress getAddress() + { + return base.getAddress(); + } + + @Override + public void kickPlayer(String string) + { + base.kickPlayer(string); + } + + @Override + public String getName() + { + return base.getName(); + } + + @Override + public PlayerInventory getInventory() + { + return base.getInventory(); + } + + @Override + public ItemStack getItemInHand() + { + return base.getItemInHand(); + } + + @Override + public void setItemInHand(ItemStack is) + { + base.setItemInHand(is); + } + + @Override + public int getHealth() + { + return base.getHealth(); + } + + @Override + public void setHealth(int i) + { + base.setHealth(i); + } + + @Override + public Egg throwEgg() + { + return base.throwEgg(); + } + + @Override + public Snowball throwSnowball() + { + return base.throwSnowball(); + } + + @Override + public Arrow shootArrow() + { + return base.shootArrow(); + } + + @Override + public boolean isInsideVehicle() + { + return base.isInsideVehicle(); + } + + @Override + public boolean leaveVehicle() + { + return base.leaveVehicle(); + } + + @Override + public Vehicle getVehicle() + { + return base.getVehicle(); + } + + @Override + public Location getLocation() + { + return base.getLocation(); + } + + @Override + public World getWorld() + { + return base.getWorld(); + } + + @Override + public Server getServer() + { + return base.getServer(); + } + + @Override + public boolean isOnline() + { + return base.isOnline(); + } + + @Override + public boolean isOp() + { + return base.isOp(); + } + + @Override + public void teleportTo(Location lctn) + { + base.teleportTo(lctn); + } + + @Override + public void teleportTo(Entity entity) + { + base.teleportTo(entity); + } + + @Override + public void sendMessage(String string) + { + base.sendMessage(string); + } + + @Override + public void setVelocity(Vector vector) + { + base.setVelocity(vector); + } + + @Override + public Vector getVelocity() + { + return base.getVelocity(); + } + + @Override + public double getEyeHeight() + { + return base.getEyeHeight(); + } + + @Override + public double getEyeHeight(boolean bln) + { + return base.getEyeHeight(bln); + } + + @Override + public List<Block> getLineOfSight(HashSet<Byte> hs, int i) + { + return base.getLineOfSight(hs, i); + } + + @Override + public Block getTargetBlock(HashSet<Byte> hs, int i) + { + return base.getTargetBlock(hs, i); + } + + @Override + public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i) + { + return base.getLastTwoTargetBlocks(hs, i); + } + + @Override + public int getFireTicks() + { + return base.getFireTicks(); + } + + @Override + public int getMaxFireTicks() + { + return base.getMaxFireTicks(); + } + + @Override + public void setFireTicks(int i) + { + base.setFireTicks(i); + } + + @Override + public void remove() + { + base.remove(); + } + + /** + * This is not deprecated because the underlying method isn't really deprecated; rather, it's just "imperfect". By + * We will continue to use this method even after the underlying CraftBukkit method is changed, so do not deprecate + * it. Chances are Bukkit will also choose to un-deprecate this method at some point. + */ + @Override + public void updateInventory() + { + base.updateInventory(); + } + + @Override + public void chat(String string) + { + base.chat(string); + } + + @Override + public boolean isSneaking() + { + return base.isSneaking(); + } + + @Override + public void setSneaking(boolean bln) + { + base.setSneaking(bln); + } + + @Override + public int getEntityId() + { + return base.getEntityId(); + } + + @Override + public boolean performCommand(String string) + { + return base.performCommand(string); + } + + @Override + public int getRemainingAir() + { + return base.getRemainingAir(); + } + + @Override + public void setRemainingAir(int i) + { + base.setRemainingAir(i); + } + + @Override + public int getMaximumAir() + { + return base.getMaximumAir(); + } + + @Override + public void setMaximumAir(int i) + { + base.setMaximumAir(i); + } + + @Override + public String getDisplayName() + { + if (base.getDisplayName() != null) + return base.getDisplayName(); + else + return base.getName(); + } + + @Override + public void damage(int i) + { + base.damage(i); + } + + @Override + public void damage(int i, Entity entity) + { + base.damage(i, entity); + } + + @Override + public Location getEyeLocation() + { + return base.getEyeLocation(); + } + + public void sendRawMessage(String string) { + base.sendRawMessage(string); + } +} diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java new file mode 100644 index 000000000..9c774b848 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Settings.java @@ -0,0 +1,348 @@ +package com.earth2me.essentials; + +import java.util.*; +import org.bukkit.ChatColor; +import com.earth2me.essentials.commands.IEssentialsCommand; +import java.io.File; +import java.util.ArrayList; +import org.bukkit.entity.CreatureType; + + +public class Settings implements IConf +{ + private EssentialsConf config; + + public Settings(File dataFolder) + { + config = new EssentialsConf(new File(dataFolder, "config.yml")); + config.setTemplateName("/config.yml"); + config.load(); + } + + public boolean getRespawnAtHome() + { + return config.getBoolean("respawn-at-home", false); + } + + public boolean getBedSetsHome() + { + return config.getBoolean("bed-sethome", false); + } + + public int getChatRadius() + { + return config.getInt("chat.radius", config.getInt("chat-radius", 0)); + } + + public long getTeleportDelay() + { + return config.getInt("teleport-delay", 0) * 1000L; + } + + public int getDefaultStackSize() + { + return config.getInt("default-stack-size", 64); + } + + public int getStartingBalance() + { + return config.getInt("starting-balance", 0); + } + + public boolean getNetherPortalsEnabled() + { + return isNetherEnabled() && config.getBoolean("nether.portals-enabled", false); + } + + public String getMcslKey() + { + return config.getString("mcsl-key", "").replaceAll("[^a-zA-Z0-9]", ""); + } + + public boolean getWhitelistEnabled() + { + return false; + } + + public boolean isCommandDisabled(IEssentialsCommand cmd) + { + return isCommandDisabled(cmd.getName()); + } + + public boolean isCommandDisabled(String label) + { + for (String c : config.getStringList("disabled-commands", new ArrayList<String>(0))) + { + if (!c.equalsIgnoreCase(label)) continue; + return true; + } + return config.getBoolean("disable-" + label.toLowerCase(), false); + } + + public boolean isCommandRestricted(IEssentialsCommand cmd) + { + return isCommandRestricted(cmd.getName()); + } + + public boolean isCommandRestricted(String label) + { + for (String c : config.getStringList("restricted-commands", new ArrayList<String>(0))) + { + if (!c.equalsIgnoreCase(label)) continue; + return true; + } + return config.getBoolean("restrict-" + label.toLowerCase(), false); + } + + public int getCommandCost(IEssentialsCommand cmd) + { + return getCommandCost(cmd.getName()); + } + + public int getCommandCost(String label) + { + int cost = config.getInt("command-costs." + label, 0); + if (cost == 0) + cost = config.getInt("cost-" + label, 0); + return cost; + } + + public String getCommandPrefix() + { + return config.getString("command-prefix", ""); + } + + public String getNicknamePrefix() + { + return config.getString("nickname-prefix", ""); + } + + public long getTeleportCooldown() + { + return (long)config.getInt("teleport-cooldown", 60) * 1000L; + } + + public long getHealCooldown() + { + return (long)config.getInt("heal-cooldown", 60) * 1000L; + } + + public Object getKit(String name) + { + Map<String, Object> kits = (Map<String, Object>)config.getProperty("kits"); + return kits.get(name.replace('.', '_').replace('/', '_')); + } + + public ChatColor getOperatorColor() + { + String colorName = config.getString("ops-name-color", null); + + if (colorName == null) + return ChatColor.RED; + + try + { + return ChatColor.valueOf(colorName.toUpperCase()); + } + catch (IllegalArgumentException ex) + { + } + + return ChatColor.getByCode(Integer.parseInt(colorName, 16)); + } + + public boolean getReclaimSetting() + { + return config.getBoolean("reclaim-onlogout", true); + } + + public String getNetherName() + { + return config.getString("nether.folder", "nether"); + } + + public boolean isNetherEnabled() + { + return config.getBoolean("nether.enabled", true); + } + + public int getSpawnMobLimit() + { + return config.getInt("spawnmob-limit", 10); + } + + public boolean showNonEssCommandsInHelp() + { + return config.getBoolean("non-ess-in-help", true); + } + + public HashMap<String, Boolean> getEpSettings() + { + HashMap<String, Boolean> epSettings = new HashMap<String, Boolean>(); + + epSettings.put("protect.protect.signs", config.getBoolean("protect.protect.signs", true)); + epSettings.put("protect.protect.rails", config.getBoolean("protect.protect.rails", true)); + epSettings.put("protect.protect.block-below", config.getBoolean("protect.protect.block-below", true)); + epSettings.put("protect.protect.prevent-block-on-rails", config.getBoolean("protect.protect.prevent-block-on-rails", false)); + return epSettings; + } + + public HashMap<String, String> getEpDBSettings() + { + HashMap<String, String> epSettings = new HashMap<String, String>(); + epSettings.put("protect.datatype", config.getString("protect.datatype", "sqlite")); + epSettings.put("protect.username", config.getString("protect.username", "root")); + epSettings.put("protect.password", config.getString("protect.password", "root")); + epSettings.put("protect.mysqlDb", config.getString("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft")); + return epSettings; + } + + public ArrayList getEpAlertOnPlacement() + { + ArrayList epAlertPlace = new ArrayList(); + epAlertPlace.addAll(Arrays.asList(config.getString("protect.alert.on-placement", "").split(","))); + return epAlertPlace; + } + + public ArrayList getEpAlertOnUse() + { + ArrayList epAlertUse = new ArrayList(); + epAlertUse.addAll(Arrays.asList(config.getString("protect.alert.on-use", "").split(","))); + return epAlertUse; + } + + public ArrayList getEpAlertOnBreak() + { + ArrayList epAlertPlace = new ArrayList(); + epAlertPlace.addAll(Arrays.asList(config.getString("protect.alert.on-break", "").split(","))); + return epAlertPlace; + } + + public ArrayList epBlackListPlacement() + { + ArrayList epBlack = new ArrayList(); + epBlack.addAll(Arrays.asList(config.getString("protect.blacklist.placement", "").split(","))); + return epBlack; + } + + public ArrayList epBlackListUsage() + { + ArrayList epBlack = new ArrayList(); + epBlack.addAll(Arrays.asList(config.getString("protect.blacklist.usage", "").split(","))); + return epBlack; + } + + public HashMap<String, Boolean> getEpGuardSettings() + { + HashMap<String, Boolean> epSettings = new HashMap<String, Boolean>(); + epSettings.put("protect.prevent.lava-flow", config.getBoolean("protect.prevent.lava-flow", false)); + epSettings.put("protect.prevent.water-flow", config.getBoolean("protect.prevent.water-flow", false)); + epSettings.put("protect.prevent.water-bucket-flow", config.getBoolean("protect.prevent.water-bucket-flow", false)); + epSettings.put("protect.prevent.fire-spread", config.getBoolean("protect.prevent.fire-spread", false)); + epSettings.put("protect.prevent.flint-fire", config.getBoolean("protect.prevent.flint-fire", false)); + epSettings.put("protect.prevent.lava-fire-spread", config.getBoolean("protect.prevent.lava-fire-spread", false)); + epSettings.put("protect.prevent.tnt-explosion", config.getBoolean("protect.prevent.tnt-explosion", false)); + epSettings.put("protect.prevent.creeper-explosion", config.getBoolean("protect.prevent.creeper-explosion", false)); + epSettings.put("protect.prevent.creeper-playerdamage", config.getBoolean("protect.prevent.creeper-playerdamage", false)); + epSettings.put("protect.prevent.creeper-blockdamage", config.getBoolean("protect.prevent.creeper-blockdamage", false)); + for (CreatureType ct : CreatureType.values()) { + String name = ct.toString().toLowerCase(); + epSettings.put("protect.prevent.spawn."+name, config.getBoolean("protect.prevent.spawn."+name, false)); + } + return epSettings; + } + + public HashMap<String, Boolean> getEpPlayerSettings() + { + HashMap<String, Boolean> epPlayerSettings = new HashMap<String, Boolean>(); + epPlayerSettings.put("protect.disable.fall", config.getBoolean("protect.disable.fall", false)); + epPlayerSettings.put("protect.disable.pvp", config.getBoolean("protect.disable.pvp", false)); + epPlayerSettings.put("protect.disable.drown", config.getBoolean("protect.disable.drown", false)); + epPlayerSettings.put("protect.disable.suffocate", config.getBoolean("protect.disable.suffocate", false)); + epPlayerSettings.put("protect.disable.lavadmg", config.getBoolean("protect.disable.lavadmg", false)); + epPlayerSettings.put("protect.disable.projectiles", config.getBoolean("protect.disable.projectiles", false)); + epPlayerSettings.put("protect.disable.contactdmg", config.getBoolean("protect.disable.contactdmg", false)); + epPlayerSettings.put("protect.disable.firedmg", config.getBoolean("protect.disable.firedmg", false)); + epPlayerSettings.put("protect.disable.build", config.getBoolean("protect.disable.build", false)); + return epPlayerSettings; + + } + + public int getEpCreeperMaxHeight() + { + return config.getInt("protect.creeper.max-height", -1); + } + + public boolean areSignsDisabled() + { + return config.getBoolean("signs-disabled", false); + } + + public long getBackupInterval() + { + return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 + } + + public String getBackupCommand() + { + return config.getString("backup.command", null); + } + + public String getChatFormat(String group) + { + return config.getString("chat.group-formats." + (group == null ? "Default" : group), + config.getString("chat.format", "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}")); + } + + public boolean getGenerateExitPortals() + { + return config.getBoolean("nether.generate-exit-portals", true); + } + + public boolean getAnnounceNewPlayers() + { + return !config.getString("newbies.announce-format", "-").isEmpty(); + } + + public String getAnnounceNewPlayerFormat(User user) + { + return format(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"), user); + } + + public String format(String format, User user) + { + return format.replace('&', '§').replace("§§", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", user.getGroup()).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); + } + + public String getNewbieSpawn() + { + return config.getString("newbies.spawnpoint", "default"); + } + public boolean getPerWarpPermission() + { + return config.getBoolean("per-warp-permission", false); + } + + public boolean getSortListByGroups() + { + return config.getBoolean("sort-list-by-groups", true); + } + + public void reloadConfig() { + config.load(); + } + + public ArrayList itemSpawnBlacklist() + { + ArrayList epItemSpwn = new ArrayList(); + epItemSpwn.addAll(Arrays.asList(config.getString("item-spawn-blacklist", "").split(","))); + return epItemSpwn; + } + + public ArrayList epBlockBreakingBlacklist() + { + ArrayList epBreakList = new ArrayList(); + epBreakList.addAll(Arrays.asList(config.getString("protect.blacklist.break", "").split(","))); + return epBreakList; + } +} diff --git a/Essentials/src/com/earth2me/essentials/Spawn.java b/Essentials/src/com/earth2me/essentials/Spawn.java new file mode 100644 index 000000000..f3c4de06a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Spawn.java @@ -0,0 +1,87 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.World.Environment; + +public class Spawn implements IConf { + + private static final Logger logger = Logger.getLogger("Minecraft"); + private EssentialsConf config; + private Server server; + + public Spawn(Server server, File dataFolder) { + File configFile = new File(dataFolder, "spawn.yml"); + this.server = server; + config = new EssentialsConf(configFile); + config.load(); + } + + public void setSpawn(Location loc, String group) { + Map<String, Object> map = new HashMap<String, Object>(); + map.put("world", loc.getWorld().getName()); + map.put("x", loc.getX()); + map.put("y", loc.getY()); + map.put("z", loc.getZ()); + map.put("yaw", loc.getYaw()); + map.put("pitch", loc.getPitch()); + config.setProperty(group, map); + config.save(); + + if ("default".equals(group)) { + loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + } + + public Location getSpawn(String group) { + if (config.getProperty(group) == null) { + group = "default"; + } + if (config.getProperty(group) == null) { + for (World w : server.getWorlds()) { + if (w.getEnvironment() != Environment.NORMAL) { + continue; + } + return w.getSpawnLocation(); + } + } + String worldId = config.getString(group + ".world", ""); + World world = server.getWorlds().get(server.getWorlds().size() > 1 ? 1 : 0); + for (World w : server.getWorlds()) { + if (w.getEnvironment() != Environment.NORMAL) { + continue; + } + world = w; + break; + } + for (World w : server.getWorlds()) { + if (!w.getName().equals(worldId)) { + continue; + } + world = w; + break; + } + + double x = config.getDouble(group + ".x", config.getDouble("default.x", 0)); + double y = config.getDouble(group + ".y", config.getDouble("default.y", 0)); + double z = config.getDouble(group + ".z", config.getDouble("default.z", 0)); + float yaw = (float) config.getDouble(group + ".yaw", config.getDouble("default.yaw", 0)); + float pitch = (float) config.getDouble(group + ".pitch", config.getDouble("default.pitch", 0)); + Location retval = new Location(world, x, y, z, yaw, pitch); + + if (y < 1) { + retval.setY(world.getHighestBlockYAt(retval)); + } + + return retval; + } + + public void reloadConfig() { + config.load(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/TargetBlock.java b/Essentials/src/com/earth2me/essentials/TargetBlock.java new file mode 100644 index 000000000..d3ac30d2d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/TargetBlock.java @@ -0,0 +1,599 @@ +package com.earth2me.essentials; + +import java.util.ArrayList; +import org.bukkit.block.Block; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +/** + * @author toi + * Thanks to Raphfrk for optimization of this class. + */ +public class TargetBlock { + + private Location loc; + private double viewHeight; + private int maxDistance; + private int[] blockToIgnore; + private double checkDistance, curDistance; + private double xRotation, yRotation; + private Vector targetPos = new Vector(); + private Vector targetPosDouble = new Vector(); + private Vector prevPos = new Vector(); + private Vector offset = new Vector(); + + /** + * Constructor requiring a player, uses default values + * + * @param player Player to work with + */ + public TargetBlock(Player player) + { + this.setValues(player.getLocation(), 300, 1.65, 0.2, null); + } + + /** + * Constructor requiring a location, uses default values + * + * @param loc Location to work with + */ + public TargetBlock(Location loc) + { + this.setValues(loc, 300, 0, 0.2, null); + } + + /** + * Constructor requiring a player, max distance and a checking distance + * + * @param player Player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + */ + public TargetBlock(Player player, int maxDistance, double checkDistance) + { + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, null); + } + + /** + * Constructor requiring a location, max distance and a checking distance + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + */ + public TargetBlock(Location loc, int maxDistance, double checkDistance) { + this.setValues(loc, maxDistance, 0, checkDistance, null); + } + + /** + * Constructor requiring a player, max distance, checking distance and an array of blocks to ignore + * + * @param player What player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Integer array of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Player player, int maxDistance, double checkDistance, int[] blocksToIgnore) + { + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, blocksToIgnore); + } + + /** + * Constructor requiring a location, max distance, checking distance and an array of blocks to ignore + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Array of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Location loc, int maxDistance, double checkDistance, int[] blocksToIgnore) + { + this.setValues(loc, maxDistance, 0, checkDistance, blocksToIgnore); + } + + /** + * Constructor requiring a player, max distance, checking distance and an array of blocks to ignore + * + * @param player What player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Player player, int maxDistance, double checkDistance, ArrayList<String> blocksToIgnore) + { + int[] bti = this.convertStringArraytoIntArray(blocksToIgnore); + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, bti); + } + + /** + * Constructor requiring a location, max distance, checking distance and an array of blocks to ignore + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Location loc, int maxDistance, double checkDistance, ArrayList<String> blocksToIgnore) + { + int[] bti = this.convertStringArraytoIntArray(blocksToIgnore); + this.setValues(loc, maxDistance, 0, checkDistance, bti); + } + + /** + * Set the values, all constructors uses this function + * + * @param loc Location of the view + * @param maxDistance How far it checks for blocks + * @param viewPos Where the view is positioned in y-axis + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Ids of blocks to ignore while checking for viable targets + */ + private void setValues(Location loc, int maxDistance, double viewHeight, double checkDistance, int[] blocksToIgnore) + { + this.loc = loc; + this.maxDistance = maxDistance; + this.viewHeight = viewHeight; + this.checkDistance = checkDistance; + this.blockToIgnore = blocksToIgnore; + this.curDistance = 0; + xRotation = (loc.getYaw() + 90) % 360; + yRotation = loc.getPitch() * -1; + + double h = (checkDistance * Math.cos(Math.toRadians(yRotation))); + offset.setY((checkDistance * Math.sin(Math.toRadians(yRotation)))); + offset.setX((h * Math.cos(Math.toRadians(xRotation)))); + offset.setZ((h * Math.sin(Math.toRadians(xRotation)))); + + targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + prevPos = targetPos.clone(); + } + + /** + * Call this to reset checking position to allow you to check for a new target with the same TargetBlock instance. + */ + public void reset() + { + targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + prevPos = targetPos.clone(); + this.curDistance = 0; + } + + /** + * Gets the distance to a block. Measures from the block underneath the player to the targetblock + * Should only be used when passing player as an constructor parameter + * + * @return double + */ + public double getDistanceToBlock() + { + Vector blockUnderPlayer = new Vector( + (int) Math.floor(loc.getX() + 0.5), + (int) Math.floor(loc.getY() - 0.5), + (int) Math.floor(loc.getZ() + 0.5)); + + Block blk = getTargetBlock(); + double x = blk.getX() - blockUnderPlayer.getBlockX(); + double y = blk.getY() - blockUnderPlayer.getBlockY(); + double z = blk.getZ() - blockUnderPlayer.getBlockZ(); + + return Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))); + } + + /** + * Gets the rounded distance to a block. Measures from the block underneath the player to the targetblock + * Should only be used when passing player as an constructor parameter + * + * @return int + */ + public int getDistanceToBlockRounded() + { + Vector blockUnderPlayer = new Vector( + (int) Math.floor(loc.getX() + 0.5), + (int) Math.floor(loc.getY() - 0.5), + (int) Math.floor(loc.getZ() + 0.5)); + + Block blk = getTargetBlock(); + double x = blk.getX() - blockUnderPlayer.getBlockX(); + double y = blk.getY() - blockUnderPlayer.getBlockY(); + double z = blk.getZ() - blockUnderPlayer.getBlockZ(); + + return (int) Math.round((Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))))); + } + + /** + * Gets the floored x distance to a block. + * + * @return int + */ + public int getXDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getX() - loc.getBlockX() + 0.5); + } + + /** + * Gets the floored y distance to a block + * + * @return int + */ + public int getYDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getY() - loc.getBlockY() + viewHeight); + } + + /** + * Gets the floored z distance to a block + * + * @return int + */ + public int getZDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getZ() - loc.getBlockZ() + 0.5); + } + + /** + * Returns the block at the sight. Returns null if out of range or if no viable target was found + * + * @return Block + */ + @SuppressWarnings("empty-statement") + public Block getTargetBlock() + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + return getCurrentBlock(); + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * + * @param typeID ID of type to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + this.reset(); + while (getNextBlock() != null && getCurrentBlock().getTypeId() == 0); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * + * @param type Material to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(Material type) + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type Name of type to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Returns the block attached to the face at the sight. Returns null if out of range or if no viable target was found + * + * @return Block + */ + @SuppressWarnings("empty-statement") + public Block getFaceBlock() + { + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + return getPreviousBlock(); + } + else + { + return null; + } + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * + * @param typeID + * @return boolean + */ + public boolean setFaceBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * + * @param type + * @return boolean + */ + public boolean setFaceBlock(Material type) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + * @return boolean + */ + public boolean setFaceBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Get next block + * + * @return Block + */ + public Block getNextBlock() + { + prevPos = targetPos.clone(); + do + { + curDistance += checkDistance; + + targetPosDouble.setX(offset.getX() + targetPosDouble.getX()); + targetPosDouble.setY(offset.getY() + targetPosDouble.getY()); + targetPosDouble.setZ(offset.getZ() + targetPosDouble.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + } + while (curDistance <= maxDistance && targetPos.getBlockX() == prevPos.getBlockX() && targetPos.getBlockY() == prevPos.getBlockY() && targetPos.getBlockZ() == prevPos.getBlockZ()); + if (curDistance > maxDistance) + { + return null; + } + + return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ()); + } + + /** + * Returns the current block along the line of vision + * + * @return Block + */ + public Block getCurrentBlock() + { + if (curDistance > maxDistance) + { + return null; + } + else + { + return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ()); + } + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * + * @param typeID + */ + public boolean setCurrentBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * + * @param type + */ + public boolean setCurrentBlock(Material type) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + */ + public boolean setCurrentBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Returns the previous block in the aimed path + * + * @return Block + */ + public Block getPreviousBlock() + { + return this.loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * + * @param typeID + */ + public boolean setPreviousBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * + * @param type + */ + public boolean setPreviousBlock(Material type) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + */ + public boolean setPreviousBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setType(mat); + return true; + } + } + return false; + } + + private int[] convertStringArraytoIntArray(ArrayList<String> array) + { + if (array != null) + { + int intarray[] = new int[array.size()]; + for (int i = 0; i < array.size(); i++) + { + try + { + intarray[i] = Integer.parseInt(array.get(i)); + } + catch (NumberFormatException nfe) + { + intarray[i] = 0; + } + } + return intarray; + } + return null; + } + + private boolean blockToIgnoreHasValue(int value) + { + if (this.blockToIgnore != null) + { + if (this.blockToIgnore.length > 0) + { + for (int i : this.blockToIgnore) + { + if (i == value) + return true; + } + } + } + return false; + } +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/TeleportTimer.java b/Essentials/src/com/earth2me/essentials/TeleportTimer.java new file mode 100644 index 000000000..11d65170f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/TeleportTimer.java @@ -0,0 +1,73 @@ +package com.earth2me.essentials; + +import java.util.TimerTask; +import java.util.Calendar; + + +public abstract class TeleportTimer implements Runnable +{ + private long started; // time this task was initiated + private long delay; // how long to delay the teleport + public User user; // the person doing the teleport + private int health; + // note that I initially stored a clone of the location for reference, but... + // when comparing locations, I got incorrect mismatches (rounding errors, looked like) + // so, the X/Y/Z values are stored instead and rounded off + private long initX; + private long initY; + private long initZ; + + public TeleportTimer(User tUser, long tDelay) + { + this.started = Calendar.getInstance().getTimeInMillis(); + this.delay = tDelay; + this.user = tUser; + this.health = user.getHealth(); + this.initX = Math.round(user.getLocation().getX() * 10000); + this.initY = Math.round(user.getLocation().getY() * 10000); + this.initZ = Math.round(user.getLocation().getZ() * 10000); + } + + // This function needs to be defined when creating a new TeleportTimer + // The actual teleport command by itself should be stuck in there, such as teleportToNow(loc) + public abstract void DoTeleport(); + + public abstract void DoCancel(); + + public void run() + { + if (user == null || !user.isOnline() || user.getLocation() == null) + { + DoCancel(); + return; + } + if (Math.round(user.getLocation().getX() * 10000) != initX + || Math.round(user.getLocation().getY() * 10000) != initY + || Math.round(user.getLocation().getZ() * 10000) != initZ + || user.getHealth() < health) + { // user moved, cancel teleport + user.cancelTeleport(true); + return; + } + + health = user.getHealth(); // in case user healed, then later gets injured + + long now = Calendar.getInstance().getTimeInMillis(); + if (now > started + delay) + { + try + { + user.teleportCooldown(false); + user.sendMessage("§7Teleportation commencing..."); + this.DoTeleport(); + return; + } + catch (Exception ex) + { + user.sendMessage("§cCooldown: " + ex.getMessage()); + } + } + //else // uncomment for timing debug + // user.sendMessage("§7" + (started + delay - now)); + } +} diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java new file mode 100644 index 000000000..0853975ca --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -0,0 +1,693 @@ +package com.earth2me.essentials; + +import java.util.*; +import java.util.logging.*; +import java.io.*; +import org.bukkit.*; +import com.earth2me.essentials.commands.IEssentialsCommand; +import net.minecraft.server.EntityHuman; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.*; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + + +public class User extends PlayerExtension implements Comparable<User> +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private final Yaml yaml = new Yaml(new SafeConstructor()); + private boolean isLoaded = false; + private final File folder; + private Map<String, Object> data = new HashMap<String, Object>(); + private static Map<String, User> users = new HashMap<String, User>(); + private boolean teleEnabled = true; + private long lastTeleport = 0; + private long lastHeal = 0; + private boolean justPortaled = false; + //private TimerTask teleTimer = null; + private int teleTimer = -1; + public Location lastLocation = null; + private User replyTo = null; + private boolean isNew = false; + public String currentJail; + public CraftItemStack[] savedInventory; + + private User(Player base) + { + super(base); + this.folder = new File((Essentials.getStatic() == null ? new File(".") : Essentials.getStatic().getDataFolder()), "userdata"); + + if (base instanceof EntityHuman) + { + this.lastLocation = getBase().getLocation(); + } + load(); + } + + public static int size() + { + return users.size(); + } + + public static <T> User get(T base) + { + if (base instanceof Player) + return get((Player)base); + return null; + } + + public static <T extends Player> User get(T base) + { + if (base == null) + return null; + + if (base instanceof User) + return (User)base; + + if (users.containsKey(base.getName())) + return users.get(base.getName()).update(base); + + User u = new User(base); + users.put(u.getName(), u); + return u; + } + + public static <T> void charge(T base, IEssentialsCommand cmd) throws Exception + { + if (base instanceof Player) + User.get(base).charge(cmd); + } + + public boolean isNew() + { + return isNew; + } + + public void respawn(Spawn spawn) throws Exception + { + respawn(spawn, null); + } + + public void respawn(Spawn spawn, final String chargeFor) throws Exception + { + teleportTo(getSafeDestination(spawn.getSpawn(getGroup())), chargeFor); + } + + private User update(Player base) + { + setBase(base); + return this; + } + + public boolean isAuthorized(IEssentialsCommand cmd) + { + return isAuthorized("essentials." + (cmd.getName().equals("r") ? "msg" : cmd.getName())); + } + + public boolean isAuthorized(String node) + { + if (isOp()) + return true; + + if (isJailed()) + return false; + + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.permission(base, node); + } + catch (Throwable ex) + { + String[] cmds = node.split("\\.", 2); + return !Essentials.getSettings().isCommandRestricted(cmds[cmds.length - 1]); + } + } + + public boolean isTeleEnabled() + { + return teleEnabled; + } + + public boolean toggleTeleEnabled() + { + return teleEnabled = !teleEnabled; + } + + public void teleportCooldown(boolean justCheck) throws Exception + { + long now = Calendar.getInstance().getTimeInMillis(); + long cooldown = Essentials.getSettings().getTeleportCooldown(); + long left = lastTeleport + cooldown - now; + if (left > 0 && !isOp() && !isAuthorized("essentials.teleport.cooldown.bypass")) + throw new Exception("Time before next teleport: " + Essentials.FormatTime(left)); + // if justCheck is set, don't update lastTeleport; we're just checking + if (!justCheck) lastTeleport = now; + } + + public void teleportCooldown() throws Exception + { + teleportCooldown(true); + } + + public void healCooldown() throws Exception + { + long now = Calendar.getInstance().getTimeInMillis(); + long cooldown = Essentials.getSettings().getHealCooldown(); + long left = lastHeal + cooldown - now; + if (left > 0 && !isOp() && !isAuthorized("essentials.heal.cooldown.bypass")) + throw new Exception("Time before next heal: " + Essentials.FormatTime(left)); + lastHeal = now; + } + + private void load() + { + if (isLoaded) return; + isLoaded = true; + + data = Essentials.getData(this); + + try + { + if (!folder.exists()) folder.mkdirs(); + File file = new File(folder, getName() + ".yml"); + if (!file.exists()) + { + isNew = true; + file.createNewFile(); + logger.info(getName() + " has logged in for the first time."); + } + + FileInputStream rx = new FileInputStream(file); + Map<String, Object> userData = (Map<String, Object>)yaml.load(new UnicodeReader(rx)); + if (userData != null) data.putAll(userData); + rx.close(); + } + catch (Throwable ex) + { + logger.log(Level.SEVERE, null, ex); + } + finally + { + if (data == null) data = new HashMap<String, Object>(); + } + } + + private void flush() + { + try + { + if (!folder.exists()) folder.mkdirs(); + File file = new File(folder, getName() + ".yml"); + if (!file.exists()) file.createNewFile(); + + FileWriter tx = new FileWriter(file); + tx.write(yaml.dump(data)); + tx.flush(); + tx.close(); + } + catch (Throwable ex) + { + logger.log(Level.SEVERE, null, ex); + } + } + + public boolean isGodModeEnabled() + { + load(); + return data.containsKey("godmode") && (Boolean)data.get("godmode"); + } + + public boolean toggleGodMode() + { + boolean retval = !isGodModeEnabled(); + data.put("godmode", retval); + flush(); + return retval; + } + + public boolean isMuted() + { + load(); + return data.containsKey("muted") && (Boolean)data.get("muted"); + } + + public boolean toggleMuted() + { + boolean retval = !isMuted(); + data.put("muted", retval); + flush(); + return retval; + } + + public boolean isJailed() + { + //load(); Do not load config everytime time! + return data.containsKey("jailed") && (Boolean)data.get("jailed"); + } + + public boolean toggleJailed() + { + boolean retval = !isJailed(); + data.put("jailed", retval); + flush(); + load(); + return retval; + } + + public double getMoney() + { + load(); + if (data.containsKey("money")) + { + if (data.get("money") instanceof Integer) + return (double)((Integer)data.get("money")); + return (Double)data.get("money"); + } + + try + { + return com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).getBalance(); + } + catch (Throwable ex) + { + try + { + Map<String, Object> idata = Essentials.getData(this); + return (Integer)idata.get("money"); + } + catch (Throwable ex2) + { + return Essentials.getSettings().getStartingBalance(); + } + } + } + + public void setMoney(double value) + { + try + { + com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value); + } + catch (Throwable ex) + { + data.put("money", value); + flush(); + } + } + + public void giveMoney(double value) + { + if (value == 0) return; + setMoney(getMoney() + value); + sendMessage("§a$" + value + " has been added to your account."); + } + + public void payUser(User reciever, int value) throws Exception + { + if (value == 0) return; + if (!canAfford(value)) + { + throw new Exception("You do not have sufficient funds."); + } + else + { + setMoney(getMoney() - value); + reciever.setMoney(reciever.getMoney() + value); + sendMessage("§a$" + value + " has been sent to " + reciever.getDisplayName()); + reciever.sendMessage("§a$" + value + " has been recieved from " + getDisplayName()); + } + } + + public void takeMoney(double value) + { + if (value == 0) return; + setMoney(getMoney() - value); + sendMessage("§c$" + value + " has been taken from your account."); + } + + public void charge(String cmd) throws Exception + { + double mon = getMoney(); + double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); + if (mon < cost && !isOp()) + throw new Exception("You do not have sufficient funds."); + takeMoney(cost); + } + + public void canAfford(String cmd) throws Exception + { + double mon = getMoney(); + double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); + if (mon < cost && !isOp()) + throw new Exception("You do not have sufficient funds."); + } + + public boolean canAfford(double cost) + { + double mon = getMoney(); + if (mon < cost && !isOp()) + { + return false; + } + else + { + return true; + } + } + + public void canAfford(IEssentialsCommand cmd) throws Exception + { + canAfford(cmd.getName()); + } + + public void cancelTeleport(boolean notifyUser) + { + if (teleTimer == -1) return; + try + { + getServer().getScheduler().cancelTask(teleTimer); + if (notifyUser) sendMessage("§cPending teleportation request cancelled."); + } + catch (Throwable ex) + { + } + finally + { + teleTimer = -1; + } + } + + public void cancelTeleport() + { + cancelTeleport(false); + } + + public void teleportTo(final Location loc, final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + teleportToNow(loc); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(loc); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + } + + @Override + public void teleportTo(final Location loc) + { + teleportTo(loc, null); + } + + public void teleportTo(final Entity entity, final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + teleportToNow(entity); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(entity); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + } + + @Override + public void teleportTo(final Entity entity) + { + teleportTo(entity, null); + } + + public Location getHome() throws Exception + { + if (data.containsKey("home")) + { + List<Object> vals = (List<Object>)data.get("home"); + World world = getServer() == null ? null : getServer().getWorlds().get(0); + if (vals.size() > 5 && getServer() != null) + getServer().getWorld((String)vals.get(5)); + return new Location( + world, + (Double)vals.get(0), + (Double)vals.get(1), + (Double)vals.get(2), + ((Double)vals.get(3)).floatValue(), + ((Double)vals.get(4)).floatValue()); + } + + try + { + Map<String, Object> gdata = Essentials.getData(this); + List<Object> vals = (List<Object>)gdata.get("home"); + World world = getServer().getWorlds().get(0); + if (vals.size() > 5) + getServer().getWorld((String)vals.get(5)); + return new Location(world, + (Double)vals.get(0), + (Double)vals.get(1), + (Double)vals.get(2), + ((Double)vals.get(3)).floatValue(), + ((Double)vals.get(4)).floatValue()); + } + catch (Throwable ex) + { + throw new Exception("You have not set a home."); + } + } + + public void teleportToHome(final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + Location loc = null; + try + { + // check this first in case user hasn't set a home yet + loc = getHome(); + } + catch (Throwable ex) + { + sendMessage("§cTeleport: " + ex.getMessage()); + return; + } + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + teleportToNow(loc); + sendMessage("§7Teleporting home..."); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(getHome()); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + } + + public void teleportToHome() + { + teleportToHome(null); + } + + public void teleportToNow(Location loc) throws Exception + { + cancelTeleport(); + lastLocation = getLocation(); + getBase().teleportTo(getSafeDestination(loc)); + } + + public void teleportToNow(Entity entity) + { + cancelTeleport(); + lastLocation = getLocation(); + getBase().teleportTo(entity); + } + + public void teleportBack(final String chargeFor) + { + teleportTo(lastLocation, chargeFor); + } + + public void teleportBack() + { + teleportBack(null); + } + + public void dispose() + { + this.base = new OfflinePlayer(getName()); + } + + public void charge(IEssentialsCommand cmd) throws Exception + { + charge(cmd.getName()); + } + + public boolean getJustPortaled() + { + return justPortaled; + } + + public void setJustPortaled(boolean value) + { + justPortaled = value; + } + + public void setReplyTo(User user) + { + replyTo = user; + } + + public User getReplyTo() + { + return replyTo; + } + + public void setHome() + { + setHome(getLocation()); + } + + public void setHome(Location home) + { + List<Object> vals = new ArrayList<Object>(6); + vals.add(new Double(home.getX())); + vals.add(new Double(home.getY())); + vals.add(new Double(home.getZ())); + vals.add(new Double(home.getYaw())); + vals.add(new Double(home.getPitch())); + vals.add(home.getWorld() == null ? "world" : home.getWorld().getName()); + data.put("home", vals); + flush(); + + setCompassTarget(home); + } + + public String getNick() + { + Essentials ess = Essentials.getStatic(); + String name = ess.getConfiguration().getBoolean("disable-nick", false) ? getName() : ess.readNickname(this); + if (isOp() && ess.getConfiguration().getString("ops-name-color", "c").matches("^[0-9a-f]$")) { + name = "§" + ess.getConfiguration().getString("ops-name-color", "c") + name + "§f"; + } + return name; + } + + public void warpTo(String warp, final String chargeFor) throws Exception + { + lastLocation = getLocation(); + Location loc = Essentials.getWarps().getWarp(warp); + teleportTo(loc, chargeFor); + sendMessage("§7Warping to " + warp + "."); + } + + public void warpTo(String string) throws Exception + { + warpTo(string, null); + } + + public void clearNewFlag() + { + isNew = false; + } + + public int compareTo(User t) { + return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName())); + } + + public Boolean canSpawnItem(int itemId) + { + if(Essentials.getSettings().itemSpawnBlacklist().contains(itemId))return false; + return true; + } +} diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java new file mode 100644 index 000000000..beaeddf29 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -0,0 +1,244 @@ +package com.earth2me.essentials; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; + +public class Warps implements IConf { + + private static final Logger logger = Logger.getLogger("Minecraft"); + Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>(); + File warpsFolder; + Server server; + + public Warps(Server server, File dataFolder) { + this.server = server; + warpsFolder = new File(dataFolder, "warps"); + if (!warpsFolder.exists()) { + warpsFolder.mkdirs(); + } else { + convertWarps(dataFolder); + } + reloadConfig(); + } + + private String convertToFileName(String name) { + return name.toLowerCase().replaceAll("[^a-z0-9]", "_"); + } + + public boolean isEmpty() { + return warpPoints.isEmpty(); + } + + public Iterable<String> getWarpNames() { + List<String> keys = new ArrayList<String>(); + for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { + keys.add(stringIgnoreCase.string); + } + Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); + return keys; + } + + public Location getWarp(String warp) throws Exception { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); + if (conf == null) { + throw new Exception("That warp does not exist."); + } + double x = conf.getDouble("x", 0); + double y = conf.getDouble("y", 0); + double z = conf.getDouble("z", 0); + float yaw = (float) conf.getDouble("yaw", 0); + float pitch = (float) conf.getDouble("pitch", 0); + String world = conf.getString("world"); + World w = server.getWorld(world); + if (w == null) { + throw new Exception("World of warp does not exist."); + } + return new Location(w, x, y, z, yaw, pitch); + } + + public void setWarp(String name, Location loc) throws Exception { + setWarp(name, loc, null); + } + + private void setWarp(String name, Location loc, String worldName) throws Exception { + String filename = convertToFileName(name); + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + File confFile = new File(warpsFolder, filename + ".yml"); + if (confFile.exists()) { + throw new Exception("A warp with a similar name already exists."); + } + conf = new EssentialsConf(confFile); + conf.setProperty("name", name); + warpPoints.put(new StringIgnoreCase(name), conf); + } + conf.setProperty("x", loc.getBlockX()); + conf.setProperty("y", loc.getBlockY()); + conf.setProperty("z", loc.getBlockZ()); + conf.setProperty("yaw", loc.getYaw()); + conf.setProperty("pitch", loc.getPitch()); + if (worldName != null) { + conf.setProperty("world", worldName); + } else { + conf.setProperty("world", loc.getWorld().getName()); + } + conf.save(); + } + + public void delWarp(String name) throws Exception { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + throw new Exception("Warp does not exist."); + } + if (!conf.getFile().delete()) { + throw new Exception("Problem deleting the warp file."); + } + warpPoints.remove(new StringIgnoreCase(name)); + } + + private void convertWarps(File dataFolder) { + File[] listOfFiles = warpsFolder.listFiles(); + if (listOfFiles.length >= 1) { + for (int i = 0; i < listOfFiles.length; i++) { + String filename = listOfFiles[i].getName(); + if (listOfFiles[i].isFile() && filename.endsWith(".dat")) { + try { + BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i])); + double x = Double.parseDouble(rx.readLine().trim()); + double y = Double.parseDouble(rx.readLine().trim()); + double z = Double.parseDouble(rx.readLine().trim()); + float yaw = Float.parseFloat(rx.readLine().trim()); + float pitch = Float.parseFloat(rx.readLine().trim()); + String worldName = rx.readLine(); + rx.close(); + World w = null; + for (World world : server.getWorlds()) { + if (world.getEnvironment() != World.Environment.NETHER) { + w = world; + break; + } + } + boolean forceWorldName = false; + if (worldName != null) { + worldName.trim(); + World w1 = null; + for (World world : server.getWorlds()) { + if (world.getName().equalsIgnoreCase(worldName)) { + w1 = world; + break; + } + } + if (w1 != null) { + w = w1; + } else { + File worldFolder = new File(dataFolder.getAbsoluteFile().getParentFile().getParentFile(), worldName); + if (worldFolder.exists() && worldFolder.isDirectory()) { + logger.log(Level.WARNING, "World " + worldName + " not loaded, but directory found. Converting warp anyway."); + forceWorldName = true; + } + } + } + Location loc = new Location(w, x, y, z, yaw, pitch); + setWarp(filename.substring(0, filename.length() - 4), loc, forceWorldName ? worldName : null); + if(!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old"))) + { + throw new Exception("Renaming file " + filename + " failed"); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + + } + File warpFile = new File(dataFolder, "warps.txt"); + if (warpFile.exists()) { + try { + BufferedReader rx = new BufferedReader(new FileReader(warpFile)); + for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":")) { + if (parts.length < 6) { + continue; + } + String name = parts[0]; + double x = Double.parseDouble(parts[1].trim()); + double y = Double.parseDouble(parts[2].trim()); + double z = Double.parseDouble(parts[3].trim()); + float yaw = Float.parseFloat(parts[4].trim()); + float pitch = Float.parseFloat(parts[5].trim()); + if (name.isEmpty()) { + continue; + } + World w = null; + for (World world : server.getWorlds()) { + if (world.getEnvironment() != World.Environment.NETHER) { + w = world; + break; + } + } + Location loc = new Location(w, x, y, z, yaw, pitch); + setWarp(name, loc); + if(!warpFile.renameTo(new File(dataFolder, "warps.txt.old"))); + { + throw new Exception("Renaming warps.txt failed"); + } + } + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + + public final void reloadConfig() { + warpPoints.clear(); + File[] listOfFiles = warpsFolder.listFiles(); + if (listOfFiles.length >= 1) { + for (int i = 0; i < listOfFiles.length; i++) { + String filename = listOfFiles[i].getName(); + if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { + EssentialsConf conf = new EssentialsConf(listOfFiles[i]); + conf.load(); + String name = conf.getString("name"); + if (name != null) { + warpPoints.put(new StringIgnoreCase(name), conf); + } + } + } + } + } + + private class StringIgnoreCase { + + String string; + + public StringIgnoreCase(String string) { + this.string = string; + } + + @Override + public int hashCode() { + return string.toLowerCase().hashCode(); + } + + @Override + public boolean equals(Object o) { + if (o instanceof String) { + return string.equalsIgnoreCase((String) o); + } + if (o instanceof StringIgnoreCase) { + return string.equalsIgnoreCase(((StringIgnoreCase) o).string); + } + return false; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java new file mode 100644 index 000000000..eb1ade4cd --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandafk extends EssentialsCommand +{ + public Commandafk() + { + super("afk"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + + if (parent.away.contains(user)) + { + user.sendMessage("§7You are no longer marked as away."); + server.broadcastMessage("§7" + user.getDisplayName() + " is no longer AFK"); + parent.away.remove(user); + return; + } + + user.sendMessage("§7You are now marked as away."); + server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK"); + parent.away.add(user); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java new file mode 100644 index 000000000..9e234ea15 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java @@ -0,0 +1,39 @@ +package com.earth2me.essentials.commands; + +import net.minecraft.server.EntityTNTPrimed; +import net.minecraft.server.World; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.craftbukkit.CraftWorld; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.TargetBlock; + + +public class Commandantioch extends EssentialsCommand +{ + public Commandantioch() + { + super("antioch"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (!user.isOp()) + { + user.sendMessage("§cNone shall pass."); + return; + } + + server.broadcastMessage("...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); + server.broadcastMessage("who being naughty in My sight, shall snuff it."); + + Location loc = user.getLocation(); + World world = ((CraftWorld)user.getWorld()).getHandle(); + loc = new TargetBlock(user).getTargetBlock().getLocation(); + EntityTNTPrimed tnt = new EntityTNTPrimed(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + world.a(tnt); + world.a(tnt, "random.fuse", 1.0F, 1.0F); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java new file mode 100644 index 000000000..03ceba9b6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; + + +public class Commandback extends EssentialsCommand +{ + public Commandback() + { + super("back"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.canAfford(this); + user.sendMessage("§7Returning to previous location."); + user.teleportBack(this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java new file mode 100644 index 000000000..7682cd141 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -0,0 +1,43 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Backup; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +/** + * + * @author schlex + */ +public class Commandbackup extends EssentialsCommand { + + public Commandbackup() { + super("backup"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + Backup backup = Essentials.getStatic().backup; + if (backup == null) return; + backup.run(); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + Backup backup = Essentials.getStatic().backup; + if (backup == null) return; + user.charge(this); + backup.run(); + user.sendMessage("Backup started"); + } + + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java new file mode 100644 index 000000000..6789af570 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandbalance extends EssentialsCommand +{ + public Commandbalance() + { + super("balance"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.sendMessage("§7Balance: $" + (args.length < 1 || !user.isAuthorized("essentials.balance.other") + ? user + : getPlayer(server, args, 0)).getMoney()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java new file mode 100644 index 000000000..c341d4645 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandban extends EssentialsCommand +{ + public Commandban() + { + super("ban"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [player] <reason>"); + return; + } + + + User p = null; + if (server.matchPlayer(args[0]).isEmpty()) + { + ((CraftServer)server).getHandle().c.f.a(args[0]); + sender.sendMessage("§cPlayer" + args[0] + " banned"); + } + else + { + p = User.get(server.matchPlayer(args[0]).get(0)); + p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Banned from server"); + ((CraftServer)server).getHandle().c.f.a(p.getName()); + sender.sendMessage("§cPlayer" + p.getName() + " banned"); + } + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java new file mode 100644 index 000000000..080bfa663 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandbanip extends EssentialsCommand +{ + public Commandbanip() + { + super("banip"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [address]"); + return; + } + + ((CraftServer)server).getHandle().c.f.c(args[0]); + sender.sendMessage("§7Banned IP address."); + Essentials.getStatic().loadBanList(); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java new file mode 100644 index 000000000..a7546bb35 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java @@ -0,0 +1,56 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.TreeType; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Location; + + +public class Commandbigtree extends EssentialsCommand +{ + public Commandbigtree() + { + super("bigtree"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Object tree = new Object(); + if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.TALL_REDWOOD; + } + else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.BIG_TREE; + } + else + { + user.sendMessage("§cUsage: /" + commandLabel + " [tree|redwood]"); + return; + } + + double x = user.getLocation().getX(); + double y = user.getLocation().getY(); + double z = user.getLocation().getZ(); + + // offset tree in direction player is facing + int r = (int)user.getCorrectedYaw(); + if (r < 68 || r > 292) x -= 3.0D; // north + else if (r > 112 && r < 248) x += 3.0D; // south + if (r > 22 && r < 158) z -= 3.0D; // east + else if (r > 202 && r < 338) z += 3.0D; // west + + Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); + boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); + if (success) + { + user.charge(this); + user.sendMessage("Big tree spawned."); + } + else + user.sendMessage("§cBig tree generation failure. Try again on grass or dirt."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java new file mode 100644 index 000000000..2069e61b9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandbroadcast extends EssentialsCommand +{ + public Commandbroadcast() + { + super("broadcast"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("Usage: /" + commandLabel + " [msg]"); + } + + StringBuilder message = new StringBuilder(); + for (int i = 0; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + + server.broadcastMessage("[§cBroadcast§f]§a " + message.toString()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java new file mode 100644 index 000000000..0c190a0f2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.entity.Player; + +public class Commandburn extends EssentialsCommand +{ + + public Commandburn() + { + super("burn"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + user.sendMessage("§cUsage: /burn [player] [seconds]"); + return; + } + + User.charge(user, this); + for (Player p : server.matchPlayer(args[0])) + { + p.setFireTicks(Integer.parseInt(args[1]) * 20); + user.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java new file mode 100644 index 000000000..de5c11376 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -0,0 +1,99 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import java.util.List; +import org.bukkit.ChatColor; + + +public class Commandclearinventory extends EssentialsCommand +{ + public Commandclearinventory() + { + super("clearinventory"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others")) + { + if (args[0].length() >= 3) + { + List<Player> online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared."); + user.charge(this); + } + } + throw new Exception("Player not found"); + } + else + { + Player u = server.getPlayer(args[0]); + if (u != null) + { + u.getInventory().clear(); + user.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared."); + user.charge(this); + } + else + { + throw new Exception("Player not found"); + } + } + } + else + { + user.getInventory().clear(); + user.sendMessage("§7Inventory cleared."); + user.charge(this); + } + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage(ChatColor.RED + "Usage: " + commandLabel + " [player]"); + return; + } + + if (args[0].length() >= 3) + { + List<Player> online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + sender.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared."); + } + } + throw new Exception("Player not found"); + } + else + { + Player u = server.getPlayer(args[0]); + if (u != null) + { + u.getInventory().clear(); + sender.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared."); + } + else + { + throw new Exception("Player not found"); + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java new file mode 100644 index 000000000..f891f0bab --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandcompass extends EssentialsCommand +{ + public Commandcompass() + { + super("compass"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + int r = (int)user.getCorrectedYaw(); + String dir; + if (r < 23) dir = "N"; + else if (r < 68) dir = "NE"; + else if (r < 113) dir = "E"; + else if (r < 158) dir = "SE"; + else if (r < 203) dir = "S"; + else if (r < 248) dir = "SW"; + else if (r < 293) dir = "W"; + else if (r < 338) dir = "NW"; + else dir = "N"; + user.sendMessage("§7Bearing: " + dir + " (" + r + " degrees)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java new file mode 100644 index 000000000..620db000c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +public class Commanddeljail extends EssentialsCommand { + + public Commanddeljail() { + super("deljail"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); + return; + } + user.charge(this); + Essentials.getJail().delJail(args[0]); + user.sendMessage("§7Jail " + args[0] + " has been removed"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + super.run(server, parent, sender, commandLabel, args); + } + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java new file mode 100644 index 000000000..a9811fb8e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commanddelwarp extends EssentialsCommand +{ + public Commanddelwarp() + { + super("delwarp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [warp name]"); + return; + } + user.charge(this); + Essentials.getWarps().delWarp(args[0]); + user.sendMessage("§7Warp removed."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [warp name]"); + return; + } + + Essentials.getWarps().delWarp(args[0]); + sender.sendMessage("§7Warp removed."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java new file mode 100644 index 000000000..d01594809 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java @@ -0,0 +1,24 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commanddepth extends EssentialsCommand +{ + public Commanddepth() + { + super("depth"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + int y = user.getLocation().getBlockY() - 63; + if (y > 0) user.sendMessage("§7You are " + y + " block(s) above sea level."); + else if (y < 0) user.sendMessage("§7You are " + (-y) + " block(s) below sea level."); + else user.sendMessage("§7You are at sea level."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java new file mode 100644 index 000000000..79a55f986 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -0,0 +1,82 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandeco extends EssentialsCommand +{ + public Commandeco() + { + super("eco"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + EcoCommands cmd; + int amount; + try + { + cmd = EcoCommands.valueOf(args[0].toUpperCase()); + amount = Integer.parseInt(args[2].replaceAll("[^0-9]", "")); + } + catch (Exception ex) + { + sender.sendMessage("§cUsage: /eco [give|take|reset] [player] [money]"); + return; + } + + if (args[1].contentEquals("*")) + { + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + switch (cmd) + { + case GIVE: + u.giveMoney(amount); + break; + + case TAKE: + u.takeMoney(amount); + break; + + case RESET: + u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); + break; + } + } + } + else + { + for (Player p : server.matchPlayer(args[1])) + { + User u = User.get(p); + switch (cmd) + { + case GIVE: + u.giveMoney(amount); + break; + + case TAKE: + u.takeMoney(amount); + break; + + case RESET: + u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); + break; + } + } + } + } + + + private enum EcoCommands + { + GIVE, TAKE, RESET + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java new file mode 100644 index 000000000..d4cc4038d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandessentials extends EssentialsCommand +{ + public Commandessentials() + { + super("essentials"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + parent.reload(); + user.charge(this); + user.sendMessage("§7Essentials Reloaded " + parent.getDescription().getVersion()); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + parent.reload(); + sender.sendMessage("Essentials Reloaded " + parent.getDescription().getVersion()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java new file mode 100644 index 000000000..1313ba5b9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandext.java @@ -0,0 +1,29 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.entity.Player; + +public class Commandext extends EssentialsCommand { + + public Commandext() { + super("ext"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + if (args.length < 1) { + User.charge(user, this); + user.setFireTicks(0); + user.sendMessage("§7You extinguished yourself."); + return; + } + + for (Player p : server.matchPlayer(args[0])) { + User.charge(user, this); + p.setFireTicks(0); + user.sendMessage("§7You extinguished " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java new file mode 100644 index 000000000..08640e15b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -0,0 +1,29 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; + + +public class Commandgc extends EssentialsCommand +{ + public Commandgc() + { + super("gc"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + sender.sendMessage("Maximum memory: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB"); + sender.sendMessage("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " MB"); + for (World w : parent.getServer().getWorlds()) + { + sender.sendMessage( + (w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": " + + w.getLoadedChunks().length + " chunks, " + + w.getEntities().size() + " entities"); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java new file mode 100644 index 000000000..39be2c524 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandgetpos extends EssentialsCommand +{ + public Commandgetpos() + { + super("getpos"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "coords" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + Location coords = user.getLocation(); + user.sendMessage("§7X: " + coords.getBlockX() + " (-North <-> +South)"); + user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)"); + user.sendMessage("§7Z: " + coords.getBlockZ() + " (+East <-> -West)"); + user.sendMessage("§7Yaw: " + user.getCorrectedYaw() + " (Rotation)"); + user.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java new file mode 100644 index 000000000..559fc5c32 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -0,0 +1,49 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class Commandgive extends EssentialsCommand +{ + public Commandgive() + { + super("give"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] [item]<:data> <amount>"); + return; + } + + String[] itemArgs = args[1].split("[^a-zA-Z0-9]"); + ItemStack stack = ItemDb.get(itemArgs[0]); + + if(sender instanceof Player && !User.get(sender).isAuthorized("essentials.itemspawn.exempt") && !User.get(sender).canSpawnItem(stack.getTypeId())) + { + sender.sendMessage(ChatColor.RED + "You are not allowed to spawn that item"); + return; + } + if (itemArgs.length > 1) + stack.setDurability(Short.parseShort(itemArgs[1])); + if (args.length > 2) + stack.setAmount(Integer.parseInt(args[2])); + + User giveTo = getPlayer(server, args, 0); + String itemName = stack.getType().name().toLowerCase().replace('_', ' '); + if (sender instanceof Player) + User.get(sender).charge(this); + sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); + giveTo.getInventory().addItem(stack); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java new file mode 100644 index 000000000..700be8c88 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.entity.Player; + + +public class Commandgod extends EssentialsCommand +{ + public Commandgod() + { + super("god"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && (user.isAuthorized("essentials.god.others") || user.isOp())) + { + for (Player p : server.matchPlayer(args[0])) + { + User u = User.get(p); + boolean enabled = u.toggleGodMode(); + u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled.")); + user.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + "."); + } + return; + } + user.sendMessage("§7God mode " + (user.toggleGodMode() ? "enabled." : "disabled.")); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java new file mode 100644 index 000000000..ddadda860 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -0,0 +1,53 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandheal extends EssentialsCommand +{ + public Commandheal() + { + super("heal"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && user.isAuthorized("essentials.heal.others")) + { + if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); + user.charge(this); + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(20); + user.sendMessage("§7Healed " + p.getDisplayName() + "."); + } + return; + } + + if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); + user.charge(this); + user.setHealth(20); + user.sendMessage("§7You have been healed."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player]"); + return; + } + + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(20); + sender.sendMessage("Healed " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java new file mode 100644 index 000000000..1468cced5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java @@ -0,0 +1,129 @@ +package com.earth2me.essentials.commands; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandhelp extends EssentialsCommand +{ + public final Yaml yaml = new Yaml(new SafeConstructor()); + + public Commandhelp() + { + super("help"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + int page; + try + { + page = args.length > 0 ? Integer.parseInt(args[0]) : 1; + } + catch (Exception ex) + { + page = 1; + } + + List<String> lines = getHelpLines(parent, user); + int start = (page - 1) * 9; + int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); + + user.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:"); + for (int i = start; i < lines.size() && i < start + 9; i++) + { + user.sendMessage(lines.get(i)); + } + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + sender.sendMessage("To view help from the console, type \"?\"."); + } + + @SuppressWarnings("CallToThreadDumpStack") + private List<String> getHelpLines(Essentials parent, User user) throws Exception + { + List<String> retval = new ArrayList<String>(); + File file = new File(parent.getDataFolder(), "help.txt"); + if (file.exists()) + { + BufferedReader rx = new BufferedReader(new FileReader(file)); + for (String l = null; rx.ready() && (l = rx.readLine()) != null;) + { + retval.add(l.replace('&', '§')); + } + return retval; + } + + boolean reported = false; + for (Plugin p : parent.getServer().getPluginManager().getPlugins()) + { + try + { + PluginDescriptionFile desc = p.getDescription(); + HashMap<String, HashMap<String, String>> cmds = (HashMap<String, HashMap<String, String>>)desc.getCommands(); + for (String k : cmds.keySet()) + { + if (p.getDescription().getName().toLowerCase().contains("essentials")) + { + String node = "essentials." + k; + if (!Essentials.getSettings().isCommandDisabled(k) && user.isAuthorized(node)) + { + HashMap<String, String> v = cmds.get(k); + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + else + { + if (Essentials.getSettings().showNonEssCommandsInHelp()) + { + HashMap<String, String> v = cmds.get(k); + if (v.containsKey("permission") && v.get("permission") != null && !(v.get("permission").equals(""))) + { + if (user.isAuthorized(v.get("permission"))) + { + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + else + { + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + + } + } + } + catch (NullPointerException ex) + { + + continue; + } + catch (Exception ex) + { + if (!reported) + { + ex.printStackTrace(); + } + reported = true; + continue; + } + } + return retval; + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java new file mode 100644 index 000000000..03dbad50e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandhelpop extends EssentialsCommand +{ + public Commandhelpop() + { + super("helpop"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cTo request help from an op, type §f/" + commandLabel+ "§c, followed by your question."); + return; + } + + user.charge(this); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + if (!u.isOp() && !u.isAuthorized("essentials.helpop.receive")) continue; + u.sendMessage("§c[HelpOp]§f §7" + user.getDisplayName() + ":§f " + getFinalArg(args, 0)); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java new file mode 100644 index 000000000..0dc92d25a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandhome extends EssentialsCommand +{ + public Commandhome() + { + super("home"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.canAfford(this); + user.teleportCooldown(); + user.teleportToHome(this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java new file mode 100644 index 000000000..2e7ec407a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -0,0 +1,39 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.craftbukkit.inventory.CraftInventory; + +public class Commandinvsee extends EssentialsCommand { + + public Commandinvsee() { + super("invsee"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + + if (args.length == 0 && user.savedInventory == null) { + user.sendMessage("§cUsage: /" + commandLabel + " <user>"); + } + User invUser = user; + if (args.length == 1) { + invUser = getPlayer(server, args, 0); + } + if (invUser == user && user.savedInventory != null) { + ((CraftInventory)invUser.getInventory()).setContents(user.savedInventory); + user.savedInventory = null; + user.sendMessage("Your inventory has been restored."); + return; + } + + user.charge(this); + if (user.savedInventory == null) { + user.savedInventory = ((CraftInventory)user.getInventory()).getContents(); + } + ((CraftInventory)user.getInventory()).setContents(((CraftInventory)invUser.getInventory()).getContents()); + user.sendMessage("You see the inventory of "+invUser.getDisplayName()+"."); + user.sendMessage("Use /invsee to restore your inventory."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java new file mode 100644 index 000000000..97d1d2218 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + + +public class Commanditem extends EssentialsCommand +{ + public Commanditem() + { + super("item"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [item] <amount>"); + return; + } + String[] itemArgs = args[0].split("[^a-zA-Z0-9]"); + ItemStack stack = ItemDb.get(itemArgs[0]); + + if(!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId())) + { + user.sendMessage(ChatColor.RED + "You are not allowed to spawn that item"); + return; + } + if (itemArgs.length > 1) + stack.setDurability(Short.parseShort(itemArgs[1])); + + if (args.length > 1) + stack.setAmount(Integer.parseInt(args[1])); + + String itemName = stack.getType().name().toLowerCase().replace('_', ' '); + user.charge(this); + user.sendMessage("§7Giving " + stack.getAmount() + " of " + itemName + " to " + user.getDisplayName() + "."); + user.getInventory().addItem(stack); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java new file mode 100644 index 000000000..75018eb19 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +public class Commandjails extends EssentialsCommand { + + public Commandjails() { + super("jails"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + StringBuilder jailList = new StringBuilder(); + for (String j : Essentials.getJail().getJails()) + { + jailList.append(j); + jailList.append(' '); + } + sender.sendMessage("§7" + jailList); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + StringBuilder jailList = new StringBuilder(); + for (String j : Essentials.getJail().getJails()) + { + jailList.append(j); + jailList.append(' '); + } + user.sendMessage("§7" + jailList); + } + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java new file mode 100644 index 000000000..b26ffd82a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -0,0 +1,50 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.TargetBlock; +import com.earth2me.essentials.User; + + +public class Commandjump extends EssentialsCommand +{ + public Commandjump() + { + super("jump"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "j" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Location loc; + Location cloc = user.getLocation(); + + try + { + loc = new TargetBlock(user, 100, 2.65).getTargetBlock().getLocation(); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc = new TargetBlock(loc).getPreviousBlock().getLocation(); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc.setY(loc.getY() + 1); + } + catch (NullPointerException ex) + { + throw new Exception("That would hurt your computer's brain.", ex); + } + + user.canAfford(this); + user.teleportTo(loc, this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java new file mode 100644 index 000000000..ddf5de5f5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; + + +public class Commandkick extends EssentialsCommand +{ + public Commandkick() + { + super("kick"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] <reason>"); + return; + } + + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Throwable ex) + { + sender.sendMessage(ChatColor.RED + "That player does not exist!"); + return; + } + + charge(sender); + p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server"); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java new file mode 100644 index 000000000..e73f57a00 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -0,0 +1,55 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandkickall extends EssentialsCommand +{ + public Commandkickall() + { + super("kickall"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§7Usage: /" + commandLabel + "<reason>"); + return; + } + + + for (Player p : server.getOnlinePlayers()) + { + if (server.getOnlinePlayers().length == 1 && p.getName().equalsIgnoreCase(user.getName())) + { + user.sendMessage("§7Only you online..."); + return; + } + else + { + if (!p.getName().equalsIgnoreCase(user.getName())) + { + p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); + } + } + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + "<reason>"); + return; + } + + for (Player p : server.getOnlinePlayers()) + p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java new file mode 100644 index 000000000..ef5315c85 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandkill extends EssentialsCommand +{ + public Commandkill() + { + super("kill"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /kill [player]"); + return; + } + + User.charge(sender, this); + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(0); + sender.sendMessage("§cKilled " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java new file mode 100644 index 000000000..eb251b06b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -0,0 +1,150 @@ +package com.earth2me.essentials.commands; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.inventory.ItemStack; + + +public class Commandkit extends EssentialsCommand +{ + static private final Map<User, Map<String, Long>> kitPlayers = new HashMap<User, Map<String, Long>>(); + + public Commandkit() + { + super("kit"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + try + { + Map<String, Object> kits = (Map<String, Object>)parent.getConfiguration().getProperty("kits"); + StringBuilder list = new StringBuilder(); + for (String k : kits.keySet()) + { + if (user.isAuthorized("essentials.kit." + k)) + { + list.append(" ").append(k); + } + } + if (list.length() > 0) + { + user.sendMessage("§7Kits:" + list.toString()); + } + else + { + user.sendMessage("§7There are no kits available yet"); + } + } + catch (Exception ex) + { + user.sendMessage("§cThere are no valid kits."); + } + } + else + { + try + { + String kitName = args[0].toLowerCase(); + Object kit = Essentials.getSettings().getKit(kitName); + List<String> items; + + if (!user.isAuthorized("essentials.kit." + kitName)) + { + user.sendMessage("§cYou need the §fessentials.kit." + kitName + "§c permission to use that kit."); + return; + } + + try + { + + System.out.println("Kit is timed"); + Map<String, Object> els = (Map<String, Object>)kit; + items = (List<String>)els.get("items"); + long delay = els.containsKey("delay") ? (Integer)els.get("delay") * 1000L : 0L; + long time = Calendar.getInstance().getTimeInMillis(); + + Map<String, Long> kitTimes; + if (!kitPlayers.containsKey(user)) + { + kitTimes = new HashMap<String, Long>(); + kitTimes.put(kitName, time); + kitPlayers.put(user, kitTimes); + } + else + { + kitTimes = kitPlayers.get(user); + if (!kitTimes.containsKey(kitName)) + { + kitTimes.put(kitName, time); + } + else if (kitTimes.get(kitName) + delay <= time) + { + kitTimes.put(kitName, time); + } + else + { + long left = kitTimes.get(kitName) + delay - time; + user.sendMessage("§cYou can't use that kit again for another " + Essentials.FormatTime(left) + "."); + + return; + } + } + } + catch (Exception ex) + { + items = (List<String>)kit; + } + + try { + user.canAfford("kit-" + kitName); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + return; + } + + boolean spew = false; + for (String d : items) + { + String[] parts = d.split("[^0-9]+", 3); + int id = Integer.parseInt(parts[0]); + int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1; + short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0; + if(user.getInventory().firstEmpty() != -1) + { + user.getInventory().addItem(new ItemStack(id, amount, data)); + } + else + { + spew = true; + user.getWorld().dropItemNaturally(user.getLocation(), new ItemStack(id, amount, data)); + } + } + if(spew) + { + user.sendMessage("§7Your inventory was full, placing kit on the floor"); + } + try { + user.charge(this); + user.charge("kit-" + kitName); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + } + user.sendMessage("§7Giving kit " + args[0].toLowerCase() + "."); + } + catch (Exception ex) + { + user.sendMessage("§cThat kit does not exist or is improperly defined."); + user.sendMessage("§cPerhaps an item is missing a quantity in the configuration?"); + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java new file mode 100644 index 000000000..aeef26ac7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -0,0 +1,93 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.ChatColor; + + +public class Commandlist extends EssentialsCommand +{ + public Commandlist() + { + super("list"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + User.charge(sender, this); + StringBuilder online = new StringBuilder(); + online.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(server.getOnlinePlayers().length); + online.append(ChatColor.BLUE).append(" out of a maximum ").append(ChatColor.RED).append(server.getMaxPlayers()); + online.append(ChatColor.BLUE).append(" players online."); + sender.sendMessage(online.toString()); + + if (Essentials.getSettings().getSortListByGroups()) { + Map<String, List<User>> sort = new HashMap<String, List<User>>(); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String group = u.getGroup(); + List<User> list = sort.get(group); + if (list == null) { + list = new ArrayList<User>(); + sort.put(group, list); + } + list.add(u); + } + String[] groups = sort.keySet().toArray(new String[0]); + Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER); + for (String group : groups) { + StringBuilder groupString = new StringBuilder(); + groupString.append(group).append(": "); + List<User> users = sort.get(group); + Collections.sort(users); + boolean first = true; + for (User user : users) { + if (!first) { + groupString.append(", "); + } else { + first = false; + } + if (parent.away.contains(user)) { + groupString.append("§7[AFK]"); + } + groupString.append(user.getDisplayName()); + } + sender.sendMessage(groupString.toString()); + } + } else { + List<User> users = new ArrayList<User>(); + for (Player p : server.getOnlinePlayers()) + { + users.add(User.get(p)); + } + Collections.sort(users); + + StringBuilder onlineUsers = new StringBuilder(); + onlineUsers.append("Connected players: "); + boolean first = true; + for (User user : users) { + if (!first) { + onlineUsers.append(", "); + } else { + first = false; + } + if (parent.away.contains(user)) { + onlineUsers.append("§7[AFK]"); + } + onlineUsers.append(user.getDisplayName()); + } + sender.sendMessage(onlineUsers.toString()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java new file mode 100644 index 000000000..3e55c982d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -0,0 +1,52 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandmail extends EssentialsCommand +{ + public Commandmail() + { + super("mail"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) + { + List<String> mail = Essentials.readMail(user); + if (mail.isEmpty()) + { + user.sendMessage("§cYou do not have any mail!"); + return; + } + for (String s : mail) user.sendMessage(s); + user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); + return; + } + if(args.length >= 3 && "send".equalsIgnoreCase(args[0])) + { + if (!user.isAuthorized("essentials.mail.send")) + { + user.sendMessage("§cYou do not have the §fessentials.mail.send§c permission."); + return; + } + + user.charge(this); + Essentials.sendMail(user, args[1], getFinalArg(args, 2)); + user.sendMessage("§7Mail sent!"); + return; + } + if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) + { + Essentials.clearMail(user); + user.sendMessage("§7Mail cleared!"); + return; + } + user.sendMessage("§7Usage: /mail [read|clear|send [to] [message]]"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandme.java b/Essentials/src/com/earth2me/essentials/commands/Commandme.java new file mode 100644 index 000000000..cd0a6b013 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.java @@ -0,0 +1,38 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandme extends EssentialsCommand +{ + public Commandme() + { + super("me"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "describe", "action" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /me [description]"); + return; + } + StringBuilder message = new StringBuilder(); + for (int i = 0; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + user.charge(this); + server.broadcastMessage("* " + user.getDisplayName() + " " + message); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java new file mode 100644 index 000000000..652310e36 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -0,0 +1,25 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + + +public class Commandmotd extends EssentialsCommand +{ + public Commandmotd() + { + super("motd"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + User.charge(sender, this); + for (String m : parent.getMotd(sender, "§cThere is no message of the day.")) + { + sender.sendMessage(m); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java new file mode 100644 index 000000000..8b02bbf19 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -0,0 +1,85 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + +public class Commandmsg extends EssentialsCommand +{ + public Commandmsg() + { + super("msg"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "m", "tell", "whisper" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0) + { + user.sendMessage("§cUsage: /" + commandLabel + " [player] [message]"); + return; + } + + StringBuilder message = new StringBuilder(); + for (int i = 1; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + + List<Player> matches = server.matchPlayer(args[0]); + + if (matches.isEmpty()) + { + user.sendMessage("§cThere are no players matching that name."); + return; + } + + user.charge(this); + for (Player p : matches) + { + user.sendMessage("[Me -> " + p.getDisplayName() + "§f] " + message); + p.sendMessage("[" + user.getDisplayName() + " -> Me§f] " + message); + user.setReplyTo(User.get(p)); + User.get(p).setReplyTo(user); + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [player] [message]"); + return; + } + + StringBuilder message = new StringBuilder(); + for (int i = 1; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + List<Player> matches = server.matchPlayer(args[0]); + + if (matches.isEmpty()) + { + sender.sendMessage("§cThere are no players matching that name."); + } + + for (Player p : matches) + { + sender.sendMessage("[§2Me -> " + p.getDisplayName() + "§f] " + message); + p.sendMessage("[§2{Console} -> Me§f] " + message); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java new file mode 100644 index 000000000..30164e25d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -0,0 +1,64 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandmute extends EssentialsCommand +{ + public Commandmute() + { + super("kick"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§7Usage: /" + commandLabel + " [player] <reason>"); + return; + } + + String[] sects2 = args[0].split(" +"); + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + user.sendMessage("§cThat player does not exist!"); + return; + } + + user.sendMessage("§7Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted.")); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player] <reason>"); + return; + } + + String[] sects2 = args[0].split(" +"); + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + sender.sendMessage("§cThat player does not exist!"); + return; + } + + sender.sendMessage("Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted.")); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java new file mode 100644 index 000000000..fb65539b6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -0,0 +1,129 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandnick extends EssentialsCommand +{ + public Commandnick() + { + super("nick"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " <target> [nickname]"); + return; + } + + if (args.length > 1) + { + if (!user.isOp()) + { + user.sendMessage("§cOnly operators can change the nicknames of other users."); + return; + } + + List<Player> matches = server.matchPlayer(args[0]); + if (matches.isEmpty()) + { + user.sendMessage("§cThat player does not exist."); + return; + } + + User target = User.get(matches.get(0)); + String nick = args[1]; + if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) + { + target.setDisplayName(target.getName()); + parent.saveNickname(target, target.getName()); + target.sendMessage("§7You no longer have a nickname."); + } + else + { + user.charge(this); + target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(target, nick); + target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7."); + } + user.sendMessage("§7Nickname changed."); + } + else + { + String nick = args[0]; + if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick)) + { + user.setDisplayName(user.getName()); + parent.saveNickname(user, user.getName()); + user.sendMessage("§7You no longer have a nickname."); + } + else + { + if (nick.matches("[^a-zA-Z_0-9]")) + { + user.sendMessage("§cNicknames must be alphanumeric."); + return; + } + + for (Player p : server.getOnlinePlayers()) + { + if (user == p) continue; + String dn = p.getDisplayName().toLowerCase(); + String n = p.getName().toLowerCase(); + String nk = nick.toLowerCase(); + if (nk.equals(dn) || nk.equals(n)) + { + user.sendMessage("§cThat name is already in use."); + return; + } + } + + user.charge(this); + user.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(user, nick); + user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7."); + } + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [target] [nickname]"); + return; + } + + List<Player> matches = server.matchPlayer(args[0]); + if (matches.isEmpty()) + { + sender.sendMessage("That player does not exist."); + return; + } + + User target = User.get(matches.get(0)); + String nick = args[1]; + if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) + { + target.setDisplayName(target.getName()); + parent.saveNickname(target, target.getName()); + target.sendMessage("§7You no longer have a nickname."); + } + else + { + target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(target, nick); + target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7."); + } + sender.sendMessage("Nickname changed."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java new file mode 100644 index 000000000..dc6ab3ac3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandnuble extends EssentialsCommand +{ + public Commandnuble() + { + super("nuble"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.sendMessage("§7Flight is allowed on this server."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java new file mode 100644 index 000000000..085f8febe --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandpay extends EssentialsCommand +{ + public Commandpay() + { + super("pay"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + + int amount; + try + { + amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + } + catch (Exception ex) + { + user.sendMessage("§cUsage: /" + commandLabel + " [player] [money]"); + return; + } + + for (Player p : server.matchPlayer(args[0])) + { + User u = User.get(p); + user.payUser(u, amount); + } + } + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandping.java b/Essentials/src/com/earth2me/essentials/commands/Commandping.java new file mode 100644 index 000000000..36d8e33c3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandping.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandping extends EssentialsCommand +{ + public Commandping() + { + super("ping"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pong" }; + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + player.sendMessage("Pong!"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java new file mode 100644 index 000000000..df1ecdaad --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java @@ -0,0 +1,161 @@ +package com.earth2me.essentials.commands; + +import java.io.File; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + + +public class Commandplugin extends EssentialsCommand +{ + private Server server; + + public Commandplugin() + { + super("plugin"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + this.server = server; + + PluginCommands sub = null; + try + { + sub = PluginCommands.valueOf(args[0].toUpperCase()); + } + catch (Exception ex) + { + sender.sendMessage("§cUsage: /plugin [load|reload|enable|disable|list] [PluginName]"); + return; + } + + switch (sub) + { + case LOAD: + if (args.length < 2) return; + User.charge(sender, this); + loadPlugin(args[1], sender); + return; + + case RELOAD: + if (args.length < 2) return; + User.charge(sender, this); + reloadPlugin(args[1], sender); + return; + + case ENABLE: + if (args.length < 2) return; + User.charge(sender, this); + enablePlugin(args[1], sender); + return; + + case DISABLE: + if (args.length < 2) return; + User.charge(sender, this); + disablePlugin(args[1], sender); + return; + + case LIST: + User.charge(sender, this); + listPlugins(sender); + return; + } + } + + private void listPlugins(CommandSender player) + { + StringBuilder plugins = new StringBuilder(); + for (Plugin p : server.getPluginManager().getPlugins()) + { + plugins.append(p.isEnabled() ? " §a" : " §c"); + plugins.append(p.getDescription().getName()); + } + + plugins.insert(0, "§7Plugins:§f"); + player.sendMessage(plugins.toString()); + } + + private boolean reloadPlugin(String name, CommandSender player) + { + return disablePlugin(name, player) && enablePlugin(name, player); + } + + private boolean loadPlugin(String name, CommandSender sender) + { + try + { + PluginManager pm = server.getPluginManager(); + pm.loadPlugin(new File("plugins", name + ".jar")); + sender.sendMessage("§7Plugin loaded."); + return enablePlugin(name, sender); + } + catch (Throwable ex) + { + sender.sendMessage("§cCould not load plugin. Is the file named properly?"); + return false; + } + } + + private boolean enablePlugin(String name, CommandSender sender) + { + try + { + final PluginManager pm = server.getPluginManager(); + final Plugin plugin = pm.getPlugin(name); + if (!plugin.isEnabled()) new Thread(new Runnable() + { + public void run() + { + synchronized (pm) + { + pm.enablePlugin(plugin); + } + } + }).start(); + sender.sendMessage("§7Plugin enabled."); + return true; + } + catch (Throwable ex) + { + listPlugins(sender); + return false; + } + } + + private boolean disablePlugin(String name, CommandSender sender) + { + try + { + final PluginManager pm = server.getPluginManager(); + final Plugin plugin = pm.getPlugin(name); + if (plugin.isEnabled()) new Thread(new Runnable() + { + public void run() + { + synchronized (pm) + { + pm.disablePlugin(plugin); + } + } + }).start(); + sender.sendMessage("§7Plugin disabled."); + return true; + } + catch (Throwable ex) + { + listPlugins(sender); + return false; + } + } + + + private enum PluginCommands + { + LOAD, RELOAD, LIST, ENABLE, DISABLE + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java new file mode 100644 index 000000000..9bc7f2f97 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.*; +import org.bukkit.*; + + +public class Commandr extends EssentialsCommand +{ + public Commandr() + { + super("r"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [message]"); + return; + } + + String message = getFinalArg(args, 0); + User target = user.getReplyTo(); + + if (target == null) + { + user.sendMessage("§cYou have nobody to whom you can reply."); + } + + user.charge(this); + user.sendMessage("[Me -> " + target.getDisplayName() + "] " + message); + target.sendMessage("[" + user.getDisplayName() + " -> Me] " + message); + user.setReplyTo(target); + target.setReplyTo(user); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java new file mode 100644 index 000000000..6bec3f633 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -0,0 +1,40 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandrealname extends EssentialsCommand +{ + public Commandrealname() + { + super("realname"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "realnick" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /whois [nickname]"); + return; + } + String whois = args[0].toLowerCase(); + user.charge(this); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String dn = u.getDisplayName().toLowerCase(); + if (!whois.equals(dn) && !whois.equals(parent.getSettings().getNicknamePrefix() + dn) && !whois.equals(u.getName().toLowerCase())) continue; + user.sendMessage(u.getDisplayName() + " is " + u.getName()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java b/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java new file mode 100644 index 000000000..c677bc1c6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandreloadall extends EssentialsCommand +{ + + public Commandreloadall() + { + super("reloadall"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "rel", "pr" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + server.reload(); + user.sendMessage("§7Reloaded all plugins."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + server.reload(); + sender.sendMessage("Reloaded all plugins."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java new file mode 100644 index 000000000..e94b98755 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.*; + + +public class Commandrules extends EssentialsCommand +{ + public Commandrules() + { + super("rules"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + for (String m : parent.getLines(user, "rules", "§cThere are no rules specified yet.")) + { + user.sendMessage(m); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java new file mode 100644 index 000000000..11ce4ba6d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -0,0 +1,63 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class Commandsell extends EssentialsCommand +{ + public Commandsell() + { + super("sell"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + ItemStack is = user.getInventory().getItemInHand(); + if(is.getType() == Material.AIR) + throw new Exception("You really tried to sell Air? Put an item in your hand."); + + int id = is.getTypeId(); + int amount = 0; + if (args.length > 0) amount = Integer.parseInt(args[0].replaceAll("[^0-9]", "")); + int worth = parent.getConfiguration().getInt("worth-" + id, 0); + boolean stack = args.length > 0 && args[0].endsWith("s"); + boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); + + if (worth < 1) throw new Exception("That item cannot be sold to the server."); + if (requireStack && !stack) throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); + + int max = 0; + for (ItemStack s : user.getInventory().all(is).values()) + { + max += s.getAmount(); + } + + if (stack) amount *= 64; + if (amount < 1) amount += max; + + if (requireStack) + { + amount -= amount % 64; + } + + if (amount > max || amount < 1) + { + user.sendMessage("§cYou do not have enough of that item to sell."); + user.sendMessage("§7If you meant to sell all of your items of that type, use /sell without parameters."); + user.sendMessage("§7/sell -1 will sell all but one item, etc."); + return; + } + + user.charge(this); + user.getInventory().removeItem(new ItemStack(id, amount)); + user.updateInventory(); + user.giveMoney(worth * amount); + user.sendMessage("§7Sold for §c$" + (worth * amount) + "§7 (" + amount + " items at $" + worth + " each)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java new file mode 100644 index 000000000..f4729ead8 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsethome extends EssentialsCommand +{ + public Commandsethome() + { + super("sethome"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.setHome(); + user.charge(this); + user.sendMessage("§7Home set."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java new file mode 100644 index 000000000..f5c330188 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java @@ -0,0 +1,28 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsetjail extends EssentialsCommand +{ + public Commandsetjail() + { + super("setjail"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); + return; + } + user.charge(this); + Essentials.getJail().setJail(user.getLocation(), args[0]); + user.sendMessage("§7Jail " + args[0] + " has been set"); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java new file mode 100644 index 000000000..e510a8f73 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsetwarp extends EssentialsCommand +{ + public Commandsetwarp() + { + super("setwarp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /setwarp [warp name]"); + return; + } + + user.charge(this); + Location loc = user.getLocation(); + Essentials.getWarps().setWarp(args[0], loc); + user.sendMessage("§7Warp set."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java new file mode 100644 index 000000000..d73c0b843 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.block.Block; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.CreatureType; + +public class Commandspawner extends EssentialsCommand +{ + public Commandspawner() + { + super("spawner"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [mob]"); + return; + } + + Block target = user.getTarget().getTargetBlock(); + if (target.getType() != Material.MOB_SPAWNER) + throw new Exception("Target block must be a mob spawner."); + + try + { + ((CreatureSpawner)target).setCreatureType(CreatureType.fromName(args[0])); + } + catch (Throwable ex) + { + + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java new file mode 100644 index 000000000..c1c883a75 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -0,0 +1,188 @@ +package com.earth2me.essentials.commands; + +import net.minecraft.server.WorldServer; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftEntity; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.Mob; +import com.earth2me.essentials.Mob.MobException; +import com.earth2me.essentials.TargetBlock; + + +public class Commandspawnmob extends EssentialsCommand +{ + public Commandspawnmob() + { + super("spawnmob"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "mob" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /spawnmob [mob]<,mount><:size> <quantity>"); + user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep"); + return; + } + + String[] split1 = args[0].split(":"); + String[] split0 = null; + CraftEntity spawned1 = null; + Mob mob2 = null; + if (split1.length == 1 && !split1[0].equalsIgnoreCase("Slime")) + { + split0 = args[0].split(","); + split1[0] = split0[0]; + } + if (split1.length == 2) + { + args[0] = split1[0] + ""; + } + Mob mob = Mob.fromName(split1[0].equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(split1[0])); + if (mob == null) + { + user.sendMessage("Invalid mob type."); + return; + } + WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)user.getWorld()).getHandle(); + CraftEntity spawned = null; + try + { + spawned = mob.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + int[] ignore = {8, 9}; + Location loc = (new TargetBlock(user, 300, 0.2, ignore)).getTargetBlock().getLocation(); + int blkId = user.getWorld().getBlockTypeIdAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + while (!(blkId == 0 || blkId == 8 || blkId == 9)) + { + loc.setY(loc.getY() + 1); + blkId = user.getWorld().getBlockTypeIdAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + spawned.teleportTo(loc); + world.a(spawned.getHandle()); + if (split0 != null && split0.length == 2) + { + mob2 = Mob.fromName(split0[1].equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(split0[1])); + if (mob2 == null) + { + user.sendMessage("Invalid mob type."); + return; + } + try + { + spawned1 = mob2.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + spawned1.teleportTo(spawned); + spawned1.getHandle().setPassengerOf(spawned.getHandle()); + world.a(spawned1.getHandle()); + } + if (split1.length == 2 && "Slime".equals(mob.name)) + { + try + { + //((EntitySlime)spawned.getHandle()).a(Integer.parseInt(split1[1])); + } + catch (Exception e) + { + user.sendMessage("Malformed size."); + return; + } + } + if (args.length == 2) + { + int mobCount = Integer.parseInt(args[1]); + int serverLimit = Essentials.getSettings().getSpawnMobLimit(); + if(mobCount > serverLimit) + { + mobCount = serverLimit; + user.sendMessage("Mob quantity limited to server limit"); + } + user.charge(this); + try + { + for (int i = 1; i < mobCount; i++) + { + spawned = mob.spawn(user, server); + spawned.teleportTo(loc); + if (split1.length > 1 && "Slime".equals("Slime")) + { + try + { + //((EntitySlime)spawned.getHandle()).a(Integer.parseInt(split1[1])); + } + catch (Exception e) + { + user.sendMessage("Malformed size."); + return; + } + } + world.a(spawned.getHandle()); + if (split0.length == 2) + { + if (mob2 == null) + { + user.sendMessage("Invalid mob mount."); + return; + } + try + { + spawned1 = mob2.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + spawned1.teleportTo(spawned); + spawned1.getHandle().setPassengerOf(spawned.getHandle()); + world.a(spawned1.getHandle()); + } + } + user.sendMessage(args[1] + " " + mob.name.toLowerCase() + mob.s + " spawned."); + } + catch (MobException e1) + { + throw new Exception("Unable to spawn mobs. Insert bad excuse here."); + } + catch (NumberFormatException e2) + { + throw new Exception("A number goes there, silly."); + } + catch (NullPointerException np) + { + throw new Exception("That mob likes to be alone"); + } + } + else + { + user.sendMessage(mob.name + " spawned."); + } + } + + private String capitalCase(String s) + { + return s.toUpperCase().charAt(0) + s.toLowerCase().substring(1); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java new file mode 100644 index 000000000..07ac23e94 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsuicide extends EssentialsCommand +{ + public Commandsuicide() + { + super("suicide"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.setHealth(0); + user.sendMessage("§cGoodbye Cruel World..."); + server.broadcastMessage("§7" + user.getDisplayName() + " took their own life" ); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java new file mode 100644 index 000000000..63e565de8 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -0,0 +1,63 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtime extends EssentialsCommand +{ + public Commandtime() + { + super("time"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + World world = user.getWorld(); + long time = world.getTime(); + time = time - time % 24000; + if (args.length < 1) + { + user.sendMessage("§cUsage: /time [day|night]"); + return; + } + if ("day".equalsIgnoreCase(args[0])) + { + user.charge(this); + world.setTime(time + 24000); + return; + } + if ("night".equalsIgnoreCase(args[0])) + { + user.charge(this); + world.setTime(time + 37700); + return; + } + throw new Exception("/time only supports day/night."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + for (World world : server.getWorlds()) + { + long time = world.getTime(); + time = time - time % 24000; + if (args.length < 1) + { + sender.sendMessage("Usage: /time [day|night]"); + return; + } + + if ("day".equalsIgnoreCase(args[0])) world.setTime(time + 24000); + else if ("night".equalsIgnoreCase(args[0])) world.setTime(time + 37700); + else throw new Exception("/time only supports day/night."); + } + + sender.sendMessage("Time set in all worlds."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java new file mode 100644 index 000000000..f6d399a0d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -0,0 +1,67 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtogglejail extends EssentialsCommand +{ + public Commandtogglejail() + { + super("togglejail"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1 || args.length > 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); + return; + } + + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + sender.sendMessage("§cThat player does not exist."); + return; + } + + if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) + { + sender.sendMessage("§cYou may not jail that person"); + return; + } + + if (args.length == 2 && !p.isJailed()) { + User.charge(sender, this); + sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); + p.sendMessage("§7You have been jailed"); + Essentials.getJail().sendToJail(p, args[1]); + p.currentJail = (args[1]); + return; + } + + if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { + sender.sendMessage("§cPerson is already in jail "+ p.currentJail); + return; + } + + if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { + if (!p.isJailed()) { + sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); + return; + } + sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); + p.sendMessage("§7You have been released"); + p.teleportBack(); + p.currentJail = ""; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java new file mode 100644 index 000000000..7776e7bcb --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtop extends EssentialsCommand +{ + public Commandtop() + { + super("top"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + int topX = user.getLocation().getBlockX(); + int topZ = user.getLocation().getBlockZ(); + int topY = user.getWorld().getHighestBlockYAt(topX, topZ); + user.charge(this); + user.teleportTo(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName()); + user.sendMessage("§7Teleporting to top."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java new file mode 100644 index 000000000..82f8e8bd2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -0,0 +1,61 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + + +public class Commandtp extends EssentialsCommand +{ + public Commandtp() + { + super("tp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + switch (args.length) + { + case 0: + user.sendMessage("§cUsage: /" + commandLabel + " <target> [to-player]"); + return; + + case 1: + User p = getPlayer(server, args, 0); + user.teleportCooldown(); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + user.sendMessage("§7Teleporting..."); + user.canAfford(this); + user.teleportTo(p, this.getName()); + break; + + case 2: + if (!user.isAuthorized("essentials.tpohere")) throw new Exception("You need access to /tpohere to teleport other players."); + user.sendMessage("§7Teleporting..."); + user.charge(this); + User target = getPlayer(server, args, 0); + User toPlayer = getPlayer(server, args, 1); + target.teleportToNow(toPlayer); + target.sendMessage("§7" + user.getDisplayName() + "§7 teleported you to " + toPlayer.getDisplayName() + "§7."); + break; + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [target] [to-player]"); + return; + } + + sender.sendMessage("§7Teleporting..."); + User target = getPlayer(server, args, 0); + User toPlayer = getPlayer(server, args, 1); + target.teleportToNow(toPlayer); + target.sendMessage("§7{Console}§7 teleported you to " + toPlayer.getDisplayName() + "§7."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java new file mode 100644 index 000000000..491c4363e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpa extends EssentialsCommand +{ + public Commandtpa() + { + super("tpa"); + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + if(args.length < 1) + { + player.sendMessage("§cUsage: /tpa [playername]"); + return; + } + + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + player.charge(this); + parent.tpcRequests.put(p, player); + parent.tpcHere.put(p, false); + p.sendMessage("§c" + player.getDisplayName() + "§c has requested to teleport to you."); + p.sendMessage("§7To teleport, type §c/tpaccept§7."); + p.sendMessage("§7To deny this request, type §c/tpdeny§7."); + player.sendMessage("§7Request sent to " + p.getDisplayName() + "§7."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java new file mode 100644 index 000000000..03907fead --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -0,0 +1,40 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandtpaccept extends EssentialsCommand +{ + public Commandtpaccept() + { + super("tpaccept"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + + User p = parent.tpcRequests.get(user); + if (p == null) throw new Exception("You do not have a pending request."); + parent.tpcRequests.remove(user); + + if (parent.tpcHere.get(user)) + { + user.teleportCooldown(); + user.canAfford(this); + user.sendMessage("§7Teleport request accepted."); + p.sendMessage("§7Teleport request accepted."); + user.teleportTo(p, this.getName()); + } + else + { + user.canAfford(this); + user.sendMessage("§7Teleport request accepted."); + p.sendMessage("§7Teleport request accepted."); + p.teleportTo(user, this.getName()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java new file mode 100644 index 000000000..bf179cc59 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpahere extends EssentialsCommand +{ + public Commandtpahere() + { + super("tpahere"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /tpahere [playername]"); + return; + } + + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + user.charge(this); + parent.tpcRequests.put(p, user); + parent.tpcHere.put(p, true); + p.sendMessage("§c" + user.getDisplayName() + "§c has requested that you teleport to him/her."); + p.sendMessage("§7To teleport, type §c/tpaccept§7."); + user.sendMessage("§7Request sent to " + p.getDisplayName() + "§c."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java new file mode 100644 index 000000000..6ed5fc8dc --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpdeny extends EssentialsCommand +{ + public Commandtpdeny() + { + super("tpdeny"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + User p = parent.tpcRequests.get(user); + if (p == null) throw new Exception("You do not have a pending request."); + parent.tpcRequests.remove(user); + + if (parent.tpcHere.get(user)) + { + user.charge(this); + user.sendMessage("§7Teleport request denied."); + p.sendMessage("§7Teleport request denied."); + parent.tpcHere.remove(user); + } + else + { + user.charge(this); + user.sendMessage("§7Teleport request denied."); + p.sendMessage("§7Teleport request denied."); + parent.tpcRequests.remove(user); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java new file mode 100644 index 000000000..3a003b257 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtphere extends EssentialsCommand +{ + public Commandtphere() + { + super("tphere"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "telehere", "s" + }; + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + player.charge(this); + p.teleportTo(player); + player.sendMessage("§7Teleporting..."); + p.sendMessage("§7Teleporting..."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java new file mode 100644 index 000000000..f3fa6900c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandtpo extends EssentialsCommand +{ + public Commandtpo() + { + super("tpo"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§c Usage: /tpo [playername]"); + } + else + { + //Just basically the old tp command + User p = getPlayer(server, args, 0); + user.teleportCooldown(); + user.charge(this); + user.teleportToNow(p); + user.sendMessage("§7Teleporting..."); + } + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java new file mode 100644 index 000000000..082f49452 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -0,0 +1,31 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpohere extends EssentialsCommand +{ + public Commandtpohere() + { + super("tpohere"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§c Usage: /tpohere [playername]"); + } + else + { + //Just basically the old tphere command + User p = getPlayer(server, args, 0); + user.charge(this); + p.teleportToNow(user); + user.sendMessage("§7Teleporting..."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java new file mode 100644 index 000000000..f352da37d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtppos extends EssentialsCommand +{ + public Commandtppos() + { + super("tppos"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "tpp" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 3) + { + user.sendMessage("§cUsage: /tppos [x] [y] [z]"); + return; + } + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int z = Integer.parseInt(args[2]); + Location l = new Location(user.getWorld(),x,y,z); + user.canAfford(this); + user.teleportCooldown(); + user.sendMessage("§7Teleporting..."); + user.teleportTo(user.getSafeDestination(l), this.getName()); + } +}
\ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java new file mode 100644 index 000000000..7e93cc4cf --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtptoggle extends EssentialsCommand +{ + public Commandtptoggle() + { + super("tptoggle"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.sendMessage("§7Teleportation " + (user.toggleTeleEnabled() ? "enabled." : "disabled.")); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java new file mode 100644 index 000000000..27ce617c9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java @@ -0,0 +1,64 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.TreeType; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandtree extends EssentialsCommand +{ + public Commandtree() + { + super("tree"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Object tree = new Object(); + if (args.length < 1) + { + user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); + return; + } + else if (args[0].equalsIgnoreCase("birch")) + { + tree = TreeType.BIRCH; + } + else if (args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.REDWOOD; + } + else if (args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.TREE; + } + else + { + user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); + return; + } + + double x = user.getLocation().getX(); + double y = user.getLocation().getY(); + double z = user.getLocation().getZ(); + + // offset tree in direction player is facing + int r = (int)user.getCorrectedYaw(); + if (r < 68 || r > 292) x -= 3.0D; // north + else if (r > 112 && r < 248) x += 3.0D; // south + if (r > 22 && r < 158) z -= 3.0D; // east + else if (r > 202 && r < 338) z += 3.0D; // west + + Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); + boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); + if (success) + { + user.charge(this); + user.sendMessage("§7Tree spawned."); + } + else + user.sendMessage("§cTree generation failure. Try again on grass or dirt."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java new file mode 100644 index 000000000..55fd54fad --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java @@ -0,0 +1,35 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandunban extends EssentialsCommand +{ + public Commandunban() + { + super("unban"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pardon" }; + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player]"); + return; + } + + ((CraftServer)server).getHandle().c.f.b(args[0]); + sender.sendMessage("Unbanned player."); + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java new file mode 100644 index 000000000..df152c23f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java @@ -0,0 +1,35 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandunbanip extends EssentialsCommand +{ + public Commandunbanip() + { + super("unbanip"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pardonip" }; + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [address]"); + return; + } + + ((CraftServer)server).getHandle().c.f.d(args[0]); + sender.sendMessage("Unbanned IP address."); + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java new file mode 100644 index 000000000..c5471f831 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -0,0 +1,74 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.Warps; + + +public class Commandwarp extends EssentialsCommand +{ + public Commandwarp() + { + super("warp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + boolean perWarpPermission = Essentials.getSettings().getPerWarpPermission(); + if (args.length == 0) { + if (!user.isAuthorized("essentials.warp.list")) + { + user.sendMessage("§cYou do not have Permission to list that warps."); + return; + } + + Warps warps = Essentials.getWarps(); + if (warps.isEmpty()) { + throw new Exception("No warps defined"); + } + StringBuilder sb = new StringBuilder(); + int i = 0; + for (String warpName : warps.getWarpNames()) + { + if (perWarpPermission) + { + if (user.isAuthorized("essentials.warp." + warpName)) + { + if (i++ > 0) sb.append(", "); + sb.append(warpName); + } + } + else + { + if (i++ > 0) sb.append(", "); + sb.append(warpName); + } + + } + user.sendMessage(sb.toString()); + return; + } + + try { + if (perWarpPermission) + { + if (user.isAuthorized("essentials.warp." + args[0])) + { + user.canAfford(this); + user.teleportCooldown(); + user.warpTo(args[0], this.getName()); + return; + } + user.sendMessage("§cYou do not have Permission to use that warp."); + return; + } + user.canAfford(this); + user.teleportCooldown(); + user.warpTo(args[0], this.getName()); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java new file mode 100644 index 000000000..508e69a58 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -0,0 +1,44 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; + + +public class Commandwhois extends EssentialsCommand +{ + public Commandwhois() + { + super("whois"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /whois [nickname]"); + return; + } + String whois = args[0].toLowerCase(); + User.charge(sender, this); + int prefixLength = ChatColor.stripColor(Essentials.getSettings().getNicknamePrefix()).length(); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String dn = ChatColor.stripColor(u.getNick()); + if (!whois.equalsIgnoreCase(dn) && !whois.equalsIgnoreCase(dn.substring(prefixLength)) && !whois.equalsIgnoreCase(u.getName())) continue; + sender.sendMessage(""); + sender.sendMessage(u.getDisplayName() + " is " + u.getName()); + sender.sendMessage(ChatColor.BLUE + " - Health: " + u.getHealth() + "/20"); + sender.sendMessage(ChatColor.BLUE + " - Location: (" + u.getLocation().getBlockX() + ", " + u.getLocation().getBlockY() + ", " + u.getLocation().getBlockZ() + ")"); + if (!parent.getConfiguration().getBoolean("disable-eco", false)) sender.sendMessage(ChatColor.BLUE + " - Money: $" + u.getMoney()); + sender.sendMessage(ChatColor.BLUE + " - Status: " + (parent.away.contains(u) ? "§cAway" : "Available")); + sender.sendMessage(ChatColor.BLUE + " - IP Address: " + u.getAddress().getAddress().toString()); + + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java new file mode 100644 index 000000000..41a2d270d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -0,0 +1,67 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandworld extends EssentialsCommand +{ + public Commandworld() + { + super("world"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + World world; + List<World> worlds = server.getWorlds(); + + if (args.length < 1) + { + world = worlds.get(user.getWorld() == worlds.get(0) && worlds.size() > 1 ? 1 : 0); + } + else + { + try + { + int wid = Integer.parseInt(args[0]); + world = server.getWorlds().get(wid); + } + catch (Throwable ex) + { + try + { + world = server.getWorld(getFinalArg(args, 0)); + if (world == null) throw new Exception(); + } + catch (Throwable ex2) + { + user.sendMessage("§cInvalid world."); + user.sendMessage("§7Possible worlds are the numbers 0 through " + (server.getWorlds().size() - 1) + "."); + user.sendMessage("§7You can also type the name of a specific world."); + return; + } + } + } + + double factor; + if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) + factor = 16; + else if (user.getWorld().getEnvironment() != world.getEnvironment()) + factor = 1 / 16; + else + factor = 1; + + Location loc = user.getLocation(); + loc = new Location(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); + + user.canAfford(this); + user.teleportCooldown(); + user.teleportTo(loc, this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java new file mode 100644 index 000000000..0933ef4a2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java @@ -0,0 +1,48 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; +import org.bukkit.inventory.ItemStack; + + +public class Commandworth extends EssentialsCommand +{ + public Commandworth() + { + super("worth"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + ItemStack is = user.getInventory().getItemInHand(); + int id = is.getTypeId(); + int amount = is.getAmount(); + + try + { + if (args.length > 0) id = Integer.parseInt(args[0]); + } + catch (NumberFormatException ex) + { + id = ItemDb.get(args[0]).getTypeId(); + } + + try + { + if (args.length > 1) amount = Integer.parseInt(args[1]); + } + catch (NumberFormatException ex) + { + amount = 64; + } + + int worth = parent.getConfiguration().getInt("worth-" + id, 0); + + user.charge(this); + user.sendMessage("§7Stack of " + id + " worth §c$" + (worth * amount) + "§7 (" + amount + " item(s) at $" + worth + " each)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java new file mode 100644 index 000000000..782f48287 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -0,0 +1,80 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public abstract class EssentialsCommand implements IEssentialsCommand +{ + private final String name; + + protected EssentialsCommand(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public String[] getTriggers() + { + return new String[] + { + getName() + }; + } + + protected User getPlayer(Server server, String[] args, int pos) throws IndexOutOfBoundsException, NoSuchFieldException + { + if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?"); + List<Player> matches = server.matchPlayer(args[pos]); + if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found."); + return User.get(matches.get(0)); + } + + @Override + public final void run(Server server, Essentials parent, User user, String commandLabel, Command cmd, String[] args) throws Exception + { + run(server, parent, user, commandLabel, args); + } + + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + run(server, parent, (CommandSender)user.getBase(), commandLabel, args); + } + + @Override + public final void run(Server server, Essentials parent, CommandSender sender, String commandLabel, Command cmd, String[] args) throws Exception + { + run(server, parent, sender, commandLabel, args); + } + + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + throw new Exception("Only in-game players can use " + commandLabel + "."); + } + + public static String getFinalArg(String[] args, int start) + { + StringBuilder bldr = new StringBuilder(); + for (int i = start; i < args.length; i++) + { + if (i != start) bldr.append(" "); + bldr.append(args[i]); + } + return bldr.toString(); + } + + protected void charge(CommandSender sender) throws Exception + { + if (sender instanceof Player) + User.get((Player)sender).charge(this); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java new file mode 100644 index 000000000..d1debd29d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java @@ -0,0 +1,20 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.*; + + +public interface IEssentialsCommand +{ + String getName(); + + String[] getTriggers(); + + void run(Server server, Essentials parent, User user, String commandLabel, Command cmd, String[] args) + throws Exception; + + void run(Server server, Essentials parent, CommandSender sender, String commandLabel, Command cmd, String[] args) + throws Exception; +} |