Пример #1
0
  @Override
  public void run(Server server, CommandSender sender, String commandLabel, String[] args)
      throws Exception {
    if (args.length < 1) {
      throw new NotEnoughArgumentsException();
    }

    if (server.matchPlayer(args[0]).isEmpty()) {
      ((CraftServer) server).getHandle().a(args[0]);
      sender.sendMessage(Util.format("playerBanned", args[0]));
    } else {
      final User player = ess.getUser(server.matchPlayer(args[0]).get(0));
      String banReason;
      if (args.length > 1) {
        banReason = getFinalArg(args, 1);
        player.setBanReason(commandLabel);
      } else {
        banReason = Util.i18n("defaultBanReason");
      }
      player.kickPlayer(banReason);
      ((CraftServer) server).getHandle().a(player.getName());
      sender.sendMessage(Util.format("playerBanned", player.getName()));
    }
    ess.loadBanList();
  }
Пример #2
0
		@EventHandler(priority = EventPriority.HIGHEST)
		public void onPlayerJoin(final PlayerJoinEvent event)
		{
			final User user = ess.getUser(event.getPlayer());
			if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
			{
				return;
			}

			try
			{
				sendToJail(user, user.getJail());
			}
			catch (Exception ex)
			{
				if (ess.getSettings().isDebug())
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
				}
				else
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
				}
			}
			user.sendMessage(_("jailMessage"));
		}
Пример #3
0
	@Override
	protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		if (args.length < 1)
		{
			throw new NotEnoughArgumentsException();
		}
		final String whois = args[0].toLowerCase(Locale.ENGLISH);
		for (Player onlinePlayer : server.getOnlinePlayers())
		{
			final User u = ess.getUser(onlinePlayer);
			if (u.isHidden())
			{
				continue;
			}
			final String displayName = Util.stripColor(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
			if (!whois.equals(displayName)
				&& !displayName.equals(Util.stripColor(ess.getSettings().getNicknamePrefix()) + whois)
				&& !whois.equalsIgnoreCase(u.getName()))
			{
				continue;
			}
			sender.sendMessage(u.getDisplayName() + " " + _("is") + " " + u.getName());
		}
	}
Пример #4
0
	/**
	 * Used to get the time and inform
	 */
	private void getUsersTime(final CommandSender sender, final Collection<User> users)
	{
		if (users.size() > 1)
		{
			sender.sendMessage(_("pTimePlayers"));
		}

		for (User user : users)
		{
			if (user.getPlayerTimeOffset() == 0)
			{
				sender.sendMessage(_("pTimeNormal", user.getName()));
			}
			else
			{
				String time = DescParseTickFormat.format(user.getPlayerTime());
				if (!user.isPlayerTimeRelative())
				{
					sender.sendMessage(_("pTimeCurrentFixed", user.getName(), time));
				}
				else
				{
					sender.sendMessage(_("pTimeCurrent", user.getName(), time));
				}
			}
		}
	}
Пример #5
0
  @Override
  public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
    charge(user);

    if (!user.toggleAfk()) {
      user.sendMessage(Util.i18n("markedAsNotAway"));
      ess.broadcastMessage(user.getName(), Util.format("userIsNotAway", user.getDisplayName()));
    } else {
      user.sendMessage(Util.i18n("markedAsAway"));
      ess.broadcastMessage(user.getName(), Util.format("userIsAway", user.getDisplayName()));
    }
  }
Пример #6
0
 /**
  * Get the Essentials user based on their playername
  *
  * @param playername The player
  * @param putInMap Put the found user in the essentials map
  * @return The user or null if not found
  */
 private User getEssentialsUser(String playername, boolean putInMap) {
   User u = plugin.getEssentials().getUserMap().getUser(playername);
   if (u != null && putInMap) { // Put in map if needed & possible
     essentialsUsers.put(u.getName(), u);
   }
   return u;
 }
Пример #7
0
	/**
	 * Used to set the time and inform of the change
	 */
	private void setUsersTime(final CommandSender sender, final Collection<User> users, final Long ticks, Boolean relative)
	{
		// Update the time
		if (ticks == null)
		{
			// Reset
			for (User user : users)
			{
				user.resetPlayerTime();
			}
		}
		else
		{
			// Set
			for (User user : users)
			{
				final World world = user.getWorld();
				long time = user.getPlayerTime();
				time -= time % 24000;
				time += 24000 + ticks;
				if (relative)
				{
					time -= world.getTime();
				}
				user.setPlayerTime(time, relative);
			}
		}

		final StringBuilder msg = new StringBuilder();
		for (User user : users)
		{
			if (msg.length() > 0)
			{
				msg.append(", ");
			}

			msg.append(user.getName());
		}

		// Inform the sender of the change
		if (ticks == null)
		{
			sender.sendMessage(_("pTimeReset", msg.toString()));
		}
		else
		{
			String time = DescParseTickFormat.format(ticks);
			if (!relative)
			{
				sender.sendMessage(_("pTimeSetFixed", time, msg.toString()));
			}
			else
			{
				sender.sendMessage(_("pTimeSet", time, msg.toString()));
			}
		}
	}
 @Override
 public void onPlayerChat(final PlayerChatEvent event) {
   final User user = ess.getUser(event.getPlayer());
   if (user.isMuted()) {
     event.setCancelled(true);
     user.sendMessage(Util.i18n("playerMuted"));
     LOGGER.info(Util.format("mutedUserSpeaks", user.getName()));
   }
   final Iterator<Player> it = event.getRecipients().iterator();
   while (it.hasNext()) {
     final User u = ess.getUser(it.next());
     if (u.isIgnoredPlayer(user.getName())) {
       it.remove();
     }
   }
   user.updateActivity(true);
   if (ess.getSettings().changeDisplayName()) {
     user.setDisplayName(user.getNick());
   }
 }
