@Override
  public void onPlayerJoin(final PlayerJoinEvent event) {
    ess.getBackup().onPlayerJoin();
    final User user = ess.getUser(event.getPlayer());

    if (ess.getSettings().changeDisplayName()) {
      user.setDisplayName(user.getNick());
    }
    user.updateActivity(false);
    if (user.isAuthorized("essentials.sleepingignored")) {
      user.setSleepingIgnored(true);
    }

    if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) {
      for (String m : ess.getMotd(user, null)) {
        if (m == null) {
          continue;
        }
        user.sendMessage(m);
      }
    }

    if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) {
      final List<String> mail = user.getMails();
      if (mail.isEmpty()) {
        user.sendMessage(Util.i18n("noNewMail"));
      } else {
        user.sendMessage(Util.format("youHaveNewMail", mail.size()));
      }
    }
  }
Пример #2
0
	@Override
	public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
	{
		final double bal = (args.length < 1
							|| !(user.isAuthorized("essentials.balance.others")
								 || user.isAuthorized("essentials.balance.other"))
							? user
							: getPlayer(server, args, 0, true)).getMoney();
		user.sendMessage(_("balance", Util.displayCurrency(bal, ess)));
	}
Пример #3
0
 public final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) {
   final ISign sign = new BlockSign(block);
   final User user = ess.getUser(player);
   try {
     return (user.isAuthorized("essentials.signs." + signName.toLowerCase() + ".break")
             || user.isAuthorized("essentials.signs.break." + signName.toLowerCase()))
         && onSignBreak(sign, user, getUsername(user), ess);
   } catch (SignException ex) {
     ess.showError(user, ex, signName);
     return false;
   }
 }
Пример #4
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));
			}
		}
	}
Пример #5
0
 @Override
 public void setVanished(final boolean set) {
   vanished = set;
   if (set) {
     for (User user : ess.getOnlineUsers()) {
       if (!user.isAuthorized("essentials.vanish.see")) {
         user.getBase().hidePlayer(getBase());
       }
     }
     setHidden(true);
     ess.getVanishedPlayers().add(getName());
     if (isAuthorized("essentials.vanish.effect")) {
       this.getBase()
           .addPotionEffect(
               new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false));
     }
   } else {
     for (Player p : ess.getOnlinePlayers()) {
       p.showPlayer(getBase());
     }
     setHidden(false);
     ess.getVanishedPlayers().remove(getName());
     if (isAuthorized("essentials.vanish.effect")) {
       this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY);
     }
   }
 }
Пример #6
0
  public void checkActivity() {
    final long autoafkkick = ess.getSettings().getAutoAfkKick();
    if (autoafkkick > 0
        && lastActivity > 0
        && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
        && !isHidden()
        && !isAuthorized("essentials.kick.exempt")
        && !isAuthorized("essentials.afk.kickexempt")) {
      final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
      lastActivity = 0;
      this.getBase().kickPlayer(kickReason);

      for (User user : ess.getOnlineUsers()) {
        if (user.isAuthorized("essentials.kick.notify")) {
          user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason));
        }
      }
    }
    final long autoafk = ess.getSettings().getAutoAfk();
    if (!isAfk()
        && autoafk > 0
        && lastActivity + autoafk * 1000 < System.currentTimeMillis()
        && isAuthorized("essentials.afk.auto")) {
      setAfk(true);
      if (!isHidden()) {
        setDisplayNick();
        final String msg = tl("userIsAway", getDisplayName());
        if (!msg.isEmpty()) {
          ess.broadcastMessage(this, msg);
        }
      }
    }
  }
