@EventHandler(priority = EventPriority.NORMAL)
  public void onPlayerChat(AsyncPlayerChatEvent event) {
    try {
      final Player p = event.getPlayer();
      String message = event.getMessage().trim();

      TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);
      playerdata.incrementMsgCount();

      // Check for spam
      if (playerdata.getMsgCount() > 10) {
        TFM_Util.bcastMsg(
            p.getName() + " was automatically kicked for spamming chat.", ChatColor.RED);
        TFM_Util.autoEject(p, "Kicked for spamming chat.");

        playerdata.resetMsgCount();

        event.setCancelled(true);
        return;
      }

      // Check for message repeat
      if (playerdata.getLastMessage().equalsIgnoreCase(message)) {
        TFM_Util.playerMsg(p, "Please do not repeat messages.");
        event.setCancelled(true);
        return;
      }
      playerdata.setLastMessage(message);

      // Check for muted
      if (playerdata.isMuted()) {
        if (!TFM_SuperadminList.isUserSuperadmin(p)) {
          p.sendMessage(ChatColor.RED + "You are muted, STFU!");
          event.setCancelled(true);
          return;
        } else {
          playerdata.setMuted(false);
        }
      }

      // Strip color from messages
      message = ChatColor.stripColor(message);

      // Truncate messages that are too long - 100 characters is vanilla client max
      if (message.length() > 100) {
        message = message.substring(0, 100);
        TFM_Util.playerMsg(p, "Message was shortened because it was too long to send.");
      }

      // Check for caps
      if (message.length() >= 6) {
        int caps = 0;
        for (char c : message.toCharArray()) {
          if (Character.isUpperCase(c)) {
            caps++;
          }
        }
        if (((float) caps / (float) message.length())
            > 0.65) // Compute a ratio so that longer sentences can have more caps.
        {
          message = message.toLowerCase();
        }
      }

      // Check for adminchat
      if (playerdata.inAdminChat()) {
        TFM_Util.adminChatMessage(p, message, false);
        event.setCancelled(true);
        return;
      }

      // Finally, set message
      event.setMessage(message);

      // Set the tag
      if (playerdata.getTag() != null) {
        p.setDisplayName((playerdata.getTag() + " " + p.getDisplayName().replaceAll(" ", "")));
      }

    } catch (Exception ex) {
      TFM_Log.severe(ex);
    }
  }
  public void setFrozen(boolean freeze) {
    cancel(unfreezeTask);
    unfreezeTask = null;
    freezeLocation = null;

    if (player.getGameMode() != GameMode.CREATIVE) {
      TFM_Util.setFlying(player, false);
    }

    if (!freeze) {
      return;
    }

    freezeLocation = player.getLocation(); // Blockify location
    TFM_Util.setFlying(player, true); // Avoid infinite falling

    unfreezeTask =
        new BukkitRunnable() {
          @Override
          public void run() {
            TFM_Util.adminAction("TotalFreedom", "Unfreezing " + player.getName(), false);
            setFrozen(false);
          }
        }.runTaskLater(TotalFreedomMod.plugin, AUTO_PURGE);
  }
  @EventHandler(priority = EventPriority.MONITOR)
  public void onPlayerJoin(PlayerJoinEvent event) {
    try {
      final Player p = event.getPlayer();
      final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);
      playerdata.setSuperadminIdVerified(null);

      TFM_UserList.getInstance(TotalFreedomMod.plugin).addUser(p);

      boolean superadmin_impostor = TFM_SuperadminList.isSuperadminImpostor(p);

      if (superadmin_impostor || TFM_SuperadminList.isUserSuperadmin(p)) {
        TFM_Util.bcastMsg(ChatColor.AQUA + p.getName() + " is " + TFM_Util.getRank(p));

        if (superadmin_impostor) {
          p.getInventory().clear();
          p.setOp(false);
          p.setGameMode(GameMode.SURVIVAL);
          TFM_Util.bcastMsg(
              "Warning: " + p.getName() + " has been flagged as an impostor!", ChatColor.RED);
        } else {
          if (TFM_SuperadminList.verifyIdentity(
              p.getName(), p.getAddress().getAddress().getHostAddress())) {
            playerdata.setSuperadminIdVerified(Boolean.TRUE);

            TFM_SuperadminList.updateLastLogin(p);
          } else {
            playerdata.setSuperadminIdVerified(Boolean.FALSE);

            TFM_Util.bcastMsg(
                "Warning: "
                    + p.getName()
                    + " is an admin, but is using a username not registered to one of their IPs.",
                ChatColor.RED);
          }

          p.setOp(true);
        }
      }

      if (TotalFreedomMod.adminOnlyMode) {
        new BukkitRunnable() {
          @Override
          public void run() {
            p.sendMessage(ChatColor.RED + "Server is currently closed to non-superadmins.");
          }
        }.runTaskLater(TotalFreedomMod.plugin, 20L * 3L);
      }
    } catch (Throwable ex) {
    }
  }
  public static TFM_PlayerData getPlayerData(Player player) {
    final String ip = TFM_Util.getIp(player);

    TFM_PlayerData data = TFM_PlayerData.PLAYER_DATA.get(ip);

    if (data != null) {
      return data;
    }

    if (Bukkit.getOnlineMode()) {
      for (TFM_PlayerData dataTest : PLAYER_DATA.values()) {
        if (dataTest.player.getName().equalsIgnoreCase(player.getName())) {
          data = dataTest;
          break;
        }
      }
    }

    if (data != null) {
      return data;
    }

    data = new TFM_PlayerData(player, TFM_UuidManager.getUniqueId(player), ip);
    TFM_PlayerData.PLAYER_DATA.put(ip, data);

    return data;
  }
  public void setHalted(boolean halted) {
    this.isHalted = halted;

    if (halted) {
      player.setOp(false);
      player.setGameMode(GameMode.SURVIVAL);
      TFM_Util.setFlying(player, false);
      TFM_EssentialsBridge.setNickname(player.getName(), player.getName());
      player.closeInventory();
      player.setTotalExperience(0);

      stopOrbiting();
      setFrozen(true);
      setMuted(true);

      player.sendMessage(ChatColor.GRAY + "You have been halted, don't move!");
    } else {
      player.setOp(true);
      player.setGameMode(GameMode.CREATIVE);
      setFrozen(false);
      setMuted(false);

      player.sendMessage(ChatColor.GRAY + "You are no longer halted.");
    }
  }
 public void setTag(String tag) {
   if (tag == null) {
     this.tag = null;
   } else {
     this.tag = TFM_Util.colorize(tag) + ChatColor.WHITE;
   }
 }
    private void doActions(CommandSender sender) {
      if (this.action == CommandBlockerAction.BLOCK_AND_EJECT && sender instanceof Player) {
        TFM_Util.autoEject((Player) sender, "You used a prohibited command: " + this.command);
        TFM_Util.bcastMsg(
            sender.getName() + " was automatically kicked for using harmful commands.",
            ChatColor.RED);
      } else {
        String response;

        if (this.action == CommandBlockerAction.BLOCK_UNKNOWN) {
          response = "Unknown command. Type \"help\" for help.";
        } else if (this.message == null || "_".equals(this.message)) {
          response = ChatColor.GRAY + "That command is blocked.";
        } else {
          response = ChatColor.GRAY + TFM_Util.colorize(this.message);
        }

        sender.sendMessage(response);
      }
    }
  public void incrementWarnings() {
    this.warningCount++;

    if (this.warningCount % 2 == 0) {
      this.player.getWorld().strikeLightning(this.player.getLocation());
      TFM_Util.playerMsg(
          this.player,
          ChatColor.RED
              + "You have been warned at least twice now, make sure to read the rules at "
              + TFM_ConfigEntry.SERVER_BAN_URL.getString());
    }
  }