Пример #9
0
  @Override
  public User load(final String stringUUID) throws Exception {
    UUID uuid = UUID.fromString(stringUUID);
    Player player = ess.getServer().getPlayer(uuid);
    if (player != null) {
      final User user = new User(player, ess);
      trackUUID(uuid, user.getName(), true);
      return user;
    }

    final File userFile = getUserFileFromID(uuid);

    if (userFile.exists()) {
      player = new OfflinePlayer(uuid, ess.getServer());
      final User user = new User(player, ess);
      ((OfflinePlayer) player).setName(user.getLastAccountName());
      trackUUID(uuid, user.getName(), false);
      return user;
    }

    throw new Exception("User not found!");
  }
Пример #10
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		if (args.length < 1)
		{
			throw new NotEnoughArgumentsException();
		}
		final User user = getPlayer(server, args, 0, true);
		if (!user.isOnline())
		{
			if (sender instanceof Player
				&& !ess.getUser(sender).isAuthorized("essentials.ban.offline"))
			{
				sender.sendMessage(_("banExempt"));
				return;
			}
		}
		else
		{
			if (user.isAuthorized("essentials.ban.exempt"))
			{
				sender.sendMessage(_("banExempt"));
				return;
			}
		}
		
		final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME;
		String banReason;
		if (args.length > 1)
		{
			banReason = _("banFormat", getFinalArg(args, 1), senderName);
		}
		else
		{
			banReason = _("banFormat", _("defaultBanReason"), senderName);
		}
		
		user.setBanReason(banReason);
		user.setBanned(true);
		user.kickPlayer(banReason);

		for (Player onlinePlayer : server.getOnlinePlayers())
		{
			final User player = ess.getUser(onlinePlayer);
			if (player.isAuthorized("essentials.ban.notify"))
			{
				onlinePlayer.sendMessage(_("playerBanned", senderName, user.getName(), banReason));
			}
		}
	}
Пример #11
0
  public User getUser(final String name) {
    try {
      final String sanitizedName = StringUtil.safeString(name);
      if (names.containsKey(sanitizedName)) {
        final UUID uuid = names.get(sanitizedName);
        return getUser(uuid);
      }

      final File userFile = getUserFileFromString(sanitizedName);
      if (userFile.exists()) {
        ess.getLogger().info("Importing user " + name + " to usermap.");
        User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess);
        trackUUID(user.getBase().getUniqueId(), user.getName(), true);
        return user;
      }
      return null;
    } catch (UncheckedExecutionException ex) {
      return null;
    }
  }
Пример #12
0
 @Override
 public void alert(final User user, final String item, final String type) {
   final Location loc = user.getLocation();
   final String warnMessage =
       Util.format(
           "alertFormat",
           user.getName(),
           type,
           item,
           loc.getWorld().getName()
               + ","
               + loc.getBlockX()
               + ","
               + loc.getBlockY()
               + ","
               + loc.getBlockZ());
   LOGGER.log(Level.WARNING, warnMessage);
   for (Player p : this.getServer().getOnlinePlayers()) {
     final User alertUser = ess.getUser(p);
     if (alertUser.isAuthorized("essentials.protect.alerts")) {
       alertUser.sendMessage(warnMessage);
     }
   }
 }
Пример #13
0
	@Override
	public int compare(User a, User b)
	{
		return a.getName().compareTo(b.getName());
	}