Пример #7
0
  public void checkActivity() {
    final long autoafkkick = ess.getSettings().getAutoAfkKick();
    if (autoafkkick > 0
        && lastActivity + autoafkkick * 1000 < System.currentTimeMillis()
        && !isHidden()
        && !isAuthorized("essentials.kick.exempt")
        && !isAuthorized("essentials.afk.kickexempt")) {
      final String kickReason = Util.format("autoAfkKickReason", autoafkkick / 60.0);
      kickPlayer(kickReason);

      for (Player player : ess.getServer().getOnlinePlayers()) {
        final User user = ess.getUser(player);
        if (user.isAuthorized("essentials.kick.notify")) {
          player.sendMessage(Util.format("playerKicked", Console.NAME, getName(), kickReason));
        }
      }
    }
    final long autoafk = ess.getSettings().getAutoAfk();
    if (!isAfk()
        && autoafk > 0
        && lastActivity + autoafk * 1000 < System.currentTimeMillis()
        && isAuthorized("essentials.afk")) {
      setAfk(true);
      if (!isHidden()) {
        ess.broadcastMessage(this, Util.format("userIsAway", getDisplayName()));
      }
    }
  }
Пример #8
0
  // 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);
    }
  }
 @Override
 protected void run(
     final Server server, final User user, final String commandLabel, final String[] args)
     throws Exception {
   if (args.length == 1) {
     Boolean toggle = matchToggleArgument(args[0]);
     if (toggle == null && user.isAuthorized(othersPermission)) {
       toggleOtherPlayers(server, user.getSource(), args);
     } else {
       togglePlayer(user.getSource(), user, toggle);
     }
   } else if (args.length == 2 && user.isAuthorized(othersPermission)) {
     toggleOtherPlayers(server, user.getSource(), args);
   } else {
     togglePlayer(user.getSource(), user, null);
   }
 }
Пример #10
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		// Which Players(s) / Users(s) are we interested in?
		String userSelector = null;
		if (args.length == 2)
		{
			userSelector = args[1];
		}
		Set<User> users = getUsers(server, sender, userSelector);

		// If no arguments we are reading the time
		if (args.length == 0)
		{
			getUsersTime(sender, users);
			return;
		}

		User user = ess.getUser(sender);
		if (user != null && (!users.contains(user) || users.size() > 1)&& !user.isAuthorized("essentials.ptime.others"))
		{
			user.sendMessage(_("pTimeOthersPermission"));
			return;
		}

		Long ticks;
		// Parse the target time int ticks from args[0]
		String timeParam = args[0];
		boolean relative = true;
		if (timeParam.startsWith("@"))
		{
			relative = false;
			timeParam = timeParam.substring(1);
		}

		if (getAliases.contains(timeParam))
		{
			getUsersTime(sender, users);
			return;
		}
		else if (DescParseTickFormat.meansReset(timeParam))
		{
			ticks = null;
		}
		else
		{
			try
			{
				ticks = DescParseTickFormat.parse(timeParam);
			}
			catch (NumberFormatException e)
			{
				throw new NotEnoughArgumentsException(e);
			}
		}

		setUsersTime(sender, users, ticks, relative);
	}
  @Override
  public void onPlayerChat(final PlayerChatEvent event) {
    if (isAborted(event)) {
      return;
    }

    /**
     * This file should handle detection of the local chat features... if local chat is enabled, we
     * need to handle it here
     */
    final User user = ess.getUser(event.getPlayer());
    final String chatType = getChatType(event.getMessage());
    long radius = ess.getSettings().getChatRadius();
    if (radius < 1) {
      return;
    }
    radius *= radius;
    try {
      if (event.getMessage().length() > 0 && chatType.length() > 0) {
        StringBuilder permission = new StringBuilder();
        permission.append("essentials.chat.").append(chatType);

        StringBuilder command = new StringBuilder();
        command.append("chat-").append(chatType);

        StringBuilder format = new StringBuilder();
        format.append(chatType).append("Format");

        StringBuilder errorMsg = new StringBuilder();
        errorMsg
            .append("notAllowedTo")
            .append(chatType.substring(0, 1).toUpperCase())
            .append(chatType.substring(1));

        if (user.isAuthorized(permission.toString())) {
          charge(user, command.toString());
          event.setMessage(event.getMessage().substring(1));
          event.setFormat(Util.format(format.toString(), event.getFormat()));
          return;
        }

        user.sendMessage(Util.i18n(errorMsg.toString()));
        event.setCancelled(true);
        return;
      }
    } catch (ChargeException ex) {
      ess.showError(user, ex, "Shout");
      event.setCancelled(true);
      return;
    }
    sendLocalChat(user, radius, event);
  }