Exemplo n.º 9
0
  public static void createBackups(String file) {
    final String save = file.split("\\.")[0];
    final TFM_Config config = new TFM_Config(TotalFreedomMod.plugin, "backup.yml", false);
    config.load();

    // Daily
    if (!config.isInt(save + ".daily")) {
      performBackup(file, "daily");
      config.set(save + ".daily", TFM_Util.getUnixTime());
    } else {
      int lastBackupDaily = config.getInt(save + ".daily");

      if (lastBackupDaily + 3600 * 24 < TFM_Util.getUnixTime()) {
        performBackup(file, "daily");
        config.set(save + ".daily", TFM_Util.getUnixTime());
      }
    }

    // Weekly
    if (!config.isInt(save + ".weekly")) {
      performBackup(file, "weekly");
      config.set(save + ".weekly", TFM_Util.getUnixTime());
    } else {
      int lastBackupWeekly = config.getInt(save + ".weekly");

      if (lastBackupWeekly + 3600 * 24 * 7 < TFM_Util.getUnixTime()) {
        performBackup(file, "weekly");
        config.set(save + ".weekly", TFM_Util.getUnixTime());
      }
    }

    config.save();
  }
Exemplo n.º 10
0
  public static String getIp(OfflinePlayer player) {
    if (player instanceof Player) {
      return ((Player) player).getAddress().getAddress().getHostAddress().trim();
    }

    final TFM_Player entry = TFM_PlayerList.getEntry(TFM_Util.getUuid(player));

    if (entry == null) {
      return null;
    }

    return entry.getIps().get(0);
  }
  @Override
  public void run() {
    for (Player p : server.getOnlinePlayers()) {
      TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);
      playerdata.resetMsgCount();
      playerdata.resetBlockDestroyCount();
      playerdata.resetBlockPlaceCount();
    }

    if (TotalFreedomMod.autoEntityWipe) {
      TFM_Util.wipeEntities(!TotalFreedomMod.allowExplosions, false);
    }

    if (TotalFreedomMod.disableNight) {
      try {
        for (World world : server.getWorlds()) {
          if (world.getTime() > 12000L) {
            TFM_Util.setWorldTime(world, 1000L);
          }
        }
      } catch (NullPointerException ex) {
      }
    }

    if (TotalFreedomMod.disableWeather) {
      for (World world : server.getWorlds()) {
        if (world.getWeatherDuration() > 0) {
          world.setThundering(false);
          world.setWeatherDuration(0);
        } else if (world.getThunderDuration() > 0) {
          world.setStorm(false);
          world.setThunderDuration(0);
        }
      }
    }
  }
Exemplo n.º 12
0
  public static boolean getSavedFlag(String flag) throws Exception {
    Boolean flagValue = null;

    Map<String, Boolean> flags = TFM_Util.getSavedFlags();

    if (flags != null) {
      if (flags.containsKey(flag)) {
        flagValue = flags.get(flag);
      }
    }

    if (flagValue != null) {
      return flagValue.booleanValue();
    } else {
      throw new Exception();
    }
  }
