Exemple #1
0
 public List<Resident> getValidatedResidents(Object sender, String[] names) {
   List<Resident> invited = new ArrayList<Resident>();
   for (String name : names) {
     List<Player> matches = plugin.getServer().matchPlayer(name);
     if (matches.size() > 1) {
       String line = "Multiple players selected";
       for (Player p : matches) line += ", " + p.getName();
       TownyMessaging.sendErrorMsg(sender, line);
     } else if (matches.size() == 1) {
       // Match found online
       try {
         Resident target = getDataSource().getResident(matches.get(0).getName());
         invited.add(target);
       } catch (TownyException x) {
         TownyMessaging.sendErrorMsg(sender, x.getMessage());
       }
     } else {
       // No online matches so test for offline.
       Resident target;
       try {
         target = getDataSource().getResident(name);
         invited.add(target);
       } catch (NotRegisteredException x) {
         TownyMessaging.sendErrorMsg(sender, x.getMessage());
       }
     }
   }
   return invited;
 }
Exemple #2
0
 public void cancelProtectionRegenTasks() {
   for (ProtectionRegenTask task : protectionRegenTasks.values()) {
     plugin.getServer().getScheduler().cancelTask(task.getTaskId());
     task.replaceProtections();
   }
   protectionRegenTasks.clear();
   protectionPlaceholders.clear();
 }
  public void reloadTowny(Boolean reset) {

    if (reset) {
      TownyUniverse.getDataSource().deleteFile(plugin.getConfigPath());
    }
    TownyLogger.shutDown();
    if (plugin.load()) {

      // Register all child permissions for ranks
      TownyPerms.registerPermissionNodes();

      // Update permissions for all online players
      TownyPerms.updateOnlinePerms();
    }

    TownyMessaging.sendMsg(sender, TownySettings.getLangString("msg_reloaded"));
    // TownyMessaging.sendMsg(TownySettings.getLangString("msg_reloaded"));
  }
Exemple #4
0
  public List<Resident> getOnlineResidents(ResidentList residentList) {
    List<Resident> onlineResidents = new ArrayList<Resident>();
    for (Player player : plugin.getServer().getOnlinePlayers()) {
      for (Resident resident : residentList.getResidents()) {
        if (resident.getName().equalsIgnoreCase(player.getName())) onlineResidents.add(resident);
      }
    }

    return onlineResidents;
  }
Exemple #5
0
  @Override
  public List<String> getTreeString(int depth) {
    List<String> out = new ArrayList<String>();
    out.add(getTreeDepth(depth) + "Universe (" + getName() + ")");
    if (plugin != null) {
      out.add(getTreeDepth(depth + 1) + "Server (" + plugin.getServer().getName() + ")");
      out.add(getTreeDepth(depth + 2) + "Version: " + plugin.getServer().getVersion());
      out.add(
          getTreeDepth(depth + 2)
              + "Players: "
              + plugin.getServer().getOnlinePlayers().length
              + "/"
              + plugin.getServer().getMaxPlayers());
      out.add(
          getTreeDepth(depth + 2)
              + "Worlds ("
              + plugin.getServer().getWorlds().size()
              + "): "
              + Arrays.toString(plugin.getServer().getWorlds().toArray(new World[0])));
    }
    out.add(getTreeDepth(depth + 1) + "Worlds (" + getDataSource().getWorlds().size() + "):");
    for (TownyWorld world : getDataSource().getWorlds()) out.addAll(world.getTreeString(depth + 2));

    out.add(getTreeDepth(depth + 1) + "Nations (" + getDataSource().getNations().size() + "):");
    for (Nation nation : getDataSource().getNations()) out.addAll(nation.getTreeString(depth + 2));

    Collection<Town> townsWithoutNation = getDataSource().getTownsWithoutNation();
    out.add(getTreeDepth(depth + 1) + "Towns (" + townsWithoutNation.size() + "):");
    for (Town town : townsWithoutNation) out.addAll(town.getTreeString(depth + 2));

    Collection<Resident> residentsWithoutTown = getDataSource().getResidentsWithoutTown();
    out.add(getTreeDepth(depth + 1) + "Residents (" + residentsWithoutTown.size() + "):");
    for (Resident resident : residentsWithoutTown) out.addAll(resident.getTreeString(depth + 2));
    return out;
  }