Пример #12
0
	@Override
	public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
	{
		switch (args.length)
		{
		case 0:
			throw new NotEnoughArgumentsException();

		case 1:
			final User player = getPlayer(server, args, 0);
			if (!player.isTeleportEnabled())
			{
				throw new Exception(_("teleportDisabled", player.getDisplayName()));
			}
			if (user.getWorld() != player.getWorld() && ess.getSettings().getIsWorldTeleportPermissions()
				&& !user.isAuthorized("essentials.world." + player.getWorld().getName()))
			{
				throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName()));
			}
			user.sendMessage(_("teleporting"));
			final Trade charge = new Trade(this.getName(), ess);
			charge.isAffordableFor(user);
			user.getTeleport().teleport(player, charge, TeleportCause.COMMAND);
			throw new NoChargeException();

		default:
			if (!user.isAuthorized("essentials.tp.others"))
			{
				throw new Exception(_("noPerm", "essentials.tp.others"));
			}
			user.sendMessage(_("teleporting"));
			final User target = getPlayer(server, args, 0);
			final User toPlayer = getPlayer(server, args, 1);
			target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND);
			target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName()));
			break;
		}
	}
	@EventHandler(priority = EventPriority.LOWEST)
	public void onPlayerDeathEvent(final PlayerDeathEvent event)
	{
		final User user = ess.getUser(event.getEntity());
		if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back"))
		{
			user.setLastLocation();
			user.sendMessage(_("backAfterDeath"));
		}
		if (!ess.getSettings().areDeathMessagesEnabled())
		{
			event.setDeathMessage("");
		}
	}
Пример #14
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{

		User user = null;
		if (sender instanceof Player)
		{
			user = ess.getUser(((Player)sender));
			if ((args.length < 1 || user != null && !user.isAuthorized("essentials.lightning.others")))
			{
				user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation());
				return;
			}
		}

		int power = 5;
		if (args.length > 1)
		{
			try
			{
				power = Integer.parseInt(args[1]);
			}
			catch (NumberFormatException ex)
			{
			}
		}

		if (args[0].trim().length() < 2)
		{
			throw new Exception(_("playerNotFound"));
		}

		final List<Player> matchedPlayers = server.matchPlayer(args[0]);
		for (Player matchPlayer : matchedPlayers)
		{
			sender.sendMessage(_("lightningUse", matchPlayer.getDisplayName()));

			final LightningStrike strike = matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation());

			if (!ess.getUser(matchPlayer).isGodModeEnabled())
			{
				matchPlayer.damage(power, strike);
			}
			if (ess.getSettings().warnOnSmite())
			{
				matchPlayer.sendMessage(_("lightningSmited"));
			}
		}
	}
Пример #15
0
 public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) {
   final ISign sign = new EventSign(event);
   final User user = ess.getUser(event.getPlayer());
   if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase() + ".create")
       || user.isAuthorized("essentials.signs.create." + signName.toLowerCase()))) {
     // Return true, so other plugins can use the same sign title, just hope
     // they won't change it to §1[Signname]
     return true;
   }
   sign.setLine(0, Util.format("signFormatFail", this.signName));
   try {
     final boolean ret = onSignCreate(sign, user, getUsername(user), ess);
     if (ret) {
       sign.setLine(0, getSuccessName());
     }
     return ret;
   } catch (ChargeException ex) {
     ess.showError(user, ex, signName);
   } catch (SignException ex) {
     ess.showError(user, ex, signName);
   }
   // Return true, so the player sees the wrong sign.
   return true;
 }