Exemplo n.º 13
0
  public static void setSavedFlag(String flag, boolean value) {
    Map<String, Boolean> flags = TFM_Util.getSavedFlags();

    if (flags == null) {
      flags = new HashMap<String, Boolean>();
    }

    flags.put(flag, value);

    try {
      final FileOutputStream fos =
          new FileOutputStream(
              new File(TotalFreedomMod.plugin.getDataFolder(), TotalFreedomMod.SAVED_FLAGS_FILE));
      final ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(flags);
      oos.close();
      fos.close();
    } catch (Exception ex) {
      TFM_Log.severe(ex);
    }
  }
Exemplo n.º 14
0
  public boolean isCommandBlocked(String command, CommandSender sender, boolean doAction) {
    if (command == null || command.isEmpty()) {
      return false;
    }

    final Matcher matcher = COMMAND_PATTERN.matcher(command);
    if (matcher.find()) {
      command = matcher.group(1);
      if (command == null) {
        return false;
      } else {
        command = command.toLowerCase().trim();
      }
    } else {
      return false;
    }

    if (command.contains(":")) {
      TFM_Util.playerMsg(sender, "Plugin-specific commands are disabled.");
      return true;
    }

    final CommandBlockerEntry entry = blockedCommands.get(command);

    if (entry != null) {
      if (!entry.getRank().hasPermission(sender)) {
        if (doAction) {
          entry.doActions(sender);
        }

        return true;
      }
    }

    return false;
  }