Exemple #6
0
 public void setupDelay(int delay) {
   if (delay <= 0) start();
   else {
     for (Long t : TimeMgmt.getCountdownDelays(delay, TimeMgmt.defaultCountdownDelays)) {
       // Schedule the warnings leading up to the start of the war event
       // warTimer.schedule(
       //              new ServerBroadCastTimerTask(plugin,
       //                              String.format("War starts in %s",
       // TimeMgmt.formatCountdownTime(t))),
       //                              (delay-t)*1000);
       int id =
           plugin
               .getServer()
               .getScheduler()
               .scheduleAsyncDelayedTask(
                   getPlugin(),
                   new ServerBroadCastTimerTask(
                       plugin, String.format("War starts in %s", TimeMgmt.formatCountdownTime(t))),
                   TimeTools.convertToTicks((delay - t)));
       if (id == -1) {
         TownyMessaging.sendErrorMsg("Could not schedule a countdown message for war event.");
         end();
       } else addTaskId(id);
     }
     // warTimer.schedule(new StartWarTimerTask(universe), delay*1000);
     int id =
         plugin
             .getServer()
             .getScheduler()
             .scheduleAsyncDelayedTask(
                 getPlugin(), new StartWarTimerTask(universe), TimeTools.convertToTicks(delay));
     if (id == -1) {
       TownyMessaging.sendErrorMsg("Could not schedule setup delay for war event.");
       end();
     } else addTaskId(id);
   }
 }
 public boolean loadServerWorldsList() {
   sendDebugMsg("Loading Server World List");
   for (World world : plugin.getServer().getWorlds())
     try {
       // String[] split = world.getName().split("/");
       // String worldName = split[split.length-1];
       // universe.newWorld(worldName);
       universe.newWorld(world.getName());
     } catch (AlreadyRegisteredException e) {
       e.printStackTrace();
     } catch (NotRegisteredException e) {
       e.printStackTrace();
     }
   return true;
 }
  public boolean hasAllTownOverride(Player player, int blockId, TownyPermission.ActionType action) {

    boolean bpermissions;

    // check for permissions
    if (bpermissions = plugin.isPermissions())
      if ((hasPermission(
          player,
          PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK.getNode(
              blockId + "." + action.toString().toLowerCase())))) return true;

    // Allow ops all access when no permissions
    if ((!bpermissions) && (isTownyAdmin(player))) return true;

    return false;
  }