Пример #16
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, String[] args) throws Exception
	{
		if (args.length < 1)
		{
			throw new NotEnoughArgumentsException();
		}

		User user = ess.getUser(sender);
		String name;
		String[] expandedArg;

		//Allowing both formats /sethome khobbits house | /sethome khobbits:house
		final String[] nameParts = args[0].split(":");
		if (nameParts[0].length() != args[0].length())
		{
			expandedArg = nameParts;
		}
		else
		{
			expandedArg = args;
		}

		if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others")))
		{
			user = getPlayer(server, expandedArg, 0, true, true);
			name = expandedArg[1];
		}
		else if (user == null)
		{
			throw new NotEnoughArgumentsException();
		}
		else
		{
			name = expandedArg[0];
		}
		
		
		if (name.equalsIgnoreCase("bed")) { throw new Exception(_("invalidHomeName")); }
		
		user.delHome(name.toLowerCase(Locale.ENGLISH));
		sender.sendMessage(_("deleteHome", name));
	}
  @Override
  public void onPlayerLogin(final PlayerLoginEvent event) {
    if (event.getResult() != Result.ALLOWED
        && event.getResult() != Result.KICK_FULL
        && event.getResult() != Result.KICK_BANNED) {
      LOGGER.log(
          Level.INFO,
          "Disconnecting user "
              + event.getPlayer().toString()
              + " due to "
              + event.getResult().toString());
      return;
    }
    User user = ess.getUser(event.getPlayer());
    user.setNPC(false);

    final long currentTime = System.currentTimeMillis();
    boolean banExpired = user.checkBanTimeout(currentTime);
    user.checkMuteTimeout(currentTime);
    user.checkJailTimeout(currentTime);

    if (banExpired == false && (user.isBanned() || event.getResult() == Result.KICK_BANNED)) {
      final String banReason = user.getBanReason();
      event.disallow(
          Result.KICK_BANNED,
          banReason != null && !banReason.isEmpty() && !banReason.equalsIgnoreCase("ban")
              ? banReason
              : Util.i18n("defaultBanReason"));
      return;
    }

    if (server.getOnlinePlayers().length >= server.getMaxPlayers()
        && !user.isAuthorized("essentials.joinfullserver")) {
      event.disallow(Result.KICK_FULL, Util.i18n("serverFull"));
      return;
    }
    event.allow();

    user.setLastLogin(System.currentTimeMillis());
    updateCompass(user);
  }
 @EventHandler(priority = EventPriority.HIGHEST)
 public void onEntityTarget(final EntityTargetEvent event) {
   if (event.isCancelled()) {
     return;
   }
   if (!(event.getTarget() instanceof Player)) {
     return;
   }
   final User user = ess.getUser(event.getTarget());
   if ((event.getReason() == TargetReason.CLOSEST_PLAYER
           || event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY
           || event.getReason() == TargetReason.PIG_ZOMBIE_TARGET
           || event.getReason() == TargetReason.RANDOM_TARGET
           || event.getReason() == TargetReason.TARGET_ATTACKED_OWNER
           || event.getReason() == TargetReason.OWNER_ATTACKED_TARGET)
       && prot.getSettingBool(ProtectConfig.prevent_entitytarget)
       && !user.isAuthorized("essentials.protect.entitytarget.bypass")) {
     event.setCancelled(true);
     return;
   }
 }
Пример #19
0
	//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 kiteItem : kits.getKeys(false))
			{
				if (user.isAuthorized("essentials.kit." + kiteItem.toLowerCase(Locale.ENGLISH)))
				{
					list.append(" ").append(capitalCase(kiteItem));
				}
			}
			return list.toString().trim();
		}
		catch (Exception ex)
		{
			throw new Exception(_("kitError"));
		}

	}
Пример #20
0
  public long getNextUse(final User user) throws Exception {
    if (user.isAuthorized("essentials.kit.exemptdelay")) {
      return 0L;
    }

    final Calendar time = new GregorianCalendar();

    double delay = 0;
    try {
      // Make sure delay is valid
      delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d;
    } catch (Exception e) {
      throw new Exception(tl("kitError2"));
    }

    // When was the last kit used?
    final long lastTime = user.getKitTimestamp(kitName);

    // When can be use the kit again?
    final Calendar delayTime = new GregorianCalendar();
    delayTime.setTimeInMillis(lastTime);
    delayTime.add(Calendar.SECOND, (int) delay);
    delayTime.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));

    if (lastTime == 0L || lastTime > time.getTimeInMillis()) {
      // If we have no record of kit use, or its corrupted, give them benefit of the doubt.
      return 0L;
    } else if (delay < 0d) {
      // If the kit has a negative kit time, it can only be used once.
      return -1;
    } else if (delayTime.before(time)) {
      // If the kit was used in the past, but outside the delay time, it can be used.
      return 0L;
    } else {
      // If the kit has been used recently, return the next time it can be used.
      return delayTime.getTimeInMillis();
    }
  }