Exemplo n.º 15
0
  public static void autoEject(Player player, String kickMessage) {
    EjectMethod method = EjectMethod.STRIKE_ONE;
    final String ip = TFM_Util.getIp(player);

    if (!TFM_Util.ejectTracker.containsKey(ip)) {
      TFM_Util.ejectTracker.put(ip, 0);
    }

    int kicks = TFM_Util.ejectTracker.get(ip);
    kicks += 1;

    TFM_Util.ejectTracker.put(ip, kicks);

    if (kicks <= 1) {
      method = EjectMethod.STRIKE_ONE;
    } else if (kicks == 2) {
      method = EjectMethod.STRIKE_TWO;
    } else if (kicks >= 3) {
      method = EjectMethod.STRIKE_THREE;
    }

    TFM_Log.info(
        "AutoEject -> name: "
            + player.getName()
            + " - player ip: "
            + ip
            + " - method: "
            + method.toString());

    player.setOp(false);
    player.setGameMode(GameMode.SURVIVAL);
    player.getInventory().clear();

    switch (method) {
      case STRIKE_ONE:
        {
          final Calendar cal = new GregorianCalendar();
          cal.add(Calendar.MINUTE, 1);
          final Date expires = cal.getTime();

          TFM_Util.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 1 minute.");

          TFM_BanManager.addIpBan(
              new TFM_Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
          TFM_BanManager.addUuidBan(
              new TFM_Ban(
                  TFM_Util.getUuid(player), player.getName(), "AutoEject", expires, kickMessage));
          player.kickPlayer(kickMessage);

          break;
        }
      case STRIKE_TWO:
        {
          final Calendar c = new GregorianCalendar();
          c.add(Calendar.MINUTE, 3);
          final Date expires = c.getTime();

          TFM_Util.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 3 minutes.");

          TFM_BanManager.addIpBan(
              new TFM_Ban(ip, player.getName(), "AutoEject", expires, kickMessage));
          TFM_BanManager.addUuidBan(
              new TFM_Ban(
                  TFM_Util.getUuid(player), player.getName(), "AutoEject", expires, kickMessage));
          player.kickPlayer(kickMessage);
          break;
        }
      case STRIKE_THREE:
        {
          String[] ipAddressParts = ip.split("\\.");

          TFM_BanManager.addIpBan(
              new TFM_Ban(ip, player.getName(), "AutoEject", null, kickMessage));
          TFM_BanManager.addIpBan(
              new TFM_Ban(
                  ipAddressParts[0] + "." + ipAddressParts[1] + ".*.*",
                  player.getName(),
                  "AutoEject",
                  null,
                  kickMessage));
          TFM_BanManager.addUuidBan(
              new TFM_Ban(
                  TFM_Util.getUuid(player), player.getName(), "AutoEject", null, kickMessage));

          TFM_Util.bcastMsg(ChatColor.RED + player.getName() + " has been banned.");

          player.kickPlayer(kickMessage);
          break;
        }
    }
  }
Exemplo n.º 16
0
  public static void handlePlayerLogin(PlayerLoginEvent event) {
    final Server server = TotalFreedomMod.server;
    final Player player = event.getPlayer();
    final String username = player.getName();
    final String ip = event.getAddress().getHostAddress().trim();
    final UUID uuid = TFM_UuidManager.newPlayer(player, ip);

    // Check username length
    if (username.length() < 3 || username.length() > TotalFreedomMod.MAX_USERNAME_LENGTH) {
      event.disallow(
          Result.KICK_OTHER,
          "Your username is an invalid length (must be between 3 and 20 characters long).");
      return;
    }

    // Check username characters
    if (!USERNAME_REGEX.matcher(username).find()) {
      event.disallow(Result.KICK_OTHER, "Your username contains invalid characters.");
      return;
    }

    // Check force-IP match
    if (TFM_ConfigEntry.FORCE_IP_ENABLED.getBoolean()) {
      final String hostname =
          event
              .getHostname()
              .replace(
                  "\u0000FML\u0000",
                  ""); // Forge fix - https://github.com/TotalFreedom/TotalFreedomMod/issues/493
      final String connectAddress = TFM_ConfigEntry.SERVER_ADDRESS.getString();
      final int connectPort = TotalFreedomMod.server.getPort();

      if (!hostname.equalsIgnoreCase(connectAddress + ":" + connectPort)
          && !hostname.equalsIgnoreCase(connectAddress + ".:" + connectPort)) {
        final int forceIpPort = TFM_ConfigEntry.FORCE_IP_PORT.getInteger();
        event.disallow(
            PlayerLoginEvent.Result.KICK_OTHER,
            TFM_ConfigEntry.FORCE_IP_KICKMSG
                .getString()
                .replace(
                    "%address%",
                    TFM_ConfigEntry.SERVER_ADDRESS.getString()
                        + (forceIpPort == TFM_PlayerListener.DEFAULT_PORT
                            ? ""
                            : ":" + forceIpPort)));
        return;
      }
    }

    // Check if player is admin
    // Not safe to use TFM_Util.isSuperAdmin(player) because player.getAddress() will return a null
    // until after player login.
    final boolean isAdmin = TFM_AdminList.isSuperAdminSafe(uuid, ip);

    // Validation below this point
    if (isAdmin) // Player is superadmin
    {
      // Force-allow log in
      event.allow();

      int count = server.getOnlinePlayers().size();
      if (count >= server.getMaxPlayers()) {
        for (Player onlinePlayer : server.getOnlinePlayers()) {
          if (!TFM_AdminList.isSuperAdmin(onlinePlayer)) {
            onlinePlayer.kickPlayer("You have been kicked to free up room for an admin.");
            count--;
          }

          if (count < server.getMaxPlayers()) {
            break;
          }
        }
      }

      if (count >= server.getMaxPlayers()) {
        event.disallow(
            Result.KICK_OTHER, "The server is full and a player could not be kicked, sorry!");
        return;
      }

      return;
    }

    // Player is not an admin
    // Server full check
    if (server.getOnlinePlayers().size() >= server.getMaxPlayers()) {
      event.disallow(Result.KICK_FULL, "Sorry, but this server is full.");
      return;
    }

    // Admin-only mode
    if (TFM_ConfigEntry.ADMIN_ONLY_MODE.getBoolean()) {
      event.disallow(Result.KICK_OTHER, "Server is temporarily open to admins only.");
      return;
    }

    // Lockdown mode
    if (TotalFreedomMod.lockdownEnabled) {
      event.disallow(Result.KICK_OTHER, "Server is currently in lockdown mode.");
      return;
    }

    // Whitelist
    if (isWhitelisted()) {
      if (!getWhitelisted().contains(username.toLowerCase())) {
        event.disallow(Result.KICK_OTHER, "You are not whitelisted on this server.");
        return;
      }
    }

    // UUID ban
    if (TFM_BanManager.isUuidBanned(uuid)) {
      final TFM_Ban ban = TFM_BanManager.getByUuid(uuid);
      event.disallow(Result.KICK_OTHER, ban.getKickMessage());
      return;
    }

    // IP ban
    if (TFM_BanManager.isIpBanned(ip)) {
      final TFM_Ban ban = TFM_BanManager.getByIp(ip);
      event.disallow(Result.KICK_OTHER, ban.getKickMessage());
      return;
    }

    // Permbanned IPs
    for (String testIp : TFM_PermbanList.getPermbannedIps()) {
      if (TFM_Util.fuzzyIpMatch(testIp, ip, 4)) {
        event.disallow(
            Result.KICK_OTHER,
            ChatColor.RED
                + "Your IP address is permanently banned from this server.\n"
                + "Release procedures are available at\n"
                + ChatColor.GOLD
                + TFM_ConfigEntry.SERVER_PERMBAN_URL.getString());
        return;
      }
    }

    // Permbanned usernames
    for (String testPlayer : TFM_PermbanList.getPermbannedPlayers()) {
      if (testPlayer.equalsIgnoreCase(username)) {
        event.disallow(
            Result.KICK_OTHER,
            ChatColor.RED
                + "Your username is permanently banned from this server.\n"
                + "Release procedures are available at\n"
                + ChatColor.GOLD
                + TFM_ConfigEntry.SERVER_PERMBAN_URL.getString());
        return;
      }
    }
  }
  @EventHandler(priority = EventPriority.NORMAL)
  public void onPlayerMove(PlayerMoveEvent event) {
    final Location from = event.getFrom();
    final Location to = event.getTo();
    try {
      if (from.getWorld() == to.getWorld() && from.distanceSquared(to) < (0.0001 * 0.0001)) {
        // If player just rotated, but didn't move, don't process this event.
        return;
      }
    } catch (IllegalArgumentException ex) {
    }

    if (!TFM_AdminWorld.getInstance().validateMovement(event)) {
      return;
    }

    Player player = event.getPlayer();
    TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);

    for (Entry<Player, Double> fuckoff : TotalFreedomMod.fuckoffEnabledFor.entrySet()) {
      Player fuckoffPlayer = fuckoff.getKey();

      if (fuckoffPlayer.equals(player) || !fuckoffPlayer.isOnline()) {
        continue;
      }

      double fuckoffRange = fuckoff.getValue().doubleValue();

      Location playerLocation = player.getLocation();
      Location fuckoffLocation = fuckoffPlayer.getLocation();

      double distanceSquared;
      try {
        distanceSquared = playerLocation.distanceSquared(fuckoffLocation);
      } catch (IllegalArgumentException ex) {
        continue;
      }

      if (distanceSquared < (fuckoffRange * fuckoffRange)) {
        event.setTo(
            fuckoffLocation
                .clone()
                .add(
                    playerLocation
                        .subtract(fuckoffLocation)
                        .toVector()
                        .normalize()
                        .multiply(fuckoffRange * 1.1)));
        break;
      }
    }

    boolean freeze = false;
    if (TotalFreedomMod.allPlayersFrozen) {
      if (!TFM_AdminList.isSuperAdmin(player)) {
        freeze = true;
      }
    } else {
      if (playerdata.isFrozen()) {
        freeze = true;
      }
    }

    if (freeze) {
      Location freezeTo = to.clone();

      freezeTo.setX(from.getX());
      freezeTo.setY(from.getY());
      freezeTo.setZ(from.getZ());

      event.setTo(freezeTo);
    }

    if (playerdata.isCaged()) {
      Location targetPos = player.getLocation().add(0, 1, 0);

      boolean outOfCage;
      if (!targetPos.getWorld().equals(playerdata.getCagePos().getWorld())) {
        outOfCage = true;
      } else {
        outOfCage = targetPos.distanceSquared(playerdata.getCagePos()) > (2.5 * 2.5);
      }

      if (outOfCage) {
        playerdata.setCaged(
            true,
            targetPos,
            playerdata.getCageMaterial(TFM_PlayerData.CageLayer.OUTER),
            playerdata.getCageMaterial(TFM_PlayerData.CageLayer.INNER));
        playerdata.regenerateHistory();
        playerdata.clearHistory();
        TFM_Util.buildHistory(targetPos, 2, playerdata);
        TFM_Util.generateHollowCube(
            targetPos, 2, playerdata.getCageMaterial(TFM_PlayerData.CageLayer.OUTER));
        TFM_Util.generateCube(
            targetPos, 1, playerdata.getCageMaterial(TFM_PlayerData.CageLayer.INNER));
      }
    }

    if (playerdata.isOrbiting()) {
      if (player.getVelocity().length() < playerdata.orbitStrength() * (2.0 / 3.0)) {
        player.setVelocity(new Vector(0, playerdata.orbitStrength(), 0));
      }
    }

    if (TFM_Jumppads.getInstance().getMode().isOn()) {
      TFM_Jumppads.getInstance().PlayerMoveEvent(event);
    }

    if (!(TFM_ConfigEntry.LANDMINES_ENABLED.getBoolean()
        && TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())) {
      return;
    }

    Iterator<Command_landmine.TFM_LandmineData> landmines =
        Command_landmine.TFM_LandmineData.landmines.iterator();
    while (landmines.hasNext()) {
      Command_landmine.TFM_LandmineData landmine = landmines.next();

      Location location = landmine.location;
      if (location.getBlock().getType() != Material.TNT) {
        landmines.remove();
        continue;
      }

      if (landmine.player.equals(player)) {
        break;
      }

      if (!player.getWorld().equals(location.getWorld())) {
        break;
      }

      if (!(player.getLocation().distanceSquared(location)
          <= (landmine.radius * landmine.radius))) {
        break;
      }

      landmine.location.getBlock().setType(Material.AIR);

      TNTPrimed tnt1 = location.getWorld().spawn(location, TNTPrimed.class);
      tnt1.setFuseTicks(40);
      tnt1.setPassenger(player);
      tnt1.setVelocity(new Vector(0.0, 2.0, 0.0));

      TNTPrimed tnt2 = location.getWorld().spawn(player.getLocation(), TNTPrimed.class);
      tnt2.setFuseTicks(1);

      player.setGameMode(GameMode.SURVIVAL);
      landmines.remove();
    }
  }
 public static boolean hasPlayerData(Player player) {
   return PLAYER_DATA.containsKey(TFM_Util.getIp(player));
 }
  @EventHandler(priority = EventPriority.HIGH)
  public void onPlayerInteract(PlayerInteractEvent event) {
    final Player player = event.getPlayer();
    final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);

    switch (event.getAction()) {
      case RIGHT_CLICK_AIR:
      case RIGHT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case WATER_BUCKET:
              {
                if (TFM_ConfigEntry.ALLOW_WATER_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Water buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case LAVA_BUCKET:
              {
                if (TFM_ConfigEntry.ALLOW_LAVA_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Lava buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case EXPLOSIVE_MINECART:
              {
                if (TFM_ConfigEntry.ALLOW_TNT_MINECARTS.getBoolean()) {
                  break;
                }

                player.getInventory().clear(player.getInventory().getHeldItemSlot());
                player.sendMessage(ChatColor.GRAY + "TNT minecarts are currently disabled.");
                event.setCancelled(true);
                break;
              }
          }
          break;
        }

      case LEFT_CLICK_AIR:
      case LEFT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case STICK:
              {
                if (!TFM_AdminList.isSuperAdmin(player)) {
                  break;
                }

                event.setCancelled(true);

                final Location location = player.getTargetBlock(null, 5).getLocation();
                final List<RollbackEntry> entries =
                    TFM_RollbackManager.getEntriesAtLocation(location);

                if (entries.isEmpty()) {
                  TFM_Util.playerMsg(player, "No block edits at that location.");
                  break;
                }

                TFM_Util.playerMsg(
                    player,
                    "Block edits at ("
                        + ChatColor.WHITE
                        + "x"
                        + location.getBlockX()
                        + ", y"
                        + location.getBlockY()
                        + ", z"
                        + location.getBlockZ()
                        + ChatColor.BLUE
                        + ")"
                        + ChatColor.WHITE
                        + ":",
                    ChatColor.BLUE);
                for (RollbackEntry entry : entries) {
                  TFM_Util.playerMsg(
                      player,
                      " - "
                          + ChatColor.BLUE
                          + entry.author
                          + " "
                          + entry.getType()
                          + " "
                          + StringUtils.capitalize(entry.getMaterial().toString().toLowerCase())
                          + (entry.data == 0 ? "" : ":" + entry.data));
                }

                break;
              }

            case BONE:
              {
                if (!playerdata.mobThrowerEnabled()) {
                  break;
                }

                Location player_pos = player.getLocation();
                Vector direction = player_pos.getDirection().normalize();

                LivingEntity rezzed_mob =
                    (LivingEntity)
                        player
                            .getWorld()
                            .spawnEntity(
                                player_pos.add(direction.multiply(2.0)),
                                playerdata.mobThrowerCreature());
                rezzed_mob.setVelocity(direction.multiply(playerdata.mobThrowerSpeed()));
                playerdata.enqueueMob(rezzed_mob);

                event.setCancelled(true);
                break;
              }

            case SULPHUR:
              {
                if (!playerdata.isMP44Armed()) {
                  break;
                }

                event.setCancelled(true);

                if (playerdata.toggleMP44Firing()) {
                  playerdata.startArrowShooter(TotalFreedomMod.plugin);
                } else {
                  playerdata.stopArrowShooter();
                }
                break;
              }

            case BLAZE_ROD:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                event.setCancelled(true);
                Block targetBlock;

                if (event.getAction().equals(Action.LEFT_CLICK_AIR)) {
                  targetBlock = player.getTargetBlock(null, 120);
                } else {
                  targetBlock = event.getClickedBlock();
                }

                if (targetBlock == null) {
                  player.sendMessage("Can't resolve target block.");
                  break;
                }

                player.getWorld().createExplosion(targetBlock.getLocation(), 4F, true);
                player.getWorld().strikeLightning(targetBlock.getLocation());

                break;
              }

            case CARROT:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                Location location = player.getLocation().clone();

                Vector playerPostion = location.toVector().add(new Vector(0.0, 1.65, 0.0));
                Vector playerDirection = location.getDirection().normalize();

                double distance = 150.0;
                Block targetBlock = player.getTargetBlock(null, Math.round((float) distance));
                if (targetBlock != null) {
                  distance = location.distance(targetBlock.getLocation());
                }

                final List<Block> affected = new ArrayList<Block>();

                Block lastBlock = null;
                for (double offset = 0.0; offset <= distance; offset += (distance / 25.0)) {
                  Block block =
                      playerPostion
                          .clone()
                          .add(playerDirection.clone().multiply(offset))
                          .toLocation(player.getWorld())
                          .getBlock();

                  if (!block.equals(lastBlock)) {
                    if (block.isEmpty()) {
                      affected.add(block);
                      block.setType(Material.TNT);
                    } else {
                      break;
                    }
                  }

                  lastBlock = block;
                }

                new BukkitRunnable() {
                  @Override
                  public void run() {
                    for (Block tntBlock : affected) {
                      TNTPrimed tnt =
                          tntBlock.getWorld().spawn(tntBlock.getLocation(), TNTPrimed.class);
                      tnt.setFuseTicks(5);
                      tntBlock.setType(Material.AIR);
                    }
                  }
                }.runTaskLater(TotalFreedomMod.plugin, 30L);

                event.setCancelled(true);
                break;
              }
          }
          break;
        }
    }
  }
  @EventHandler(priority = EventPriority.NORMAL)
  public void onPlayerChat(AsyncPlayerChatEvent event) {
    try {
      final Player player = event.getPlayer();
      String message = event.getMessage().trim();

      final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);

      // Check for spam
      final Long lastRan = TFM_Heartbeat.getLastRan();
      if (lastRan == null
          || lastRan + TotalFreedomMod.HEARTBEAT_RATE * 1000L < System.currentTimeMillis()) {
        // TFM_Log.warning("Heartbeat service timeout - can't check block place/break rates.");
      } else {
        if (playerdata.incrementAndGetMsgCount() > MSG_PER_HEARTBEAT) {
          TFM_Util.bcastMsg(
              player.getName() + " was automatically kicked for spamming chat.", ChatColor.RED);
          TFM_Util.autoEject(player, "Kicked for spamming chat.");

          playerdata.resetMsgCount();

          event.setCancelled(true);
          return;
        }
      }

      // Check for message repeat
      if (playerdata.getLastMessage().equalsIgnoreCase(message)) {
        TFM_Util.playerMsg(player, "Please do not repeat messages.");
        event.setCancelled(true);
        return;
      }

      playerdata.setLastMessage(message);

      // Check for muted
      if (playerdata.isMuted()) {
        if (!TFM_AdminList.isSuperAdmin(player)) {
          player.sendMessage(ChatColor.RED + "You are muted, STFU!");
          event.setCancelled(true);
          return;
        }

        playerdata.setMuted(false);
      }

      // Strip color from messages
      message = ChatColor.stripColor(message);

      // Truncate messages that are too long - 100 characters is vanilla client max
      if (message.length() > 100) {
        message = message.substring(0, 100);
        TFM_Util.playerMsg(player, "Message was shortened because it was too long to send.");
      }

      // Check for caps
      if (message.length() >= 6) {
        int caps = 0;
        for (char c : message.toCharArray()) {
          if (Character.isUpperCase(c)) {
            caps++;
          }
        }
        if (((float) caps / (float) message.length())
            > 0.65) // Compute a ratio so that longer sentences can have more caps.
        {
          message = message.toLowerCase();
        }
      }

      // Check for adminchat
      if (playerdata.inAdminChat()) {
        TFM_Util.adminChatMessage(player, message, false);
        event.setCancelled(true);
        return;
      }

      // Finally, set message
      event.setMessage(message);

      // Set the tag
      if (playerdata.getTag() != null) {
        player.setDisplayName(
            (playerdata.getTag() + " " + player.getDisplayName().replaceAll(" ", "")));
      }

    } catch (Exception ex) {
      TFM_Log.severe(ex);
    }
  }
  @EventHandler(priority = EventPriority.HIGH)
  public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
    String command = event.getMessage();
    Player p = event.getPlayer();

    TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);
    playerdata.incrementMsgCount();
    playerdata.setLastCommand(command);

    if (playerdata.getMsgCount() > 10) {
      TFM_Util.bcastMsg(
          p.getName() + " was automatically kicked for spamming commands.", ChatColor.RED);
      TFM_Util.autoEject(p, "Kicked for spamming commands.");

      playerdata.resetMsgCount();

      TFM_Util.TFM_EntityWiper.wipeEntities(true, true);

      event.setCancelled(true);
      return;
    }

    if (playerdata.allCommandsBlocked()) {
      TFM_Util.playerMsg(p, "Your commands have been blocked by an admin.", ChatColor.RED);
      event.setCancelled(true);
      return;
    }

    // Block commands if player is muted
    if (playerdata.isMuted()) {
      if (!TFM_SuperadminList.isUserSuperadmin(p)) {
        for (String test_command : BLOCKED_MUTED_CMDS) {
          if (Pattern.compile("^/" + test_command.toLowerCase() + " ").matcher(command).find()) {
            p.sendMessage(ChatColor.RED + "That command is blocked while you are muted.");
            event.setCancelled(true);
            return;
          }
        }
      } else {
        playerdata.setMuted(false);
      }
    }

    if (TotalFreedomMod.preprocessLogEnabled) {
      TFM_Log.info(
          String.format(
              "[PREPROCESS_COMMAND] %s(%s): %s",
              p.getName(), ChatColor.stripColor(p.getDisplayName()), command),
          true);
    }

    command = command.toLowerCase().trim();

    // Blocked commands
    if (TFM_CommandBlockerNew.getInstance().isCommandBlocked(command, event.getPlayer())) {
      // CommandBlocker handles messages and broadcasts
      event.setCancelled(true);
    }

    if (!TFM_SuperadminList.isUserSuperadmin(p)) {
      for (Player pl : Bukkit.getOnlinePlayers()) {
        if (TFM_SuperadminList.isUserSuperadmin(pl)
            && TFM_PlayerData.getPlayerData(pl).cmdspyEnabled()) {
          TFM_Util.playerMsg(pl, p.getName() + ": " + command);
        }
      }
    }
  }
  @EventHandler(priority = EventPriority.MONITOR)
  public void onPlayerJoin(PlayerJoinEvent event) {
    final Player player = event.getPlayer();
    final String ip = TFM_Util.getIp(player);
    TFM_Log.info(
        "[JOIN] " + TFM_Util.formatPlayer(player) + " joined the game with IP address: " + ip,
        true);

    if (TFM_PlayerList.getInstance().existsEntry(player)) {
      final TFM_PlayerEntry entry = TFM_PlayerList.getInstance().getEntry(player);
      entry.setLastJoinUnix(TFM_Util.getUnixTime());
      entry.setLastJoinName(player.getName());
      entry.save();
    } else {
      TFM_PlayerList.getInstance().getEntry(player);
      TFM_Log.info("Added new player: " + TFM_Util.formatPlayer(player));
    }

    final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);
    playerdata.setSuperadminIdVerified(false);

    // Verify strict IP match
    if (TFM_AdminList.isSuperAdmin(player)) {
      TFM_BanManager.getInstance().unbanIp(ip);
      TFM_BanManager.getInstance().unbanIp(TFM_Util.getFuzzyIp(ip));
      TFM_BanManager.getInstance().unbanUuid(player.getUniqueId());

      player.setOp(true);

      if (!TFM_AdminList.isIdentityMatched(player)) {
        playerdata.setSuperadminIdVerified(false);

        TFM_Util.bcastMsg(
            "Warning: "
                + player.getName()
                + " is an admin, but is using an account not registered to one of their ip-list.",
            ChatColor.RED);
      } else {
        playerdata.setSuperadminIdVerified(true);
        TFM_AdminList.updateLastLogin(player);
      }
    }

    // Handle admin impostors
    if (TFM_AdminList.isAdminImpostor(player)) {
      TFM_Util.bcastMsg(
          "Warning: " + player.getName() + " has been flagged as an impostor!", ChatColor.RED);
      TFM_Util.bcastMsg(
          ChatColor.AQUA + player.getName() + " is " + TFM_PlayerRank.getLoginMessage(player));
      player.getInventory().clear();
      player.setOp(false);
      player.setGameMode(GameMode.SURVIVAL);
    } else if (TFM_AdminList.isSuperAdmin(player)
        || TFM_Util.DEVELOPERS.contains(player.getName())) {
      TFM_Util.bcastMsg(
          ChatColor.AQUA + player.getName() + " is " + TFM_PlayerRank.getLoginMessage(player));
    }

    new BukkitRunnable() {
      @Override
      public void run() {
        if (TFM_ConfigEntry.ADMIN_ONLY_MODE.getBoolean()) {
          player.sendMessage(ChatColor.RED + "Server is currently closed to non-superadmins.");
        }

        if (TotalFreedomMod.lockdownEnabled) {
          TFM_Util.playerMsg(
              player,
              "Warning: Server is currenty in lockdown-mode, new players will not be able to join!",
              ChatColor.RED);
        }
      }
    }.runTaskLater(TotalFreedomMod.plugin, 20L * 3L);
  }
  @EventHandler(priority = EventPriority.NORMAL)
  public void onPlayerMove(PlayerMoveEvent event) {
    if (!TFM_AdminWorld.getInstance().validateMovement(event)) {
      return;
    }

    Player p = event.getPlayer();
    TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(p);

    for (Entry<Player, Double> fuckoff : TotalFreedomMod.fuckoffEnabledFor.entrySet()) {
      Player fuckoff_player = fuckoff.getKey();

      if (fuckoff_player.equals(p) || !fuckoff_player.isOnline()) {
        continue;
      }

      double fuckoff_range = fuckoff.getValue().doubleValue();

      Location mover_pos = p.getLocation();
      Location fuckoff_pos = fuckoff_player.getLocation();

      double distanceSquared;
      try {
        distanceSquared = mover_pos.distanceSquared(fuckoff_pos);
      } catch (IllegalArgumentException ex) {
        continue;
      }

      if (distanceSquared < (fuckoff_range * fuckoff_range)) {
        event.setTo(
            fuckoff_pos
                .clone()
                .add(
                    mover_pos
                        .subtract(fuckoff_pos)
                        .toVector()
                        .normalize()
                        .multiply(fuckoff_range * 1.1)));
        break;
      }
    }

    boolean do_freeze = false;
    if (TotalFreedomMod.allPlayersFrozen) {
      if (!TFM_SuperadminList.isUserSuperadmin(p)) {
        do_freeze = true;
      }
    } else {
      if (playerdata.isFrozen()) {
        do_freeze = true;
      }
    }

    if (do_freeze) {
      Location from = event.getFrom();
      Location to = event.getTo().clone();

      to.setX(from.getX());
      to.setY(from.getY());
      to.setZ(from.getZ());

      event.setTo(to);
    }

    if (playerdata.isCaged()) {
      Location target_pos = p.getLocation().add(0, 1, 0);

      boolean out_of_cage;
      if (!target_pos.getWorld().equals(playerdata.getCagePos().getWorld())) {
        out_of_cage = true;
      } else {
        out_of_cage = target_pos.distanceSquared(playerdata.getCagePos()) > (2.5 * 2.5);
      }

      if (out_of_cage) {
        playerdata.setCaged(
            true,
            target_pos,
            playerdata.getCageMaterial(TFM_PlayerData.CageLayer.OUTER),
            playerdata.getCageMaterial(TFM_PlayerData.CageLayer.INNER));
        playerdata.regenerateHistory();
        playerdata.clearHistory();
        TFM_Util.buildHistory(target_pos, 2, playerdata);
        TFM_Util.generateCube(
            target_pos, 2, playerdata.getCageMaterial(TFM_PlayerData.CageLayer.OUTER));
        TFM_Util.generateCube(
            target_pos, 1, playerdata.getCageMaterial(TFM_PlayerData.CageLayer.INNER));
      }
    }

    if (playerdata.isOrbiting()) {
      if (p.getVelocity().length() < playerdata.orbitStrength() * (2.0 / 3.0)) {
        p.setVelocity(new Vector(0, playerdata.orbitStrength(), 0));
      }
    }

    if (TotalFreedomMod.landminesEnabled && TotalFreedomMod.allowExplosions) {
      Iterator<TFM_LandmineData> landmines = TFM_LandmineData.landmines.iterator();
      while (landmines.hasNext()) {
        TFM_LandmineData landmine = landmines.next();

        Location landmine_pos = landmine.landmine_pos;
        if (landmine_pos.getBlock().getType() != Material.TNT) {
          landmines.remove();
          continue;
        }

        if (!landmine.player.equals(p)) {
          if (p.getWorld().equals(landmine_pos.getWorld())) {
            if (p.getLocation().distanceSquared(landmine_pos)
                <= (landmine.radius * landmine.radius)) {
              landmine.landmine_pos.getBlock().setType(Material.AIR);

              TNTPrimed tnt1 = landmine_pos.getWorld().spawn(landmine_pos, TNTPrimed.class);
              tnt1.setFuseTicks(40);
              tnt1.setPassenger(p);
              tnt1.setVelocity(new Vector(0.0, 2.0, 0.0));

              TNTPrimed tnt2 = landmine_pos.getWorld().spawn(p.getLocation(), TNTPrimed.class);
              tnt2.setFuseTicks(1);

              p.setGameMode(GameMode.SURVIVAL);
              landmines.remove();
            }
          }
        }
      }
    }
  }
Exemplo n.º 24
0
 public static void bcastMsg(String message) {
   TFM_Util.bcastMsg(message, null);
 }
Exemplo n.º 25
0
 // Still in use by listeners
 public static void playerMsg(CommandSender sender, String message) {
   TFM_Util.playerMsg(sender, message, ChatColor.GRAY);
 }
Exemplo n.º 26
0
 public static String formatPlayer(OfflinePlayer player) {
   return player.getName() + " (" + TFM_Util.getUuid(player) + ")";
 }
Exemplo n.º 27
0
 public static void adminAction(String adminName, String action, boolean isRed) {
   TFM_Util.bcastMsg(adminName + " - " + action, (isRed ? ChatColor.RED : ChatColor.AQUA));
 }