Пример #14
0
  @SuppressWarnings("CallToThreadDumpStack")
  private List<String> getHelpLines(User user, String match) throws Exception {
    List<String> retval = new ArrayList<String>();
    File helpFile =
        new File(ess.getDataFolder(), "help_" + Util.sanitizeFileName(user.getName()) + ".txt");
    if (!helpFile.exists()) {
      helpFile =
          new File(ess.getDataFolder(), "help_" + Util.sanitizeFileName(user.getGroup()) + ".txt");
    }
    if (!helpFile.exists()) {
      helpFile = new File(ess.getDataFolder(), "help.txt");
    }
    if (helpFile.exists()) {
      final BufferedReader bufferedReader = new BufferedReader(new FileReader(helpFile));
      try {

        while (bufferedReader.ready()) {
          final String line = bufferedReader.readLine();
          retval.add(line.replace('&', '§'));
        }
      } finally {
        bufferedReader.close();
      }
      return retval;
    }

    boolean reported = false;
    String pluginName = "";
    for (Plugin p : ess.getServer().getPluginManager().getPlugins()) {
      try {
        final PluginDescriptionFile desc = p.getDescription();
        final HashMap<String, HashMap<String, String>> cmds =
            (HashMap<String, HashMap<String, String>>) desc.getCommands();
        for (Entry<String, HashMap<String, String>> k : cmds.entrySet()) {
          if ((!match.equalsIgnoreCase(""))
              && (!p.getDescription().getName().toLowerCase().contains(match))
              && (!p.getDescription().getDescription().toLowerCase().contains(match))) {
            continue;
          }

          if (p.getDescription().getName().toLowerCase().contains("essentials")) {
            final String node = "essentials." + k.getKey();
            if (!ess.getSettings().isCommandDisabled(k.getKey()) && user.isAuthorized(node)) {
              retval.add("§c" + k.getKey() + "§7: " + k.getValue().get("description"));
            }
          } else {
            if (ess.getSettings().showNonEssCommandsInHelp()) {
              pluginName = p.getDescription().getName();
              final HashMap<String, String> value = k.getValue();
              if (value.containsKey("permission")
                  && value.get("permission") != null
                  && !(value.get("permission").equals(""))) {
                if (user.isAuthorized(value.get("permission"))) {
                  retval.add("§c" + k.getKey() + "§7: " + value.get("description"));
                }
              } else {
                if (!ess.getSettings().hidePermissionlessHelp()) {
                  retval.add("§c" + k.getKey() + "§7: " + value.get("description"));
                }
              }
            }
          }
        }
      } catch (NullPointerException ex) {
        continue;
      } catch (Exception ex) {
        if (!reported) {
          logger.log(Level.WARNING, "Error getting help for:" + pluginName, ex);
        }
        reported = true;
        continue;
      }
    }
    return retval;
  }
Пример #15
0
 private String getUsername(final User user) {
   return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
 }
Пример #16
0
	@Override
	public boolean onCommandEssentials(final CommandSender sender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module)
	{
		// Allow plugins to override the command via onCommand
		if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName())))
		{
			final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel);
			if (pc != null)
			{
				alternativeCommandsHandler.executed(commandLabel, pc.getLabel());
				try
				{
					return pc.execute(sender, commandLabel, args);
				}
				catch (final Exception ex)
				{
					Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
					sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
					return true;
				}
			}
		}

		try
		{
			User user = null;
			if (sender instanceof Player)
			{
				user = getUser(sender);
				LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)));
			}

			// New mail notification
			if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
			{
				final List<String> mail = user.getMails();
				if (mail != null && !mail.isEmpty())
				{
					user.sendMessage(_("youHaveNewMail", mail.size()));
				}
			}

			// Check for disabled commands
			if (getSettings().isCommandDisabled(commandLabel))
			{
				return true;
			}

			IEssentialsCommand cmd;
			try
			{
				cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
				cmd.setEssentials(this);
				cmd.setEssentialsModule(module);
			}
			catch (Exception ex)
			{
				sender.sendMessage(_("commandNotLoaded", commandLabel));
				LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandLabel), ex);
				return true;
			}

			// Check authorization
			if (user != null && !user.isAuthorized(cmd, permissionPrefix))
			{
				LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName()));
				user.sendMessage(_("noAccessCommand"));
				return true;
			}

			// Run the command
			try
			{
				if (user == null)
				{
					cmd.run(getServer(), sender, commandLabel, command, args);
				}
				else
				{
					cmd.run(getServer(), user, commandLabel, command, args);
				}
				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)
			{
				showError(sender, ex, commandLabel);
				return true;
			}
		}
		catch (Throwable ex)
		{
			LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex);
			return true;
		}
	}
	@EventHandler(priority = EventPriority.LOWEST)
	public void onEntityDamage(final EntityDamageByEntityEvent event)
	{
		final Entity eAttack = event.getDamager();
		final Entity eDefend = event.getEntity();
		if (eDefend instanceof Player && eAttack instanceof Player)
		{
			final User defender = ess.getUser(eDefend);
			final User attacker = ess.getUser(eAttack);
			attacker.updateActivity(true);
			final List<String> commandList = attacker.getPowertool(attacker.getItemInHand());
			if (commandList != null && !commandList.isEmpty())
			{
				for (String command : commandList)
				{
					if (command != null && !command.isEmpty())
					{
						attacker.getServer().dispatchCommand(attacker, command.replaceAll("\\{player\\}", defender.getName()));
						event.setCancelled(true);
						return;
					}
				}
			}
		}
		else if (eDefend instanceof Animals && eAttack instanceof Player)
		{
			final User player = ess.getUser(eAttack);
			final ItemStack hand = player.getItemInHand();
			if (hand != null && hand.getType() == Material.MILK_BUCKET)
			{
				((Animals)eDefend).setAge(-24000);
				hand.setType(Material.BUCKET);
				player.setItemInHand(hand);
				player.updateInventory();
				event.setCancelled(true);
			}
		}
	}
Пример #18
0
  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);
    }
  }