public void trackUUID(final UUID uuid, final String name, boolean replace) { if (uuid != null) { keys.add(uuid); if (name != null && name.length() > 0) { final String keyName = StringUtil.safeString(name); if (!names.containsKey(keyName)) { names.put(keyName, uuid); uuidMap.writeUUIDMap(); } else if (!names.get(keyName).equals(uuid)) { if (replace) { ess.getLogger() .info( "Found new UUID for " + name + ". Replacing " + names.get(keyName).toString() + " with " + uuid.toString()); names.put(keyName, uuid); uuidMap.writeUUIDMap(); } else { if (ess.getSettings().isDebug()) { ess.getLogger() .info( "Found old UUID for " + name + " (" + uuid.toString() + "). Not adding to usermap."); } } } } } }
// TODO: Convert this to use one of the new text classes? public static String listKits(final IEssentials ess, final User user) throws Exception { try { final ConfigurationSection kits = ess.getSettings().getKits(); final StringBuilder list = new StringBuilder(); for (String kitItem : kits.getKeys(false)) { if (user == null) { list.append(" ").append(capitalCase(kitItem)); } else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) { String cost = ""; String name = capitalCase(kitItem); BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); if (costPrice.signum() > 0) { cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess)); } Kit kit = new Kit(kitItem, ess); if (kit.getNextUse(user) != 0) { name = tl("kitDelay", name); } list.append(" ").append(name).append(cost); } } return list.toString().trim(); } catch (Exception ex) { throw new Exception(tl("kitError"), ex); } }
public static String shortCurrency(final double value, final IEssentials ess) { @Cleanup final ISettings settings = ess.getSettings(); settings.acquireReadLock(); return settings.getData().getEconomy().getCurrencySymbol() + formatAsCurrency(value); }
@EventHandler(priority = EventPriority.MONITOR) public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) { final ISettings settings = ess.getSettings(); final IUser user = userMap.getUser(event.getPlayer()); if (settings.getData().getChat().getChangeDisplayname()) { user.updateDisplayName(); } if (!settings.getData().getWorldOptions(event.getPlayer().getLocation().getWorld().getName()).isGodmode() && !Permissions.NOGOD_OVERRIDE.isAuthorized( user)) { if (user.getData().isGodmode()) { user.sendMessage(_("§4Warning! God mode in this world disabled.")); } } if (settings.getData().getCommands().getTeleport().isCancelRequestsOnWorldChange()) { if (user.getTeleportRequester() != null) { user.requestTeleport(null, false); user.sendMessage(_("teleportRequestsCancelledWorldChange")); } } if (settings.getData().getGeneral().isPtClearOnWorldChange()) { user.getData().clearAllPowertools(); user.queueSave(); user.sendMessage(_("§6All powertool commands have been cleared.")); } }
@Override public void run() { if (!active.compareAndSet(false, true)) { return; } final ISettings settings = ess.getSettings(); final net.ess3.settings.Backup backupSettings = settings.getData().getGeneral().getBackup(); String backupCommand = backupSettings.getCommand() == null || backupSettings.getCommand().isEmpty() ? ("NORUN") : backupSettings.getCommand(); /*if (backupCommand.equals("NORUN")) { TODO: Un-comment if you do not want commands to be run if there is no backup command return; }*/ ess.getLogger().log(Level.INFO, _("backupStarted")); if (!backupSettings.getCommandsBeforeBackup().isEmpty()) { final CommandSender consoleSender = server.getConsoleSender(); for (String command : backupSettings.getCommandsBeforeBackup()) { server.dispatchCommand(consoleSender, command); } } ess.getPlugin().scheduleAsyncDelayedTask(new BackupRunner(backupCommand)); }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerMove(final PlayerMoveEvent event) { final IUser user = userMap.getUser(event.getPlayer()); final ISettings settings = ess.getSettings(); if (user.getData().isAfk() && settings.getData().getCommands().getAfk().isFreezeAFKPlayers()) { final Location from = event.getFrom(); final Location to = event.getTo().clone(); to.setX(from.getX()); to.setY(from.getY()); to.setZ(from.getZ()); try { event.setTo(LocationUtil.getSafeDestination(to)); } catch (Exception ex) { event.setTo(to); } return; } final Location afk = user.getAfkPosition(); if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) { user.updateActivity(true); } }
@EventHandler(priority = EventPriority.NORMAL) public void onPlayerInteract(final PlayerInteractEvent event) { final IUser user = userMap.getUser(event.getPlayer()); user.updateActivity(true); switch (event.getAction()) { case RIGHT_CLICK_BLOCK: if (event.isCancelled()) { return; } final ISettings settings = ess.getSettings(); if (settings.getData().getCommands().getHome().isUpdateBedAtDaytime() && event.getClickedBlock().getType() == Material.BED_BLOCK) { event.getPlayer().setBedSpawnLocation(event.getClickedBlock().getLocation()); } break; case LEFT_CLICK_AIR: case LEFT_CLICK_BLOCK: if (user.getData().hasPowerTools() && user.getData().isPowerToolsEnabled()) { if (usePowertools(user)) { event.setCancelled(true); } } break; default: break; } }
public void executed(final String label, final String otherLabel) { if (ess.getSettings().isDebug()) { LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + otherLabel); } disabledList.put(label, otherLabel); }
@Override public void showCommandError(final CommandSender sender, final String commandLabel, final Throwable exception) { sender.sendMessage(_("errorWithMessage", exception.getMessage())); if (ess.getSettings().isDebug()) { LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception); } }
public Kit(final String kitName, final IEssentials ess) throws Exception { this.kitName = kitName; this.ess = ess; this.kit = ess.getSettings().getKit(kitName); this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess); if (kit == null) { throw new Exception(tl("kitNotFound")); } }
@EventHandler(priority = EventPriority.MONITOR) public void onPluginEnable(final PluginEnableEvent event) { if (event.getPlugin().getName().equals("EssentialsChat")) { ess.getSettings().setEssentialsChatActive(true); } ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); ess.getPermissionsHandler().checkPermissions(); ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) { ess.getLogger() .log( Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); } }
@EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(final PlayerQuitEvent event) { final String quitMessage = ess.getSettings().getData().getGeneral().getLeaveMessage(); if (quitMessage != null) { final IText itOutput = new KeywordReplacer(new SimpleTextInput(quitMessage), userMap.getUser(event.getPlayer()), ess); final SimpleTextPager stPager = new SimpleTextPager(itOutput); event.setQuitMessage(FormatUtil.replaceFormat(stPager.getString(0))); } else { event.setQuitMessage(null); } final IUser user = userMap.getUser(event.getPlayer()); final ISettings settings = ess.getSettings(); if (settings.getData().getCommands().getGod().isRemoveOnDisconnect() && user.isGodModeEnabled()) { user.setGodModeEnabled(false); } if (user.isVanished()) { user.toggleVanished(); } if (user.getData().getInventory() != null) { user.getPlayer().getInventory().setContents(user.getData().getInventory().getBukkitInventory()); user.getData().setInventory(null); } user.updateActivity(false); //user.getPlayer().dispose(); if (settings.getData().getGeneral().isPtClearOnQuit()) { user.getData().clearAllPowertools(); user.queueSave(); user.sendMessage(_("§6All powertool commands have been cleared.")); } }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerTeleport(final PlayerTeleportEvent event) { final ISettings settings = ess.getSettings(); //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. if ((event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND) && settings.getData().getCommands().getBack().isRegisterBackInListener()) { final IUser user = userMap.getUser(event.getPlayer()); user.setLastLocation(); } }
public UserMap(final IEssentials ess) { super(); this.ess = ess; uuidMap = new UUIDMap(ess); // RemovalListener<UUID, User> remListener = new UserMapRemovalListener(); // users = // CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().removalListener(remListener).build(this); users = CacheBuilder.newBuilder() .maximumSize(ess.getSettings().getMaxUserCacheCount()) .softValues() .build(this); }
@EventHandler(priority = EventPriority.MONITOR) public void onPluginDisable(final PluginDisableEvent event) { if (event.getPlugin().getName().equals("EssentialsChat")) { ess.getSettings().setEssentialsChatActive(false); } ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); // Check to see if the plugin thats being disabled is the one we are using if (ess.getPaymentMethod() != null && Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) { Methods.reset(); ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); } }
@Override public final void startTask() { if (running.compareAndSet(false, true)) { final ISettings settings = ess.getSettings(); final long interval = settings.getData().getGeneral().getBackup().getInterval() * 1200; // minutes -> ticks if (interval < 1200) { running.set(false); return; } taskId = ess.getPlugin().scheduleSyncRepeatingTask(this, interval, interval); } }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerPickupItem(final PlayerPickupItemEvent event) { final ISettings settings = ess.getSettings(); if (!settings.getData().getCommands().getAfk().isDisableItemPickupWhileAfk()) { return; } final IUser user = userMap.getUser(event.getPlayer()); if (user.getData().isAfk()) { event.setCancelled(true); } }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final IUser user = userMap.getUser(event.getPlayer()); final String cmd = spaceSplit.split(event.getMessage().toLowerCase(Locale.ENGLISH))[0].replace("/", "").toLowerCase(Locale.ENGLISH); if (ess.getSettings().getData().getCommands().getSocialspy().getSocialspyCommands().contains(cmd)) { for (Player player : ess.getServer().getOnlinePlayers()) { IUser spyer = userMap.getUser(player); if (spyer.getData().isSocialspy() && !user.equals(spyer)) { player.sendMessage(user.getPlayer().getDisplayName() + " : " + event.getMessage()); } } } if (!cmd.equalsIgnoreCase("afk")) { user.updateActivity(true); } }
@Override public void run() { if (!active.compareAndSet(false, true)) { return; } @Cleanup final ISettings settings = ess.getSettings(); settings.acquireReadLock(); final String command = settings.getData().getGeneral().getBackup().getCommand(); if (command == null || command.isEmpty()) { return; } ess.getLogger().log(Level.INFO, _("backupStarted")); final CommandSender consoleSender = server.getConsoleSender(); server.dispatchCommand(consoleSender, "save-all"); server.dispatchCommand(consoleSender, "save-off"); ess.getPlugin().scheduleAsyncDelayedTask(new BackupRunner(command)); }
public void delayedJoin(final Player player) { if (!player.isOnline()) { return; } ess.getBackup().startTask(); final IUser user = userMap.getUser(player); user.setDisplayNick(); user.updateCompass(); user.getData().setTimestamp(TimestampType.LOGIN, System.currentTimeMillis()); user.updateActivity(false); if (!ess.getVanishedPlayers().isEmpty() && !Permissions.VANISH_SEE_OTHERS.isAuthorized(user)) { for (String p : ess.getVanishedPlayers()) { final Player toVanish = userMap.getUser(p).getPlayer(); if (toVanish.isOnline()) { user.setVanished(true); } } } if (Permissions.SLEEPINGIGNORED.isAuthorized(user)) { ess.getPlugin().scheduleSyncDelayedTask( new Runnable() { @Override public void run() { user.getPlayer().setSleepingIgnored(true); } }); } final Commands settings = ess.getSettings().getData().getCommands(); if (!settings.isDisabled("motd") && Permissions.MOTD.isAuthorized(user)) { try { final IText input = new TextInput(user, "motd", true, ess); final IText output = new KeywordReplacer(input, user, ess); final TextPager pager = new TextPager(output, true); pager.showPage("1", null, "motd", user); } catch (IOException ex) { if (ess.getSettings().isDebug()) { ess.getLogger().log(Level.WARNING, ex.getMessage(), ex); } else { ess.getLogger().log(Level.WARNING, ex.getMessage()); } } } if (!settings.isDisabled("mail") && Permissions.MAIL.isAuthorized(user)) { final List<String> mail = user.getMails(); if (mail.isEmpty()) { final String msg = _("§6You have no new mail."); if (!msg.isEmpty()) { user.sendMessage(msg); } } else { user.sendMessage(_("§6You have§c {0} §6messages! Type §c/mail read§6 to view your mail.", mail.size())); } } if (Permissions.FLY_SAFELOGIN.isAuthorized(user)) { final Location loc = user.getPlayer().getLocation(); final World world = loc.getWorld(); final int x = loc.getBlockX(); int y = loc.getBlockY(); final int z = loc.getBlockZ(); while (LocationUtil.isBlockUnsafe(world, x, y, z) && y > -1) { y--; } if (loc.getBlockY() - y > 1 || y < 0) { user.getPlayer().setAllowFlight(true); user.getPlayer().setFlying(true); user.sendMessage(_("§6Set fly mode§c {0} §6for {1}§6.", _("enabled"), user.getPlayer().getDisplayName())); } } }
@Override public boolean handleCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { boolean disabled = false; boolean overridden = false; ISettings settings = ess.getSettings(); settings.acquireReadLock(); try { disabled = settings.getData().getCommands().isDisabled(command.getName()); overridden = !disabled || settings.getData().getCommands().isOverridden(command.getName()); } finally { settings.unlock(); } // Allow plugins to override the command via onCommand if (!overridden && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) { final PluginCommand pc = getAlternative(commandLabel); if (pc != null) { executed(commandLabel, pc.getLabel()); try { return pc.execute(sender, commandLabel, args); } catch (final Exception ex) { final ArrayList<StackTraceElement> elements = new ArrayList<StackTraceElement>(Arrays.asList(ex.getStackTrace())); elements.remove(0); final ArrayList<StackTraceElement> toRemove = new ArrayList<StackTraceElement>(); for (final StackTraceElement e : elements) { if (e.getClassName().equals("net.ess3.Essentials")) { toRemove.add(e); } } elements.removeAll(toRemove); final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]); ex.setStackTrace(trace); ex.printStackTrace(); sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); return true; } } } try { IUser user = null; if (sender instanceof Player) { user = ess.getUserMap().getUser((Player)sender); LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0))); } // Check for disabled commands if (disabled) { return true; } final String commandName = command.getName().toLowerCase(Locale.ENGLISH); IEssentialsCommand cmd = commands.get(commandName); if (cmd == null) { try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + commandName).newInstance(); cmd.init(ess, commandName); cmd.setEssentialsModule(module); commands.put(commandName, cmd); } catch (Exception ex) { sender.sendMessage(_("commandNotLoaded", commandName)); LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandName), ex); return true; } } // Check authorization if (sender != null && !cmd.isAuthorized(sender)) { LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName())); user.sendMessage(_("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(sender, command, commandLabel, args); } else { user.acquireReadLock(); try { cmd.run(user, command, commandLabel, args); } finally { user.unlock(); } } return true; } catch (NoChargeException ex) { return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); if (!ex.getMessage().isEmpty()) { sender.sendMessage(ex.getMessage()); } return true; } catch (Throwable ex) { showCommandError(sender, commandLabel, ex); return true; } } catch (Throwable ex) { LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex); return true; } }
public HelpInput(final IUser user, final String match, final IEssentials ess) throws IOException { final ISettings settings = ess.getSettings(); boolean reported = false; final List<String> newLines = new ArrayList<String>(); String pluginName = ""; String pluginNameLow = ""; if (!match.equalsIgnoreCase("")) { lines.add(_("Commands matching \"{0}\":", match)); } for (Plugin p : ess.getServer().getPluginManager().getPlugins()) { try { final List<String> pluginLines = new ArrayList<String>(); final PluginDescriptionFile desc = p.getDescription(); final Map<String, Map<String, Object>> cmds = desc.getCommands(); pluginName = p.getDescription().getName(); pluginNameLow = pluginName.toLowerCase(Locale.ENGLISH); if (pluginNameLow.equals(match)) { lines.clear(); newLines.clear(); lines.add(_("Commands from {0}:", p.getDescription().getName())); } for (Map.Entry<String, Map<String, Object>> k : cmds.entrySet()) { try { if (!match.equalsIgnoreCase("") && (!pluginNameLow.contains(match)) && (!k.getKey().toLowerCase(Locale.ENGLISH).contains( match)) && (!(k.getValue().get(DESCRIPTION) instanceof String && ((String)k.getValue().get(DESCRIPTION)).toLowerCase( Locale.ENGLISH).contains(match)))) { continue; } if (pluginNameLow.contains("essentials")) { final String node = "essentials." + k.getKey(); if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) { pluginLines.add(_("/{0}: {1}", k.getKey(), k.getValue().get(DESCRIPTION))); } } else { if (settings.getData().getCommands().getHelp().isShowNonEssCommandsInHelp()) { final Map<String, Object> value = k.getValue(); Object permissions = null; if (value.containsKey(PERMISSION)) { permissions = value.get(PERMISSION); } else if (value.containsKey(PERMISSIONS)) { permissions = value.get(PERMISSIONS); } if (Permissions.HELP.isAuthorized(user, pluginNameLow)) { pluginLines.add(_("/{0}: {1}", k.getKey(), value.get(DESCRIPTION))); } else if (permissions instanceof List && !((List<Object>)permissions).isEmpty()) { boolean enabled = false; for (Object o : (List<Object>)permissions) { if (o instanceof String && user.hasPermission(o.toString())) { enabled = true; break; } } if (enabled) { pluginLines.add(_("/{0}: {1}", k.getKey(), value.get(DESCRIPTION))); } } else if (permissions instanceof String && !"".equals(permissions)) { if (user.hasPermission(permissions.toString())) { pluginLines.add(_("/{0}: {1}", k.getKey(), value.get(DESCRIPTION))); } } else { if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) { pluginLines.add(_("/{0}: {1}", k.getKey(), value.get(DESCRIPTION))); } } } } } catch (NullPointerException ex) { continue; } } if (!pluginLines.isEmpty()) { newLines.addAll(pluginLines); if (pluginNameLow.equals(match)) { break; } if (match.equalsIgnoreCase("")) { lines.add(_("{0}: Plugin Help: /help {1}", pluginName, pluginNameLow)); } } } catch (NullPointerException ex) { continue; } catch (Exception ex) { if (!reported) { logger.log(Level.WARNING, _("Error getting help for: {0}", pluginNameLow), ex); } reported = true; continue; } } lines.addAll(newLines); }
public void expandItems(final User user, final List<String> items) throws Exception { try { IText input = new SimpleTextInput(items); IText output = new KeywordReplacer(input, user.getSource(), ess); boolean spew = false; final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); for (String kitItem : output.getLines()) { if (kitItem.startsWith(ess.getSettings().getCurrencySymbol())) { BigDecimal value = new BigDecimal( kitItem.substring(ess.getSettings().getCurrencySymbol().length()).trim()); Trade t = new Trade(value, ess); t.pay(user, OverflowType.DROP); continue; } if (kitItem.startsWith("/")) { String command = kitItem.substring(1); String name = user.getName(); command = command.replace("{player}", name); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); continue; } final String[] parts = kitItem.split(" +"); final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1); if (parseStack.getType() == Material.AIR) { continue; } final MetaItemStack metaStack = new MetaItemStack(parseStack); if (parts.length > 2) { // We pass a null sender here because kits should not do perm checks metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess); } final Map<Integer, ItemStack> overfilled; final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks"); if (allowOversizedStacks) { overfilled = InventoryWorkaround.addOversizedItems( user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack()); } else { overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack()); } for (ItemStack itemStack : overfilled.values()) { int spillAmount = itemStack.getAmount(); if (!allowOversizedStacks) { itemStack.setAmount( spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize()); } while (spillAmount > 0) { user.getWorld().dropItemNaturally(user.getLocation(), itemStack); spillAmount -= itemStack.getAmount(); } spew = true; } } user.getBase().updateInventory(); if (spew) { user.sendMessage(tl("kitInvFull")); } } catch (Exception e) { user.getBase().updateInventory(); ess.getLogger().log(Level.WARNING, e.getMessage()); throw new Exception(tl("kitError2"), e); } }