Exemple #9
0
  public void start() {
    warTime = true;

    // Announce

    // Seed spoils of war
    try {
      warSpoils.pay(TownySettings.getBaseSpoilsOfWar(), "Start of War - Base Spoils");
      TownyMessaging.sendMsg(
          "[War] Seeding spoils of war with " + TownySettings.getBaseSpoilsOfWar());
    } catch (EconomyException e) {
      TownyMessaging.sendErrorMsg("[War] Could not seed spoils of war.");
    }

    // Gather all nations at war
    for (Nation nation : TownyUniverse.getDataSource().getNations()) {
      if (!nation.isNeutral()) {
        add(nation);
        TownyMessaging.sendGlobalMessage(
            String.format(TownySettings.getLangString("msg_war_join_nation"), nation.getName()));
      } else if (!TownySettings.isDeclaringNeutral()) {
        try {
          nation.setNeutral(false);
          add(nation);
          TownyMessaging.sendGlobalMessage(
              String.format(TownySettings.getLangString("msg_war_join_forced"), nation.getName()));
        } catch (TownyException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    // warTimer.scheduleAtFixedRate(new WarTimerTask(this), 0, 1000);
    int id =
        plugin
            .getServer()
            .getScheduler()
            .scheduleAsyncRepeatingTask(
                getPlugin(), new WarTimerTask(this), 0, TimeTools.convertToTicks(5));
    if (id == -1) {
      TownyMessaging.sendErrorMsg("Could not schedule war event loop.");
      end();
    } else addTaskId(id);
    checkEnd();
  }
Exemple #10
0
 public List<Resident> getOnlineResidents(Player player, String[] names) {
   List<Resident> invited = new ArrayList<Resident>();
   for (String name : names) {
     List<Player> matches = plugin.getServer().matchPlayer(name);
     if (matches.size() > 1) {
       String line = "Multiple players selected";
       for (Player p : matches) line += ", " + p.getName();
       TownyMessaging.sendErrorMsg(player, line);
     } else if (matches.size() == 1)
       try {
         Resident target = getDataSource().getResident(matches.get(0).getName());
         invited.add(target);
       } catch (TownyException x) {
         TownyMessaging.sendErrorMsg(player, x.getMessage());
       }
   }
   return invited;
 }
Exemple #11
0
 public void toggleMobRemoval(boolean on) {
   if (on && !isMobRemovalRunning()) {
     mobRemoveTask =
         getPlugin()
             .getServer()
             .getScheduler()
             .scheduleSyncRepeatingTask(
                 getPlugin(),
                 new MobRemovalTimerTask(this, plugin.getServer()),
                 0,
                 MinecraftTools.convertToTicks(TownySettings.getMobRemovalSpeed()));
     if (mobRemoveTask == -1) TownyMessaging.sendErrorMsg("Could not schedule mob removal loop.");
   } else if (!on && isMobRemovalRunning()) {
     getPlugin().getServer().getScheduler().cancelTask(mobRemoveTask);
     mobRemoveTask = -1;
   }
   setChangedNotify(TOGGLE_MOB_REMOVAL);
 }
Exemple #12
0
 public void toggleHealthRegen(boolean on) {
   if (on && !isHealthRegenRunning()) {
     healthRegenTask =
         getPlugin()
             .getServer()
             .getScheduler()
             .scheduleSyncRepeatingTask(
                 getPlugin(),
                 new HealthRegenTimerTask(this, plugin.getServer()),
                 0,
                 MinecraftTools.convertToTicks(TownySettings.getHealthRegenSpeed()));
     if (healthRegenTask == -1)
       TownyMessaging.sendErrorMsg("Could not schedule health regen loop.");
   } else if (!on && isHealthRegenRunning()) {
     getPlugin().getServer().getScheduler().cancelTask(healthRegenTask);
     healthRegenTask = -1;
   }
   setChangedNotify(TOGGLE_HEALTH_REGEN);
 }
  public void parseToggleCommand(String[] split) throws TownyException {

    boolean choice;

    if (split.length == 0) {
      // command was '/townyadmin toggle'
      player.sendMessage(ChatTools.formatTitle("/townyadmin toggle"));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "war", ""));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "neutral", ""));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "devmode", ""));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "debug", ""));
      player.sendMessage(
          ChatTools.formatCommand("", "/townyadmin toggle", "townwithdraw/nationwithdraw", ""));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle npc", "[resident]", ""));
      return;
    }

    if (!TownyUniverse.getPermissionSource()
        .testPermission(
            player,
            PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_TOGGLE.getNode(split[0].toLowerCase())))
      throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));

    if (split[0].equalsIgnoreCase("war")) {
      choice = TownyUniverse.isWarTime();

      if (!choice) {
        plugin.getTownyUniverse().startWarEvent();
        TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("msg_war_started"));
      } else {
        plugin.getTownyUniverse().endWarEvent();
        TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("msg_war_ended"));
      }
    } else if (split[0].equalsIgnoreCase("neutral")) {

      try {
        choice = !TownySettings.isDeclaringNeutral();
        TownySettings.setDeclaringNeutral(choice);
        TownyMessaging.sendMsg(
            getSender(),
            String.format(
                TownySettings.getLangString("msg_nation_allow_neutral"),
                choice ? "Enabled" : "Disabled"));

      } catch (Exception e) {
        TownyMessaging.sendErrorMsg(
            getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
        return;
      }

    } else if (split[0].equalsIgnoreCase("devmode")) {
      try {
        choice = !TownySettings.isDevMode();
        TownySettings.setDevMode(choice);
        TownyMessaging.sendMsg(
            getSender(),
            "Dev Mode " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
      } catch (Exception e) {
        TownyMessaging.sendErrorMsg(
            getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
      }
    } else if (split[0].equalsIgnoreCase("debug")) {
      try {
        choice = !TownySettings.getDebug();
        TownySettings.setDebug(choice);
        TownyMessaging.sendMsg(
            getSender(),
            "Debug Mode " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
      } catch (Exception e) {
        TownyMessaging.sendErrorMsg(
            getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
      }
    } else if (split[0].equalsIgnoreCase("townwithdraw")) {
      try {
        choice = !TownySettings.getTownBankAllowWithdrawls();
        TownySettings.SetTownBankAllowWithdrawls(choice);
        TownyMessaging.sendMsg(
            getSender(),
            "Town Withdrawls " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
      } catch (Exception e) {
        TownyMessaging.sendErrorMsg(
            getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
      }
    } else if (split[0].equalsIgnoreCase("nationwithdraw")) {
      try {
        choice = !TownySettings.geNationBankAllowWithdrawls();
        TownySettings.SetNationBankAllowWithdrawls(choice);
        TownyMessaging.sendMsg(
            getSender(),
            "Nation Withdrawls " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
      } catch (Exception e) {
        TownyMessaging.sendErrorMsg(
            getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
      }

    } else if (split[0].equalsIgnoreCase("npc")) {

      if (split.length != 2)
        throw new TownyException(
            String.format(
                TownySettings.getLangString("msg_err_invalid_input"), "Eg: toggle npc [resident]"));

      try {
        Resident resident = TownyUniverse.getDataSource().getResident(split[1]);
        resident.setNPC(!resident.isNPC());

        TownyUniverse.getDataSource().saveResident(resident);

        TownyMessaging.sendMessage(
            sender,
            String.format(
                TownySettings.getLangString("msg_npc_flag"), resident.isNPC(), resident.getName()));

      } catch (NotRegisteredException x) {
        throw new TownyException(
            String.format(TownySettings.getLangString("msg_err_not_registered_1"), split[1]));
      }

    } else {
      // parameter error message
      // neutral/war/townmobs/worldmobs
      TownyMessaging.sendErrorMsg(
          getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
    }
  }
  /**
   * Remove residents who havn't logged in for X amount of days.
   *
   * @param split
   */
  public void purge(String[] split) {

    if (split.length == 0) {
      // command was '/townyadmin purge'
      player.sendMessage(ChatTools.formatTitle("/townyadmin purge"));
      player.sendMessage(ChatTools.formatCommand("", "/townyadmin purge", "[number of days]", ""));
      player.sendMessage(
          ChatTools.formatCommand(
              "", "", "Removes offline residents not seen for this duration.", ""));

      return;
    }

    int days = 1;

    try {
      days = Integer.parseInt(split[0]);
    } catch (NumberFormatException e) {
      TownyMessaging.sendErrorMsg(
          getSender(), TownySettings.getLangString("msg_error_must_be_int"));
      return;
    }

    // Use questioner to confirm.
    Plugin test = BukkitTools.getServer().getPluginManager().getPlugin("Questioner");

    if (this.sender instanceof Player
        && TownySettings.isUsingQuestioner()
        && test != null
        && test instanceof Questioner
        && test.isEnabled()) {
      Questioner questioner = (Questioner) test;
      questioner.loadClasses();

      List<Option> options = new ArrayList<Option>();
      options.add(
          new Option(
              TownySettings.questionerAccept(),
              new PurgeQuestionTask(plugin, this.sender, TimeTools.getMillis(days + "d"))));
      options.add(
          new Option(
              TownySettings.questionerDeny(),
              new PurgeQuestionTask(plugin, this.sender, TimeTools.getMillis(days + "d")) {

                @Override
                public void run() {

                  TownyMessaging.sendMessage(getSender(), "Purge Aborted!");
                }
              }));

      Question question =
          new Question(this.sender.getName(), "Do you really want to perform this purge", options);

      try {
        plugin.appendQuestion(questioner, question);
      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
    } else {

      // Run a purge in it's own thread
      new ResidentPurge(plugin, this.sender, TimeTools.getMillis(days + "d")).start();
    }
  }
Exemple #15
0
 public boolean isActiveResident(Resident resident) {
   return ((System.currentTimeMillis() - resident.getLastOnline()
           < (20 * TownySettings.getInactiveAfter()))
       || (plugin.isOnline(resident.getName())));
 }
  public void adminSet(String[] split) throws TownyException {

    if (split.length == 0) {
      sender.sendMessage(ChatTools.formatTitle("/townyadmin set"));
      // TODO: player.sendMessage(ChatTools.formatCommand("",
      // "/townyadmin set", "king [nation] [king]", ""));
      sender.sendMessage(
          ChatTools.formatCommand(
              "",
              "/townyadmin set",
              "mayor [town] " + TownySettings.getLangString("town_help_2"),
              ""));
      sender.sendMessage(ChatTools.formatCommand("", "/townyadmin set", "mayor [town] npc", ""));
      // player.sendMessage(ChatTools.formatCommand("", "/townyadmin set",
      // "debugmode [on/off]", ""));
      // player.sendMessage(ChatTools.formatCommand("", "/townyadmin set",
      // "devmode [on/off]", ""));

      return;
    }

    if (!TownyUniverse.getPermissionSource()
        .testPermission(
            player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_SET.getNode(split[0].toLowerCase())))
      throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));

    if (split[0].equalsIgnoreCase("mayor")) {
      if (split.length < 3) {

        sender.sendMessage(ChatTools.formatTitle("/townyadmin set mayor"));
        sender.sendMessage(
            ChatTools.formatCommand(
                "Eg",
                "/townyadmin set mayor",
                "[town] " + TownySettings.getLangString("town_help_2"),
                ""));
        sender.sendMessage(
            ChatTools.formatCommand("Eg", "/townyadmin set mayor", "[town] npc", ""));

      } else
        try {
          Resident newMayor = null;
          Town town = TownyUniverse.getDataSource().getTown(split[1]);

          if (split[2].equalsIgnoreCase("npc")) {
            String name = nextNpcName();
            TownyUniverse.getDataSource().newResident(name);

            newMayor = TownyUniverse.getDataSource().getResident(name);

            newMayor.setRegistered(System.currentTimeMillis());
            newMayor.setLastOnline(0);
            newMayor.setNPC(true);

            TownyUniverse.getDataSource().saveResident(newMayor);
            TownyUniverse.getDataSource().saveResidentList();

            // set for no upkeep as an NPC mayor is assigned
            town.setHasUpkeep(false);

          } else {
            newMayor = TownyUniverse.getDataSource().getResident(split[2]);

            // set upkeep again
            town.setHasUpkeep(true);
          }

          if (!town.hasResident(newMayor)) TownCommand.townAddResident(town, newMayor);
          // Delete the resident if the old mayor was an NPC.
          Resident oldMayor = town.getMayor();

          town.setMayor(newMayor);

          if (oldMayor.isNPC()) {
            try {
              town.removeResident(oldMayor);
              TownyUniverse.getDataSource().removeResident(oldMayor);

              TownyUniverse.getDataSource().removeResidentList(oldMayor);

            } catch (EmptyTownException e) {
              // Should never reach here as we are setting a new
              // mayor before removing the old one.
              e.printStackTrace();
            }
          }
          TownyUniverse.getDataSource().saveTown(town);
          String[] msg = TownySettings.getNewMayorMsg(newMayor.getName());
          TownyMessaging.sendTownMessage(town, msg);
          // TownyMessaging.sendMessage(player, msg);
        } catch (TownyException e) {
          TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
        }

    } else if (split[0].equalsIgnoreCase("capital")) {

      if (split.length < 2) {

        sender.sendMessage(ChatTools.formatTitle("/townyadmin set capital"));
        sender.sendMessage(ChatTools.formatCommand("Eg", "/ta set capital", "[town name]", ""));

      } else {

        try {
          Town newCapital = TownyUniverse.getDataSource().getTown(split[1]);
          Nation nation = newCapital.getNation();

          nation.setCapital(newCapital);
          plugin.resetCache();

          TownyMessaging.sendNationMessage(
              nation,
              TownySettings.getNewKingMsg(newCapital.getMayor().getName(), nation.getName()));

          TownyUniverse.getDataSource().saveNation(nation);
          TownyUniverse.getDataSource().saveNationList();

        } catch (TownyException e) {
          TownyMessaging.sendErrorMsg(player, e.getMessage());
        }
      }

    } else {
      TownyMessaging.sendErrorMsg(
          getSender(),
          String.format(TownySettings.getLangString("msg_err_invalid_property"), "administrative"));
      return;
    }
  }
Exemple #17
0
  /**
   * Tests the attacker against defender to see if we need to cancel the damage event due to world
   * PvP, Plot PvP or Friendly Fire settings. Only allow a Wolves owner to cause it damage, and
   * residents with destroy permissions to damage passive animals and villagers while in a town.
   *
   * @param world
   * @param attackingEntity
   * @param defendingEntity
   * @param attackingPlayer
   * @param defendingPlayer
   * @return true if we should cancel.
   */
  public static boolean preventDamageCall(
      Towny plugin,
      TownyWorld world,
      Entity attackingEntity,
      Entity defendingEntity,
      Player attackingPlayer,
      Player defendingPlayer) {

    // World using Towny
    if (!world.isUsingTowny()) return false;

    /*
     * We have an attacking player
     */
    if (attackingPlayer != null) {

      Coord coord = Coord.parseCoord(defendingEntity);
      TownBlock defenderTB = null;
      TownBlock attackerTB = null;

      try {
        attackerTB = world.getTownBlock(Coord.parseCoord(attackingEntity));
      } catch (NotRegisteredException ex) {
      }

      try {
        defenderTB = world.getTownBlock(coord);
      } catch (NotRegisteredException ex) {
      }

      /*
       * If another player is the target
       * or
       * The target is in a TownBlock and...
       * the target is a tame wolf and we are not it's owner
       */
      if ((defendingPlayer != null)
          || ((defenderTB != null)
              && ((defendingEntity instanceof Wolf)
                  && ((Wolf) defendingEntity).isTamed()
                  && !((Wolf) defendingEntity).getOwner().equals((AnimalTamer) attackingEntity)))) {

        /*
         * Defending player is in a warzone
         */
        if (world.isWarZone(coord)) return false;

        /*
         * Check for special pvp plots (arena)
         */
        if (isPvPPlot(attackingPlayer, defendingPlayer)) return false;

        /*
         * Check if we are preventing friendly fire between allies
         * Check the attackers TownBlock and it's Town for their PvP
         * status, else the world.
         * Check the defenders TownBlock and it's Town for their PvP
         * status, else the world.
         */
        if (preventFriendlyFire(attackingPlayer, defendingPlayer)
            || preventPvP(world, attackerTB)
            || preventPvP(world, defenderTB)) {

          DisallowedPVPEvent event = new DisallowedPVPEvent(attackingPlayer, defendingPlayer);
          plugin.getServer().getPluginManager().callEvent(event);

          return !event.isCancelled();
        }

      } else {

        /*
         * Remove animal killing prevention start
         */

        /*
         * Defender is not a player so check for PvM
         */
        if (defenderTB != null) {
          List<Class<?>> prots =
              EntityTypeUtil.parseLivingEntityClassNames(
                  TownySettings.getEntityTypes(), "TownMobPVM:");
          if (EntityTypeUtil.isInstanceOfAny(prots, defendingEntity)) {
            /*
             * Only allow the player to kill protected entities etc,
             * if they are from the same town
             * and have destroy permissions (grass) in the defending
             * TownBlock
             */
            if (!PlayerCacheUtil.getCachePermission(
                attackingPlayer, attackingPlayer.getLocation(), 3, (byte) 0, ActionType.DESTROY))
              return true;
          }
        }

        /*
         * Remove prevention end
         */

        /*
         * Protect specific entity interactions (faked with block ID's).
         */
        int blockID = 0;

        switch (defendingEntity.getType()) {
          case ITEM_FRAME:
            blockID = 389;
            break;

          case PAINTING:
            blockID = 321;

            break;

          case MINECART:
            if (defendingEntity instanceof org.bukkit.entity.minecart.StorageMinecart) {

              blockID = 342;

            } else if (defendingEntity instanceof org.bukkit.entity.minecart.RideableMinecart) {

              blockID = 328;

            } else if (defendingEntity instanceof org.bukkit.entity.minecart.PoweredMinecart) {

              blockID = 343;

            } else if (defendingEntity instanceof org.bukkit.entity.minecart.HopperMinecart) {

              blockID = 408;

            } else {

              blockID = 321;
            }
          default:
            break;
        }

        if (blockID != 0) {
          // Get permissions (updates if none exist)
          boolean bDestroy =
              PlayerCacheUtil.getCachePermission(
                  attackingPlayer,
                  defendingEntity.getLocation(),
                  blockID,
                  (byte) 0,
                  TownyPermission.ActionType.DESTROY);

          if (!bDestroy) {

            /*
             * Fetch the players cache
             */
            PlayerCache cache = plugin.getCache(attackingPlayer);

            if (cache.hasBlockErrMsg())
              TownyMessaging.sendErrorMsg(attackingPlayer, cache.getBlockErrMsg());

            return true;
          }
        }
      }
    }

    return false;
  }
 public void sendDebugMsg(String msg) {
   if (plugin != null) plugin.sendDebugMsg(msg);
   else System.out.println("[Towny] Debug: " + msg);
 }
Exemple #19
0
 public String getRootFolder() {
   if (plugin != null) return plugin.getDataFolder().getPath();
   else return rootFolder;
 }
Exemple #20
0
  public boolean loadSettings() {
    try {
      FileMgmt.checkFolders(
          new String[] {
            getRootFolder(),
            getRootFolder() + FileMgmt.fileSeparator() + "settings",
            getRootFolder() + FileMgmt.fileSeparator() + "logs"
          }); // Setup the logs folder here as the logger will not yet be enabled.

      TownySettings.loadConfig(
          getRootFolder()
              + FileMgmt.fileSeparator()
              + "settings"
              + FileMgmt.fileSeparator()
              + "config.yml",
          plugin.getVersion());
      TownySettings.loadLanguage(
          getRootFolder() + FileMgmt.fileSeparator() + "settings", "english.yml");

    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }

    // Setup any defaults before we load the database.
    Coord.setCellSize(TownySettings.getTownBlockSize());

    System.out.println(
        "[Towny] Database: [Load] "
            + TownySettings.getLoadDatabase()
            + " [Save] "
            + TownySettings.getSaveDatabase());

    worlds.clear();
    nations.clear();
    towns.clear();
    residents.clear();

    if (!loadDatabase(TownySettings.getLoadDatabase())) {
      System.out.println("[Towny] Error: Failed to load!");
      return false;
    }

    try {
      getDataSource().cleanupBackups();
      // Set the new class for saving.
      // setDataSource(TownySettings.getSaveDatabase());
      // getDataSource().initialize(plugin, this);
      try {
        getDataSource().backup();
        getDataSource().deleteUnusedResidentFiles();
      } catch (IOException e) {
        System.out.println("[Towny] Error: Could not create backup.");
        e.printStackTrace();
        return false;
      }

      // if (TownySettings.isSavingOnLoad())
      //      townyUniverse.getDataSource().saveAll();
    } catch (UnsupportedOperationException e) {
      System.out.println("[Towny] Error: Unsupported save format!");
      return false;
    }

    return true;
  }
Exemple #21
0
  public War(Towny plugin, int startDelay) {
    this.plugin = plugin;
    this.universe = plugin.getTownyUniverse();

    setupDelay(startDelay);
  }
Exemple #22
0
 public void checkEnd() {
   if (warringNations.size() <= 1) toggleEnd();
   else if (plugin.getTownyUniverse().areAllAllies(warringNations)) toggleEnd();
 }
Exemple #23
0
 public void sendMessageTo(ResidentList residents, String msg, String modeRequired) {
   for (Player player : getOnlinePlayers(residents))
     if (plugin.hasPlayerMode(player, modeRequired)) player.sendMessage(msg);
 }
  public void registerPermissionNodes() {

    plugin
        .getServer()
        .getScheduler()
        .scheduleSyncDelayedTask(
            plugin,
            new Runnable() {

              @Override
              public void run() {
                Permission perm = null;

                for (int blockId = 0; blockId < 512; blockId++) {
                  /** Register all towny.wild.block.[id].* nodes */
                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_WILD_BLOCK_BUILD.getNode(blockId),
                          "User can build a specific block in the wild.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_WILD_BUILD.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_WILD_BLOCK_BUILD.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_WILD_BLOCK_DESTROY.getNode(blockId + ""),
                          "User can destroy a specific block in the wild.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_WILD_DESTROY.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_WILD_BLOCK_DESTROY.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_WILD_BLOCK_SWITCH.getNode(blockId + ""),
                          "User can switch a specific block in the wild.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_WILD_SWITCH.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_WILD_BLOCK_SWITCH.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_WILD_BLOCK_ITEM_USE.getNode(blockId + ""),
                          "User can item_use a specific block in the wild.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_WILD_ITEM_USE.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_WILD_BLOCK_ITEM_USE.getNode(), true);

                  /** Register all towny.claimed.alltown.block.[id].* nodes */
                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_BUILD.getNode(blockId + ""),
                          "User can build in all town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_BUILD.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_BUILD.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_DESTROY.getNode(blockId + ""),
                          "User can destroy in all town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_DESTROY.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_DESTROY.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_SWITCH.getNode(blockId + ""),
                          "User can switch in all town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_SWITCH.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_SWITCH.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_ITEM_USE.getNode(blockId + ""),
                          "User can item_use in all town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ITEM_USE.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ALL_BLOCK_ITEM_USE.getNode(), true);

                  /** Register all towny.claimed.owntown.block.[id].* nodes */
                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_BUILD.getNode(blockId + ""),
                          "User can build in own town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_BUILD.getNode(), true);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_BUILD.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_DESTROY.getNode(blockId + ""),
                          "User can destroy in own town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_DESTROY.getNode(), true);
                  perm.addParent(
                      PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_DESTROY.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_SWITCH.getNode(blockId + ""),
                          "User can switch in own town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_SWITCH.getNode(), true);
                  perm.addParent(
                      PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_SWITCH.getNode(), true);

                  perm =
                      new Permission(
                          PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_ITEM_USE.getNode(
                              blockId + ""),
                          "User can item_use in own town zones.",
                          PermissionDefault.FALSE,
                          null);
                  perm.addParent(PermissionNodes.TOWNY_CLAIMED_ITEM_USE.getNode(), true);
                  perm.addParent(
                      PermissionNodes.TOWNY_CLAIMED_OWNTOWN_BLOCK_ITEM_USE.getNode(), true);
                }
              }
            },
            1);
  }
Exemple #25
0
 public void addWarZone(WorldCoord worldCoord) {
   worldCoord.getWorld().addWarZone(worldCoord);
   plugin.updateCache(worldCoord);
 }
Exemple #26
0
 public void removeWarZone(WorldCoord worldCoord) {
   worldCoord.getWorld().removeWarZone(worldCoord);
   plugin.updateCache(worldCoord);
 }