Пример #21
0
	@Override
	public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
	{
		// Which World(s) are we interested in?
		String worldSelector = null;
		if (args.length == 2)
		{
			worldSelector = args[1];
		}
		final Set<World> worlds = getWorlds(server, sender, worldSelector);

		// If no arguments we are reading the time
		if (args.length == 0)
		{
			getWorldsTime(sender, worlds);
			return;
		}

		final User user = ess.getUser(sender);
		if (user != null && !user.isAuthorized("essentials.time.set"))
		{
			user.sendMessage(_("timeSetPermission"));
			return;
		}

		// Parse the target time int ticks from args[0]
		long ticks;
		try
		{
			ticks = DescParseTickFormat.parse(args[0]);
		}
		catch (NumberFormatException e)
		{
			throw new NotEnoughArgumentsException();
		}

		setWorldsTime(sender, worlds, ticks);
	}
Пример #22
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);
     }
   }
 }
Пример #23
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;
  }
Пример #24
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);
    }
  }
Пример #25
0
 public void checkPerms(final User user) throws Exception {
   if (!user.isAuthorized("essentials.kits." + kitName)) {
     throw new Exception(tl("noKitPermission", "essentials.kits." + kitName));
   }
 }
  @Override
  public void onPlayerMove(final PlayerMoveEvent event) {
    if (event.isCancelled()) {
      return;
    }
    final User user = ess.getUser(event.getPlayer());

    if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) {
      final Location from = event.getFrom();
      final Location to = event.getTo().clone();
      to.setX(from.getX());
      to.setY(from.getBlock().getTypeId() == 0 ? from.getY() - 1 : from.getY());
      to.setZ(from.getZ());
      event.setTo(to);
      return;
    }

    Location afk = user.getAfkPosition();
    if (afk == null
        || !event.getTo().getWorld().equals(afk.getWorld())
        || afk.distanceSquared(event.getTo()) > 9) {
      user.updateActivity(true);
    }

    if (!ess.getSettings().getNetherPortalsEnabled()) {
      return;
    }

    final Block block =
        event
            .getPlayer()
            .getWorld()
            .getBlockAt(
                event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ());
    final List<World> worlds = server.getWorlds();

    if (block.getType() == Material.PORTAL
        && worlds.size() > 1
        && user.isAuthorized("essentials.portal")) {
      if (user.getJustPortaled()) {
        return;
      }

      World nether = server.getWorld(ess.getSettings().getNetherName());
      if (nether == null) {
        for (World world : worlds) {
          if (world.getEnvironment() == World.Environment.NETHER) {
            nether = world;
            break;
          }
        }
        if (nether == null) {
          return;
        }
      }
      final World world = user.getWorld() == nether ? worlds.get(0) : nether;

      double factor;
      if (user.getWorld().getEnvironment() == World.Environment.NETHER
          && world.getEnvironment() == World.Environment.NORMAL) {
        factor = ess.getSettings().getNetherRatio();
      } else if (user.getWorld().getEnvironment() == World.Environment.NORMAL
          && world.getEnvironment() == World.Environment.NETHER) {
        factor = 1.0 / ess.getSettings().getNetherRatio();
      } else {
        factor = 1.0;
      }

      Location loc = event.getTo();
      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
            || ess.getSettings().getGenerateExitPortals()) {
          portal = NetherPortal.createPortal(dest);
          LOGGER.info(Util.format("userCreatedPortal", event.getPlayer().getName()));
          user.sendMessage(Util.i18n("generatingPortal"));
          loc = portal.getSpawn();
        }
      } else {
        LOGGER.info(Util.format("userUsedPortal", event.getPlayer().getName()));
        user.sendMessage(Util.i18n("usingPortal"));
        loc = portal.getSpawn();
      }

      event.setFrom(loc);
      event.setTo(loc);
      try {
        user.getTeleport().now(loc, new Trade("portal", ess));
      } catch (Exception ex) {
        user.sendMessage(ex.getMessage());
      }
      user.setJustPortaled(true);
      user.sendMessage(Util.i18n("teleportingPortal"));

      event.setCancelled(true);
      return;
    }

    user.setJustPortaled(false);
  }
  @EventHandler(priority = EventPriority.HIGHEST)
  public void onEntityDamage(final EntityDamageEvent event) {
    if (event.isCancelled()) {
      return;
    }
    final Entity target = event.getEntity();

    if (target instanceof Villager && prot.getSettingBool(ProtectConfig.prevent_villager_death)) {
      event.setCancelled(true);
      return;
    }

    final User user = ess.getUser(target);
    if (event instanceof EntityDamageByBlockEvent) {
      final DamageCause cause = event.getCause();

      if (prot.getSettingBool(ProtectConfig.disable_contactdmg)
          && cause == DamageCause.CONTACT
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.contact")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
      if (prot.getSettingBool(ProtectConfig.disable_lavadmg)
          && cause == DamageCause.LAVA
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.lava")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
      if (prot.getSettingBool(ProtectConfig.prevent_tnt_explosion)
          && cause == DamageCause.BLOCK_EXPLOSION
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.tnt")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
    }

    if (event instanceof EntityDamageByEntityEvent) {
      final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent) event;
      final Entity eAttack = edEvent.getDamager();
      final User attacker = ess.getUser(eAttack);

      // PVP Settings
      if (target instanceof Player
          && eAttack instanceof Player
          && prot.getSettingBool(ProtectConfig.disable_pvp)
          && (!user.isAuthorized("essentials.protect.pvp")
              || !attacker.isAuthorized("essentials.protect.pvp"))) {
        event.setCancelled(true);
        return;
      }

      // Creeper explode prevention
      if (eAttack instanceof Creeper
          && prot.getSettingBool(ProtectConfig.prevent_creeper_explosion)
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.creeper")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }

      if (eAttack instanceof Creeper
          && prot.getSettingBool(ProtectConfig.prevent_creeper_playerdmg)
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.creeper")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }

      if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball)
          && prot.getSettingBool(ProtectConfig.prevent_fireball_playerdmg)
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.fireball")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }

      if (eAttack instanceof TNTPrimed
          && prot.getSettingBool(ProtectConfig.prevent_tnt_playerdmg)
          && !(target instanceof Player
              && user.isAuthorized("essentials.protect.damage.tnt")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }

      if (edEvent.getDamager() instanceof Projectile
          && target instanceof Player
          && ((prot.getSettingBool(ProtectConfig.disable_projectiles)
                  && !(user.isAuthorized("essentials.protect.damage.projectiles")
                      && !user.isAuthorized("essentials.protect.damage.disable")))
              || (((Projectile) edEvent.getDamager()).getShooter() instanceof Player
                  && prot.getSettingBool(ProtectConfig.disable_pvp)
                  && (!user.isAuthorized("essentials.protect.pvp")
                      || !ess.getUser(((Projectile) edEvent.getDamager()).getShooter())
                          .isAuthorized("essentials.protect.pvp"))))) {
        event.setCancelled(true);
        return;
      }
    }

    final DamageCause cause = event.getCause();
    if (target instanceof Player) {
      if (cause == DamageCause.FALL
          && prot.getSettingBool(ProtectConfig.disable_fall)
          && !(user.isAuthorized("essentials.protect.damage.fall")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }

      if (cause == DamageCause.SUFFOCATION
          && prot.getSettingBool(ProtectConfig.disable_suffocate)
          && !(user.isAuthorized("essentials.protect.damage.suffocation")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
      if ((cause == DamageCause.FIRE || cause == DamageCause.FIRE_TICK)
          && prot.getSettingBool(ProtectConfig.disable_firedmg)
          && !(user.isAuthorized("essentials.protect.damage.fire")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
      if (cause == DamageCause.DROWNING
          && prot.getSettingBool(ProtectConfig.disable_drown)
          && !(user.isAuthorized("essentials.protect.damage.drowning")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
      if (cause == DamageCause.LIGHTNING
          && prot.getSettingBool(ProtectConfig.disable_lightning)
          && !(user.isAuthorized("essentials.protect.damage.lightning")
              && !user.isAuthorized("essentials.protect.damage.disable"))) {
        event.setCancelled(true);
        return;
      }
    }
  }
Пример #28
0
	public static void expandItems(final IEssentials ess, final User user, final List<String> items) throws Exception
	{
		try
		{
			boolean spew = false;
			for (String d : items)
			{
				final String[] parts = d.split(" ");
				final String[] item = parts[0].split("[:+',;.]", 2);
				final int id = Material.getMaterial(Integer.parseInt(item[0])).getId();
				final short data = item.length > 1 ? Short.parseShort(item[1]) : 0;
				final int amount = parts.length > 1 ? Integer.parseInt(parts[1]) : 1;

				final ItemStack stack = new ItemStack(id, amount, data);
				if (parts.length > 2)
				{
					for (int i = 2; i < parts.length; i++)
					{
						final String[] split = parts[i].split("[:+',;.]", 2);
						if (split.length < 1)
						{
							continue;
						}
						final Enchantment enchantment = Commandenchant.getEnchantment(split[0], user);
						int level;
						if (split.length > 1)
						{
							level = Integer.parseInt(split[1]);
						}
						else
						{
							level = enchantment.getMaxLevel();
						}
						stack.addEnchantment(enchantment, level);
					}
				}

				final Map<Integer, ItemStack> overfilled;
				if (user.isAuthorized("essentials.oversizedstacks"))
				{
					overfilled = InventoryWorkaround.addItem(user.getInventory(), true, ess.getSettings().getOversizedStackSize(), stack);
				}
				else
				{
					overfilled = InventoryWorkaround.addItem(user.getInventory(), true, new ItemStack(id, amount, data));
				}
				for (ItemStack itemStack : overfilled.values())
				{
					user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
					spew = true;
				}
			}
			user.updateInventory();
			if (spew)
			{
				user.sendMessage(_("kitInvFull"));
			}
		}
		catch (Exception e)
		{
			user.updateInventory();
			throw new Exception(_("kitError2"));
		}
	}
Пример #29
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;
		}
	}
  @Override
  public void run(Server server, User user, String commandLabel, String[] args) throws Exception {
    if (args.length < 1) {
      throw new NotEnoughArgumentsException();
    }

    User target = user;

    if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) {
      target = getPlayer(server, args, 1);
    }

    if (args[0].equalsIgnoreCase("list")) {
      StringBuilder sb = new StringBuilder();
      sb.append(Util.i18n("unlimitedItems")).append(" ");
      boolean first = true;
      List<Integer> items = target.getUnlimited();
      if (items.isEmpty()) {
        sb.append(Util.i18n("none"));
      }
      for (Integer integer : items) {
        if (!first) {
          sb.append(", ");
        }
        first = false;
        String matname = Material.getMaterial(integer).toString().toLowerCase().replace("_", "");
        sb.append(matname);
      }
      user.sendMessage(sb.toString());
      return;
    }

    final ItemStack stack = ess.getItemDb().get(args[0], 1);
    stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2));

    String itemname = stack.getType().toString().toLowerCase().replace("_", "");
    if (!user.isAuthorized("essentials.unlimited.item-all")
        && !user.isAuthorized("essentials.unlimited.item-" + itemname)
        && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId())
        && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET)
            && user.isAuthorized("essentials.unlimited.item-bucket"))) {
      user.sendMessage(Util.format("unlimitedItemPermission", itemname));
      return;
    }

    if (target.hasUnlimited(stack)) {
      if (user != target) {
        user.sendMessage(Util.format("disableUnlimited", itemname, target.getDisplayName()));
      }
      target.sendMessage(Util.format("disableUnlimited", itemname, target.getDisplayName()));
      target.setUnlimited(stack, false);
      return;
    }
    charge(user);
    if (user != target) {
      user.sendMessage(Util.format("enableUnlimited", itemname, target.getDisplayName()));
    }
    target.sendMessage(Util.format("enableUnlimited", itemname, target.getDisplayName()));
    if (!InventoryWorkaround.containsItem(target.getInventory(), true, stack)) {
      target.getInventory().addItem(stack);
    }
    target.setUnlimited(stack, true);
  }