Ejemplo n.º 1
0
 @Override
 public boolean onCommand(final PlotPlayer plr, final String[] args) {
   final Location ploc = plr.getLocation();
   if (!PS.get().isPlotWorld(ploc.getWorld())) {
     MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
     return false;
   }
   PlotId id = PlotId.fromString(args[0]);
   if (id == null) {
     if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) {
       Plot closest = null;
       int distance = Integer.MAX_VALUE;
       for (final Plot plot : PS.get().getPlotsInWorld(ploc.getWorld())) {
         final double current = plot.getBottomAbs().getEuclideanDistanceSquared(ploc);
         if (current < distance) {
           distance = (int) current;
           closest = plot;
         }
       }
       id = closest.getId();
     } else {
       MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
       return false;
     }
   }
   final Location loc = MainUtil.getPlotHome(ploc.getWorld(), id);
   plr.setCompassTarget(loc);
   MainUtil.sendMessage(plr, C.COMPASS_TARGET);
   return true;
 }
 public UUID getUUID(final String name, RunnableVal<UUID> ifFetch) {
   if ((name == null) || (name.length() == 0)) {
     return null;
   }
   // check online
   final PlotPlayer player = getPlayer(name);
   if (player != null) {
     return player.getUUID();
   }
   // check cache
   final StringWrapper wrap = new StringWrapper(name);
   UUID uuid = uuidMap.get(wrap);
   if (uuid != null) {
     return uuid;
   }
   // Read from disk OR convert directly to offline UUID
   if (Settings.OFFLINE_MODE) {
     uuid = uuidWrapper.getUUID(name);
     add(new StringWrapper(name), uuid);
     return uuid;
   }
   if (Settings.UUID_FROM_DISK && ifFetch != null) {
     fetchUUID(name, ifFetch);
     return null;
   }
   return null;
 }
Ejemplo n.º 3
0
  @Subscribe
  public void onJoin(PlayerJoinEvent event) {
    final Player player = event.getUser();
    SpongeUtil.removePlayer(player.getName());
    final PlotPlayer pp = SpongeUtil.getPlayer(player);
    final String username = pp.getName();
    final StringWrapper name = new StringWrapper(username);
    final UUID uuid = pp.getUUID();
    UUIDHandler.add(name, uuid);
    ExpireManager.dates.put(uuid, System.currentTimeMillis());

    // TODO worldedit bypass

    if (PS.get().update != null && pp.hasPermission("plots.admin")) {
      TaskManager.runTaskLater(
          new Runnable() {
            @Override
            public void run() {
              MainUtil.sendMessage(pp, "&6An update for PlotSquared is available: &7/plot update");
            }
          },
          20);
    }
    final Location loc = SpongeUtil.getLocation(player);
    final Plot plot = MainUtil.getPlot(loc);
    if (plot == null) {
      return;
    }
    if (Settings.TELEPORT_ON_LOGIN) {
      MainUtil.teleportPlayer(pp, pp.getLocation(), plot);
      MainUtil.sendMessage(pp, C.TELEPORTED_TO_ROAD);
    }
    PlotListener.plotEntry(pp, plot);
  }
 public PlotPlayer getPlayer(final UUID uuid) {
   for (final PlotPlayer player : players.values()) {
     if (player.getUUID().equals(uuid)) {
       return player;
     }
   }
   return null;
 }
Ejemplo n.º 5
0
 public boolean toggle(PlotPlayer player, String key) {
   if (player.getAttribute(key)) {
     player.removeAttribute(key);
     return true;
   } else {
     player.setAttribute(key);
     return false;
   }
 }
Ejemplo n.º 6
0
  @Subscribe
  public void onChat(PlayerChatEvent event) {
    final Player player = event.getEntity();
    final String world = player.getWorld().getName();
    if (!PS.get().isPlotWorld(world)) {
      return;
    }
    final PlotWorld plotworld = PS.get().getPlotWorld(world);
    final PlotPlayer plr = SpongeUtil.getPlayer(player);
    if (!plotworld.PLOT_CHAT && (plr.getMeta("chat") == null || !(Boolean) plr.getMeta("chat"))) {
      return;
    }
    final Location loc = SpongeUtil.getLocation(player);
    final Plot plot = MainUtil.getPlot(loc);
    if (plot == null) {
      return;
    }
    Text message = event.getUnformattedMessage();

    // TODO use display name rather than username
    //  - Getting displayname currently causes NPE, so wait until sponge fixes that

    String sender = player.getName();
    PlotId id = plot.id;
    String newMessage =
        StringMan.replaceAll(
            C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
    Text forcedMessage = event.getMessage();
    //        String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", id.x
    // + ";" + id.y, "%sender%", sender);
    for (PlotPlayer user : UUIDHandler.getPlayers().values()) {
      String toSend;
      if (plot.equals(MainUtil.getPlot(user.getLocation()))) {
        toSend = newMessage;
      } else if (Permissions.hasPermission(user, C.PERMISSION_COMMANDS_CHAT)) {
        ((SpongePlayer) user).player.sendMessage(forcedMessage);
        continue;
      } else {
        continue;
      }
      String[] split = (toSend + " ").split("%msg%");
      List<Text> components = new ArrayList<>();
      Text prefix = null;
      for (String part : split) {
        if (prefix != null) {
          components.add(prefix);
        } else {
          prefix = message;
        }
        components.add(Texts.of(part));
      }
      ((SpongePlayer) user).player.sendMessage(Texts.join(components));
    }
    event.setNewMessage(Texts.of());
    event.setCancelled(true);
  }
Ejemplo n.º 7
0
 /**
  * Get the plot from a string.
  *
  * @param player Provides a context for what world to search in. Prefixing the term with
  *     'world_name;' will override this context.
  * @param arg The search term
  * @param message If a message should be sent to the player if a plot cannot be found
  * @return The plot if only 1 result is found, or null
  */
 public static Plot getPlotFromString(PlotPlayer player, String arg, boolean message) {
   if (arg == null) {
     if (player == null) {
       if (message) {
         PS.log(C.NOT_VALID_PLOT_WORLD);
       }
       return null;
     }
     return player.getCurrentPlot();
   }
   PlotArea area;
   if (player != null) {
     area = PS.get().getPlotAreaByString(arg);
     if (area == null) {
       area = player.getApplicablePlotArea();
     }
   } else {
     area = ConsolePlayer.getConsole().getApplicablePlotArea();
   }
   String[] split = arg.split(";|,");
   PlotId id;
   if (split.length == 4) {
     area = PS.get().getPlotAreaByString(split[0] + ';' + split[1]);
     id = PlotId.fromString(split[2] + ';' + split[3]);
   } else if (split.length == 3) {
     area = PS.get().getPlotAreaByString(split[0]);
     id = PlotId.fromString(split[1] + ';' + split[2]);
   } else if (split.length == 2) {
     id = PlotId.fromString(arg);
   } else {
     Collection<Plot> plots = area == null ? PS.get().getPlots() : area.getPlots();
     for (Plot p : plots) {
       String name = p.getAlias();
       if (!name.isEmpty() && StringMan.isEqualIgnoreCase(name, arg)) {
         return p;
       }
     }
     if (message) {
       sendMessage(player, C.NOT_VALID_PLOT_ID);
     }
     return null;
   }
   if (id == null) {
     if (message) {
       sendMessage(player, C.NOT_VALID_PLOT_ID);
     }
     return null;
   }
   if (area == null) {
     if (message) {
       sendMessage(player, C.NOT_VALID_PLOT_WORLD);
     }
     return null;
   }
   return area.getPlotAbs(id);
 }
Ejemplo n.º 8
0
 @Subscribe
 public void onConnect(PlayerConnectionEvent event) {
   PlayerConnection connection = event.getConnection();
   Player player = connection.getPlayer();
   String name = player.getName();
   PlotPlayer pp = SpongeUtil.getPlayer(player);
   if (name.equals("PlotSquared") || pp.getUUID().equals(DBFunc.everyone)) {
     player.kick();
     SpongeUtil.removePlayer(pp.getName());
   }
 }
Ejemplo n.º 9
0
  @Subscribe
  public void onQuit(PlayerQuitEvent event) {
    Player player = event.getEntity();
    PlotPlayer pp = SpongeUtil.getPlayer(player);
    ExpireManager.dates.put(pp.getUUID(), System.currentTimeMillis());
    EventUtil.unregisterPlayer(pp);

    // TODO unregister WorldEdit manager
    // TODO delete plots on ban

    SpongeUtil.removePlayer(pp.getName());
  }
Ejemplo n.º 10
0
 @Subscribe
 public void onBlockPlace(PlayerPlaceBlockEvent event) {
   Player player = event.getEntity();
   World world = player.getWorld();
   String worldname = world.getName();
   org.spongepowered.api.world.Location blockLoc = event.getLocation();
   final Location loc = SpongeUtil.getLocation(worldname, blockLoc);
   final Plot plot = MainUtil.getPlot(loc);
   if (plot != null) {
     if (blockLoc.getY() == 0) {
       event.setCancelled(true);
       return;
     }
     final PlotPlayer pp = SpongeUtil.getPlayer(player);
     if (!plot.hasOwner()) {
       if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
         return;
       }
       MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
       event.setCancelled(true);
       return;
     } else if (!plot.isAdded(pp.getUUID())) {
       final Flag destroy = FlagManager.getPlotFlag(plot, "place");
       BlockState state = blockLoc.getBlock();
       if ((destroy != null)
           && ((HashSet<PlotBlock>) destroy.getValue())
               .contains(SpongeMain.THIS.getPlotBlock(state))) {
         return;
       }
       if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
         return;
       }
       MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
       event.setCancelled(true);
     } else if (Settings.DONE_RESTRICTS_BUILDING && plot.getSettings().flags.containsKey("done")) {
       if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
         MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
         event.setCancelled(true);
         return;
       }
     }
     return;
   }
   final PlotPlayer pp = SpongeUtil.getPlayer(player);
   if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) {
     return;
   }
   if (MainUtil.isPlotArea(loc)) {
     MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD);
     event.setCancelled(true);
   }
 }
 public static boolean claimPlot(
     final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic) {
   final boolean result = EventUtil.manager.callClaim(player, plot, false);
   if (result) {
     MainUtil.createPlot(player.getUUID(), plot);
     MainUtil.setSign(player.getName(), plot);
     MainUtil.sendMessage(player, C.CLAIMED);
     if (teleport) {
       MainUtil.teleportPlayer(player, player.getLocation(), plot);
     }
   }
   return !result;
 }
Ejemplo n.º 12
0
  @Subscribe
  public void onWorldChange(PlayerChangeWorldEvent event) {
    final PlotPlayer player = SpongeUtil.getPlayer(event.getUser());

    player.deleteMeta("location");
    player.deleteMeta("lastplot");

    // TODO worldedit mask

    if (Settings.PERMISSION_CACHING) {
      ((SpongePlayer) player).hasPerm = new HashSet<>();
      ((SpongePlayer) player).noPerm = new HashSet<>();
    }
  }
Ejemplo n.º 13
0
 public static void getPersistentMeta(UUID uuid, String key, RunnableVal<byte[]> result) {
   PlotPlayer player = UUIDHandler.getPlayer(uuid);
   if (player != null) {
     result.run(player.getPersistentMeta(key));
   } else {
     DBFunc.getPersistentMeta(
         uuid,
         new RunnableVal<Map<String, byte[]>>() {
           @Override
           public void run(Map<String, byte[]> value) {
             result.run(value.get(key));
           }
         });
   }
 }
Ejemplo n.º 14
0
 public void displaySaves(final PlotPlayer player, final int page) {
   final List<String> schematics = (List<String>) player.getMeta("plot_schematics");
   for (int i = 0; i < Math.min(schematics.size(), 32); i++) {
     try {
       final String schem = schematics.get(i);
       final String[] split = schem.split("_");
       if (split.length != 6) {
         continue;
       }
       final String time =
           secToTime((System.currentTimeMillis() / 1000) - (Long.parseLong(split[0])));
       final String world = split[1];
       final PlotId id = PlotId.fromString(split[2] + ";" + split[3]);
       final String size = split[4];
       final String server = split[5].replaceAll(".schematic", "");
       String color;
       if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) {
         color = "$4";
       } else {
         color = "$1";
       }
       MainUtil.sendMessage(
           player,
           "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ";" + id + "$3 | "
               + color + size + "x" + size);
     } catch (final Exception e) {
       e.printStackTrace();
     }
   }
   MainUtil.sendMessage(player, C.LOAD_LIST);
 }
 public String getName(final UUID uuid) {
   if (uuid == null) {
     return null;
   }
   // check online
   final PlotPlayer player = getPlayer(uuid);
   if (player != null) {
     return player.getName();
   }
   // check cache
   final StringWrapper name = uuidMap.inverse().get(uuid);
   if (name != null) {
     return name.value;
   }
   return null;
 }
Ejemplo n.º 16
0
 @Override
 public boolean canModify(Plot plot, PlotPlayer player) {
   if (plot == null) {
     return Permissions.hasPermission(player, "plots.inbox.modify." + toString());
   }
   return (Permissions.hasPermission(player, "plots.inbox.modify." + toString())
       && (PlotHandler.isOwner(plot, player.getUUID())
           || Permissions.hasPermission(player, "plots.inbox.modify." + toString() + ".other")));
 }
Ejemplo n.º 17
0
 /**
  * Send a message to a player.
  *
  * @param player Can be null to represent console, or use ConsolePlayer.getConsole()
  * @param msg
  * @param prefix If the message should be prefixed with the configured prefix
  * @return
  */
 public static boolean sendMessage(PlotPlayer player, String msg, boolean prefix) {
   if (!msg.isEmpty()) {
     if (player == null) {
       String message = (prefix ? C.PREFIX.s() : "") + msg;
       PS.log(message);
     } else {
       player.sendMessage((prefix ? C.PREFIX.s() : "") + C.color(msg));
     }
   }
   return true;
 }
Ejemplo n.º 18
0
 /**
  * Send a message to the player
  *
  * @param player the recipient of the message
  * @param caption the message to send
  * @return boolean success
  */
 public static boolean sendMessage(PlotPlayer player, C caption, Object... args) {
   if (caption.s().isEmpty()) {
     return true;
   }
   TaskManager.runTaskAsync(
       () -> {
         String m = C.format(caption, args);
         if (player == null) {
           PS.log(m);
         } else {
           player.sendMessage(m);
         }
       });
   return true;
 }
Ejemplo n.º 19
0
  @Override
  public boolean onCommand(final PlotPlayer plr, final String[] args) {

    if (!Settings.METRICS) {
      MainUtil.sendMessage(
          plr,
          "&cPlease enable metrics in order to use this command.\n&7 - Or host it yourself if you don't like the free service");
      return false;
    }
    final String world = plr.getLocation().getWorld();
    if (!PS.get().isPlotWorld(world)) {
      return !sendMessage(plr, C.NOT_IN_PLOT_WORLD);
    }
    final Plot plot = MainUtil.getPlot(plr.getLocation());
    if (plot == null) {
      return !sendMessage(plr, C.NOT_IN_PLOT);
    }
    if (!plot.hasOwner()) {
      MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
      return false;
    }
    if (!plot.isOwner(plr.getUUID())
        && !Permissions.hasPermission(plr, "plots.admin.command.load")) {
      MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
      return false;
    }
    if (MainUtil.runners.containsKey(plot)) {
      MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
      return false;
    }

    if (args.length != 0) {
      if (args.length == 1) {
        // TODO load save here
        final List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
        if (schematics == null) {
          // No schematics found:
          MainUtil.sendMessage(plr, C.LOAD_NULL);
          return false;
        }
        String schem;
        try {
          schem = schematics.get(Integer.parseInt(args[0]) - 1);
        } catch (final Exception e) {
          // use /plot load <index>
          MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")");
          return false;
        }
        final URL url;
        try {
          url = new URL(Settings.WEB_URL + "saves/" + plr.getUUID() + "/" + schem + ".schematic");
        } catch (final MalformedURLException e) {
          e.printStackTrace();
          MainUtil.sendMessage(plr, C.LOAD_FAILED);
          return false;
        }

        MainUtil.runners.put(plot, 1);
        MainUtil.sendMessage(plr, C.GENERATING_COMPONENT);
        TaskManager.runTaskAsync(
            new Runnable() {
              @Override
              public void run() {
                final Schematic schematic = SchematicHandler.manager.getSchematic(url);
                if (schematic == null) {
                  MainUtil.runners.remove(plot);
                  sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format");
                  return;
                }
                SchematicHandler.manager.paste(
                    schematic,
                    plot,
                    0,
                    0,
                    new RunnableVal<Boolean>() {
                      @Override
                      public void run() {
                        MainUtil.runners.remove(plot);
                        if (value) {
                          sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
                        } else {
                          sendMessage(plr, C.SCHEMATIC_PASTE_FAILED);
                        }
                      }
                    });
              }
            });
        return true;
      }
      MainUtil.runners.remove(plot);
      MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot load <index>");
      return false;
    }

    // list schematics

    final List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
    if (schematics == null) {
      MainUtil.runners.put(plot, 1);
      TaskManager.runTaskAsync(
          new Runnable() {
            @Override
            public void run() {
              final List<String> schematics = SchematicHandler.manager.getSaves(plr.getUUID());
              MainUtil.runners.remove(plot);
              if ((schematics == null) || (schematics.size() == 0)) {
                MainUtil.sendMessage(plr, C.LOAD_FAILED);
                return;
              }
              plr.setMeta("plot_schematics", schematics);
              displaySaves(plr, 0);
            }
          });
    } else {
      displaySaves(plr, 0);
    }
    return true;
  }
Ejemplo n.º 20
0
  public static boolean plotEntry(final PlotPlayer pp, final Plot plot) {
    if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) {
      return false;
    }
    Plot last = pp.getMeta("lastplot");
    if ((last != null) && !last.getId().equals(plot.getId())) {
      plotExit(pp, last);
    }
    if (ExpireManager.IMP != null) {
      ExpireManager.IMP.handleEntry(pp, plot);
    }
    pp.setMeta("lastplot", plot);
    EventUtil.manager.callEntry(pp, plot);
    if (plot.hasOwner()) {
      HashMap<String, Flag> flags = FlagManager.getPlotFlags(plot);
      int size = flags.size();
      boolean titles = Settings.TITLES;
      final String greeting;

      if (size != 0) {
        Flag titleFlag = flags.get("titles");
        if (titleFlag != null) {
          titles = (Boolean) titleFlag.getValue();
        }
        Flag greetingFlag = flags.get("greeting");
        if (greetingFlag != null) {
          greeting = (String) greetingFlag.getValue();
          MainUtil.format(
              C.PREFIX_GREETING.s() + greeting,
              plot,
              pp,
              false,
              new RunnableVal<String>() {
                @Override
                public void run(String value) {
                  MainUtil.sendMessage(pp, value);
                }
              });
        } else {
          greeting = "";
        }
        Flag enter = flags.get("notify-enter");
        if (enter != null && (Boolean) enter.getValue()) {
          if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
            for (UUID uuid : plot.getOwners()) {
              PlotPlayer owner = UUIDHandler.getPlayer(uuid);
              if (owner != null && !owner.getUUID().equals(pp.getUUID())) {
                MainUtil.sendMessage(
                    owner,
                    C.NOTIFY_ENTER
                        .s()
                        .replace("%player", pp.getName())
                        .replace("%plot", plot.getId().toString()));
              }
            }
          }
        }
        Flag gamemodeFlag = flags.get("gamemode");
        if (gamemodeFlag != null) {
          if (pp.getGameMode() != gamemodeFlag.getValue()) {
            if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
              pp.setGameMode((PlotGameMode) gamemodeFlag.getValue());
            } else {
              MainUtil.sendMessage(
                  pp,
                  StringMan.replaceAll(
                      C.GAMEMODE_WAS_BYPASSED.s(),
                      "{plot}",
                      plot.getId(),
                      "{gamemode}",
                      gamemodeFlag.getValue()));
            }
          }
        }
        Flag flyFlag = flags.get("fly");
        if (flyFlag != null) {
          pp.setFlight((boolean) flyFlag.getValue());
        }
        Flag timeFlag = flags.get("time");
        if (timeFlag != null) {
          try {
            long time = (long) timeFlag.getValue();
            pp.setTime(time);
          } catch (Exception e) {
            FlagManager.removePlotFlag(plot, "time");
          }
        }
        Flag weatherFlag = flags.get("weather");
        if (weatherFlag != null) {
          pp.setWeather((PlotWeather) weatherFlag.getValue());
        }

        Flag musicFlag = flags.get("music");
        if (musicFlag != null) {
          Integer id = (Integer) musicFlag.getValue();
          if ((id >= 2256 && id <= 2267) || (id == 0)) {
            Location loc = pp.getLocation();
            Location lastLoc = pp.getMeta("music");
            if (lastLoc != null) {
              pp.playMusic(lastLoc, 0);
              if (id == 0) {
                pp.deleteMeta("music");
              }
            }
            if (id != 0) {
              try {
                pp.setMeta("music", loc);
                pp.playMusic(loc, id);
              } catch (Exception ignored) {
              }
            }
          }
        } else {
          Location lastLoc = pp.getMeta("music");
          if (lastLoc != null) {
            pp.deleteMeta("music");
            pp.playMusic(lastLoc, 0);
          }
        }
        CommentManager.sendTitle(pp, plot);
      } else if (titles) {
        greeting = "";
      } else {
        return true;
      }
      if (titles) {
        if (!C.TITLE_ENTERED_PLOT.s().isEmpty() || !C.TITLE_ENTERED_PLOT_SUB.s().isEmpty()) {
          TaskManager.runTaskLaterAsync(
              new Runnable() {
                @Override
                public void run() {
                  Plot lastPlot = pp.getMeta("lastplot");
                  if ((lastPlot != null) && plot.getId().equals(lastPlot.getId())) {
                    Map<String, String> replacements = new HashMap<>();
                    replacements.put("%x%", lastPlot.getId().x + "");
                    replacements.put("%z%", lastPlot.getId().y + "");
                    replacements.put("%world%", plot.getArea().toString());
                    replacements.put("%greeting%", greeting);
                    replacements.put("%alias", plot.toString());
                    replacements.put("%s", MainUtil.getName(plot.owner));
                    String main = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
                    String sub =
                        StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements);
                    AbstractTitle.sendTitle(pp, main, sub);
                  }
                }
              },
              20);
        }
      }
      return true;
    }
    return true;
  }
Ejemplo n.º 21
0
 @Override
 public boolean onCommand(final PlotPlayer player, final String... args) {
   final List<String> allowed_params =
       Arrays.asList(
           "calibrate-analysis",
           "remove-flag",
           "stop-expire",
           "start-expire",
           "show-expired",
           "update-expired",
           "seen",
           "trim-check");
   if (args.length > 0) {
     final String arg = args[0].toLowerCase();
     String script;
     boolean async = false;
     switch (arg) {
       case "analyze":
         {
           final Plot plot = MainUtil.getPlotAbs(player.getLocation());
           if (plot == null) {
             MainUtil.sendMessage(player, C.NOT_IN_PLOT);
             return false;
           }
           final PlotAnalysis analysis = plot.getComplexity();
           if (analysis != null) {
             final int complexity = analysis.getComplexity();
             MainUtil.sendMessage(player, "Changes/column: " + (analysis.changes / 1.0));
             MainUtil.sendMessage(player, "Complexity: " + complexity);
             return true;
           }
           MainUtil.sendMessage(player, "$1Starting task...");
           HybridUtils.manager.analyzePlot(
               plot,
               new RunnableVal<PlotAnalysis>() {
                 @Override
                 public void run() {
                   MainUtil.sendMessage(
                       player, "$1Done: $2use $3/plot debugexec analyze$2 for more information");
                 }
               });
           return true;
         }
       case "calibrate-analysis":
         {
           if (args.length != 2) {
             MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze <threshold>");
             MainUtil.sendMessage(
                 player,
                 "$1<threshold> $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating it)");
             return false;
           }
           double threshold;
           try {
             threshold = Integer.parseInt(args[1]) / 100d;
           } catch (final NumberFormatException e) {
             MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]);
             MainUtil.sendMessage(
                 player,
                 "$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
             return false;
           }
           PlotAnalysis.calcOptimalModifiers(
               new Runnable() {
                 @Override
                 public void run() {
                   MainUtil.sendMessage(
                       player, "$1Thank you for calibrating PlotSquared plot expiry");
                 }
               },
               threshold);
           return true;
         }
       case "stop-expire":
         {
           if (ExpireManager.task != -1) {
             PS.get().TASK.cancelTask(ExpireManager.task);
           } else {
             return MainUtil.sendMessage(player, "Task already halted");
           }
           ExpireManager.task = -1;
           return MainUtil.sendMessage(player, "Cancelled task.");
         }
       case "remove-flag":
         {
           if (args.length != 2) {
             MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <flag>");
             return false;
           }
           final String flag = args[1];
           for (final Plot plot : PS.get().getPlots()) {
             if (FlagManager.getPlotFlagRaw(plot, flag) != null) {
               FlagManager.removePlotFlag(plot, flag);
             }
           }
           return MainUtil.sendMessage(player, "Cleared flag: " + flag);
         }
       case "start-rgar":
         {
           if (args.length != 2) {
             MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar <world>");
             return false;
           }
           boolean result;
           if (!PS.get().isPlotWorld(args[1])) {
             MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
             return false;
           }
           if (HybridUtils.regions != null) {
             result =
                 ((BukkitHybridUtils) (HybridUtils.manager))
                     .scheduleRoadUpdate(args[1], HybridUtils.regions, 0);
           } else {
             result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0);
           }
           if (!result) {
             MainUtil.sendMessage(
                 player, "&cCannot schedule mass schematic update! (Is one already in progress?)");
             return false;
           }
           return true;
         }
       case "stop-rgar":
         {
           if (!HybridUtils.UPDATE) {
             MainUtil.sendMessage(player, "&cTASK NOT RUNNING!");
             return false;
           }
           HybridUtils.UPDATE = false;
           MainUtil.sendMessage(player, "&cCancelling task... (please wait)");
           return true;
         }
       case "start-expire":
         {
           if (ExpireManager.task == -1) {
             ExpireManager.runTask();
           } else {
             return MainUtil.sendMessage(player, "Plot expiry task already started");
           }
           return MainUtil.sendMessage(player, "Started plot expiry task");
         }
       case "update-expired":
         {
           if (args.length > 1) {
             final String world = args[1];
             if (!BlockManager.manager.isWorld(world)) {
               return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
             }
             MainUtil.sendMessage(player, "Updating expired plot list");
             ExpireManager.updateExpired(args[1]);
             return true;
           }
           return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>");
         }
       case "show-expired":
         {
           if (args.length > 1) {
             final String world = args[1];
             if (!BlockManager.manager.isWorld(world)) {
               return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
             }
             if (!ExpireManager.expiredPlots.containsKey(args[1])) {
               return MainUtil.sendMessage(player, "No task for world: " + args[1]);
             }
             MainUtil.sendMessage(
                 player,
                 "Expired plots (" + ExpireManager.expiredPlots.get(args[1]).size() + "):");
             for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) {
               MainUtil.sendMessage(
                   player,
                   " - "
                       + plot.world
                       + ";"
                       + plot.id.x
                       + ";"
                       + plot.id.y
                       + ";"
                       + UUIDHandler.getName(plot.owner)
                       + " : "
                       + ExpireManager.dates.get(plot.owner));
             }
             return true;
           }
           return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>");
         }
       case "seen":
         {
           if (args.length != 2) {
             return MainUtil.sendMessage(player, "Use /plot debugexec seen <player>");
           }
           final UUID uuid = UUIDHandler.getUUID(args[1], null);
           if (uuid == null) {
             return MainUtil.sendMessage(player, "player not found: " + args[1]);
           }
           final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
           if ((op == null) || (op.getLastPlayed() == 0)) {
             return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]);
           }
           final Timestamp stamp = new Timestamp(op.getLastPlayed());
           final Date date = new Date(stamp.getTime());
           MainUtil.sendMessage(player, "PLAYER: " + args[1]);
           MainUtil.sendMessage(player, "UUID: " + uuid);
           MainUtil.sendMessage(player, "Object: " + date.toGMTString());
           MainUtil.sendMessage(player, "GMT: " + date.toGMTString());
           MainUtil.sendMessage(player, "Local: " + date.toLocaleString());
           return true;
         }
       case "trim-check":
         {
           if (args.length != 2) {
             MainUtil.sendMessage(player, "Use /plot debugexec trim-check <world>");
             MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim");
             return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run");
           }
           final String world = args[1];
           if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(args[1])) {
             return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
           }
           final ArrayList<ChunkLoc> empty = new ArrayList<>();
           final boolean result =
               Trim.getTrimRegions(
                   empty,
                   world,
                   new Runnable() {
                     @Override
                     public void run() {
                       Trim.sendMessage(
                           "Processing is complete! Here's how many chunks would be deleted:");
                       Trim.sendMessage(" - MCA #: " + empty.size());
                       Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)");
                       Trim.sendMessage("Exporting log for manual approval...");
                       final File file =
                           new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt");
                       PrintWriter writer;
                       try {
                         writer = new PrintWriter(file);
                         for (final ChunkLoc loc : empty) {
                           writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca");
                         }
                         writer.close();
                         Trim.sendMessage("File saved to 'plugins/PlotSquared/trim.txt'");
                       } catch (final FileNotFoundException e) {
                         e.printStackTrace();
                         Trim.sendMessage("File failed to save! :(");
                       }
                       Trim.sendMessage("How to get the chunk coords from a region file:");
                       Trim.sendMessage(
                           " - Locate the x,z values for the region file (the two numbers which are separated by a dot)");
                       Trim.sendMessage(
                           " - Multiply each number by 32; this gives you the starting position");
                       Trim.sendMessage(" - Add 31 to each number to get the end position");
                     }
                   });
           if (!result) {
             MainUtil.sendMessage(player, "Trim task already started!");
           }
           return result;
         }
       case "h":
       case "he":
       case "?":
       case "help":
         {
           MainUtil.sendMessage(
               player,
               "Possible sub commands: /plot debugexec <"
                   + StringMan.join(allowed_params, "|")
                   + ">");
           return false;
         }
       case "addcmd":
         {
           try {
             final String cmd =
                 StringMan.join(
                     Files.readLines(
                         new File(
                             new File(PS.get().IMP.getDirectory() + File.separator + "scripts"),
                             args[1]),
                         StandardCharsets.UTF_8),
                     System.getProperty("line.separator"));
             final Command<PlotPlayer> subcommand =
                 new Command<PlotPlayer>(args[1].split("\\.")[0]) {
                   @Override
                   public boolean onCommand(final PlotPlayer plr, final String[] args) {
                     try {
                       scope.put("PlotPlayer", plr);
                       scope.put("args", args);
                       engine.eval(cmd, scope);
                       return true;
                     } catch (final ScriptException e) {
                       e.printStackTrace();
                       MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG);
                       return false;
                     }
                   }
                 };
             MainCommand.getInstance().addCommand(subcommand);
             return true;
           } catch (final Exception e) {
             e.printStackTrace();
             MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>");
             return false;
           }
         }
       case "runasync":
         {
           async = true;
         }
       case "run":
         {
           try {
             script =
                 StringMan.join(
                     Files.readLines(
                         new File(
                             new File(PS.get().IMP.getDirectory() + File.separator + "scripts"),
                             args[1]),
                         StandardCharsets.UTF_8),
                     System.getProperty("line.separator"));
             if (args.length > 2) {
               final HashMap<String, String> replacements = new HashMap<>();
               for (int i = 2; i < args.length; i++) {
                 replacements.put("%s" + (i - 2), args[i]);
               }
               script = StringMan.replaceFromMap(script, replacements);
             }
           } catch (final IOException e) {
             e.printStackTrace();
             return false;
           }
           break;
         }
       default:
         {
           script = StringMan.join(args, " ");
         }
     }
     if (!ConsolePlayer.isConsole(player)) {
       MainUtil.sendMessage(player, C.NOT_CONSOLE);
       return false;
     }
     init();
     scope.put("PlotPlayer", player);
     PS.debug("> " + script);
     try {
       if (async) {
         final String toExec = script;
         TaskManager.runTaskAsync(
             new Runnable() {
               @Override
               public void run() {
                 final long start = System.currentTimeMillis();
                 Object result = null;
                 try {
                   result = engine.eval(toExec, scope);
                 } catch (final ScriptException e) {
                   e.printStackTrace();
                 }
                 PS.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
               }
             });
       } else {
         final long start = System.currentTimeMillis();
         Object result = engine.eval(script, scope);
         PS.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
       }
       return true;
     } catch (final ScriptException e) {
       e.printStackTrace();
       return false;
     }
   }
   return false;
 }
Ejemplo n.º 22
0
  @Override
  public boolean onCommand(final PlotPlayer plr, final String[] args) {

    final Location loc = plr.getLocationFull();
    final Plot plot = MainUtil.getPlot(loc);
    if (plot == null) {
      return !sendMessage(plr, C.NOT_IN_PLOT);
    }
    if ((plot == null) || !plot.hasOwner()) {
      MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
      return false;
    }
    final boolean admin = Permissions.hasPermission(plr, "plots.admin.command.merge");
    if (!plot.isOwner(plr.getUUID()) && !admin) {
      MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
      return false;
    }
    int direction = -1;
    if (args.length == 0) {
      switch (direction(plr.getLocationFull().getYaw())) {
        case "NORTH":
          direction = 0;
          break;
        case "EAST":
          direction = 1;
          break;
        case "SOUTH":
          direction = 2;
          break;
        case "WEST":
          direction = 3;
          break;
      }
    } else {
      for (int i = 0; i < values.length; i++) {
        if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) {
          direction = i;
          break;
        }
      }
    }
    if (direction == -1) {
      MainUtil.sendMessage(
          plr,
          C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(values, C.BLOCK_LIST_SEPARATER.s()));
      MainUtil.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw())));
      return false;
    }
    PlotId bot = MainUtil.getBottomPlot(plot).id;
    PlotId top = MainUtil.getTopPlot(plot).id;
    ArrayList<PlotId> selPlots;
    final String world = loc.getWorld();
    switch (direction) {
      case 0: // north = -y
        selPlots =
            MainUtil.getMaxPlotSelectionIds(
                world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
        break;
      case 1: // east = +x
        selPlots =
            MainUtil.getMaxPlotSelectionIds(
                world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
        break;
      case 2: // south = +y
        selPlots =
            MainUtil.getMaxPlotSelectionIds(
                world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
        break;
      case 3: // west = -x
        selPlots =
            MainUtil.getMaxPlotSelectionIds(
                world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
        break;
      default:
        return false;
    }
    int size = selPlots.size();
    if (Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS) < size) {
      MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + size);
      return false;
    }
    final PlotId botId = selPlots.get(0);
    final PlotId topId = selPlots.get(selPlots.size() - 1);
    final PlotId bot1 = MainUtil.getBottomPlot(MainUtil.getPlot(world, botId)).id;
    final PlotId bot2 = MainUtil.getBottomPlot(MainUtil.getPlot(world, topId)).id;
    final PlotId top1 = MainUtil.getTopPlot(MainUtil.getPlot(world, topId)).id;
    final PlotId top2 = MainUtil.getTopPlot(MainUtil.getPlot(world, botId)).id;
    bot = new PlotId(Math.min(bot1.x, bot2.x), Math.min(bot1.y, bot2.y));
    top = new PlotId(Math.max(top1.x, top2.x), Math.max(top1.y, top2.y));
    final ArrayList<PlotId> plots = MainUtil.getMaxPlotSelectionIds(world, bot, top);
    boolean multiMerge = false;
    final HashSet<UUID> multiUUID = new HashSet<UUID>();
    HashSet<PlotId> multiPlots = new HashSet<>();
    final UUID u1 = plot.owner;
    for (final PlotId myid : plots) {
      final Plot myplot = PS.get().getPlot(world, myid);
      if (myplot == null || myplot.owner == null) {
        MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
        return false;
      }
      UUID u2 = myplot.owner;
      if (u2.equals(u1)) {
        continue;
      }
      PlotPlayer p2 = UUIDHandler.getPlayer(u2);
      if (p2 == null) {
        MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
        return false;
      }
      multiMerge = true;
      multiPlots.add(myid);
      multiUUID.add(u2);
    }
    if (multiMerge) {
      if (!Permissions.hasPermission(plr, C.PERMISSION_MERGE_OTHER)) {
        MainUtil.sendMessage(plr, C.NO_PERMISSION, C.PERMISSION_MERGE_OTHER.s());
        return false;
      }
      for (final UUID uuid : multiUUID) {
        PlotPlayer accepter = UUIDHandler.getPlayer(uuid);
        CmdConfirm.addPending(
            accepter,
            C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", plr.getName()),
            new Runnable() {
              @Override
              public void run() {
                PlotPlayer accepter = UUIDHandler.getPlayer(uuid);
                multiUUID.remove(uuid);
                if (multiUUID.size() == 0) {
                  PlotPlayer pp = UUIDHandler.getPlayer(u1);
                  if (pp == null) {
                    sendMessage(accepter, C.MERGE_NOT_VALID);
                    return;
                  }
                  final PlotWorld plotWorld = PS.get().getPlotWorld(world);
                  if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
                    double cost = plotWorld.MERGE_PRICE;
                    cost = plots.size() * cost;
                    if (cost > 0d) {
                      if (EconHandler.manager.getMoney(plr) < cost) {
                        sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
                        return;
                      }
                      EconHandler.manager.withdrawMoney(plr, cost);
                      sendMessage(plr, C.REMOVED_BALANCE, cost + "");
                    }
                  }
                  final boolean result = EventUtil.manager.callMerge(world, plot, plots);
                  if (!result) {
                    MainUtil.sendMessage(plr, "&cMerge has been cancelled");
                    return;
                  }
                  MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
                  MainUtil.mergePlots(world, plots, true, true);
                  MainUtil.setSign(UUIDHandler.getName(plot.owner), plot);
                }
                MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED);
              }
            });
      }
      MainUtil.sendMessage(plr, C.MERGE_REQUESTED);
      return true;
    }
    final PlotWorld plotWorld = PS.get().getPlotWorld(world);
    if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
      double cost = plotWorld.MERGE_PRICE;
      cost = plots.size() * cost;
      if (cost > 0d) {
        if (EconHandler.manager.getMoney(plr) < cost) {
          sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
          return false;
        }
        EconHandler.manager.withdrawMoney(plr, cost);
        sendMessage(plr, C.REMOVED_BALANCE, cost + "");
      }
    }
    final boolean result = EventUtil.manager.callMerge(world, plot, plots);
    if (!result) {
      MainUtil.sendMessage(plr, "&cMerge has been cancelled");
      return false;
    }
    MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
    MainUtil.mergePlots(world, plots, true, true);
    MainUtil.setSign(UUIDHandler.getName(plot.owner), plot);
    return true;
  }
Ejemplo n.º 23
0
 public static boolean plotExit(final PlotPlayer pp, Plot plot) {
   pp.deleteMeta("lastplot");
   EventUtil.manager.callLeave(pp, plot);
   if (plot.hasOwner()) {
     PlotArea pw = plot.getArea();
     if (pw == null) {
       return true;
     }
     if (FlagManager.getPlotFlagRaw(plot, "gamemode") != null) {
       if (pp.getGameMode() != pw.GAMEMODE) {
         if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
           pp.setGameMode(pw.GAMEMODE);
         } else {
           MainUtil.sendMessage(
               pp,
               StringMan.replaceAll(
                   C.GAMEMODE_WAS_BYPASSED.s(),
                   "{plot}",
                   plot.toString(),
                   "{gamemode}",
                   pw.GAMEMODE.name().toLowerCase()));
         }
       }
     }
     Flag farewell = FlagManager.getPlotFlagRaw(plot, "farewell");
     if (farewell != null) {
       MainUtil.format(
           C.PREFIX_FAREWELL.s() + farewell.getValueString(),
           plot,
           pp,
           false,
           new RunnableVal<String>() {
             @Override
             public void run(String value) {
               MainUtil.sendMessage(pp, value);
             }
           });
     }
     Flag leave = FlagManager.getPlotFlagRaw(plot, "notify-leave");
     if ((leave != null) && (Boolean) leave.getValue()) {
       if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
         for (UUID uuid : plot.getOwners()) {
           PlotPlayer owner = UUIDHandler.getPlayer(uuid);
           if ((owner != null) && !owner.getUUID().equals(pp.getUUID())) {
             MainUtil.sendMessage(
                 pp,
                 C.NOTIFY_LEAVE
                     .s()
                     .replace("%player", pp.getName())
                     .replace("%plot", plot.getId().toString()));
           }
         }
       }
     }
     if (FlagManager.getPlotFlagRaw(plot, "fly") != null) {
       PlotGameMode gamemode = pp.getGameMode();
       if (gamemode == PlotGameMode.SURVIVAL || (gamemode == PlotGameMode.ADVENTURE)) {
         pp.setFlight(false);
       }
     }
     if (FlagManager.getPlotFlagRaw(plot, "time") != null) {
       pp.setTime(Long.MAX_VALUE);
     }
     if (FlagManager.getPlotFlagRaw(plot, "weather") != null) {
       pp.setWeather(PlotWeather.RESET);
     }
     Location lastLoc = pp.getMeta("music");
     if (lastLoc != null) {
       pp.deleteMeta("music");
       pp.playMusic(lastLoc, 0);
     }
   }
   return true;
 }
Ejemplo n.º 24
0
 @Subscribe
 public void onWorldChange(EntityTeleportEvent event) {
   Entity entity = event.getEntity();
   if (entity instanceof Player) {
     org.spongepowered.api.world.Location from = event.getOldLocation();
     org.spongepowered.api.world.Location to = event.getNewLocation();
     int x2;
     if (getInt(from.getX()) != (x2 = getInt(to.getX()))) {
       Player player = (Player) entity;
       PlotPlayer pp = SpongeUtil.getPlayer(player);
       Extent extent = to.getExtent();
       if (!(extent instanceof World)) {
         pp.deleteMeta("location");
         return;
       }
       pp.setMeta("location", SpongeUtil.getLocation(player));
       World world = (World) extent;
       String worldname = ((World) extent).getName();
       PlotWorld plotworld = PS.get().getPlotWorld(worldname);
       if (plotworld == null) {
         return;
       }
       PlotManager plotManager = PS.get().getPlotManager(worldname);
       PlotId id = plotManager.getPlotId(plotworld, x2, 0, getInt(to.getZ()));
       Plot lastPlot = (Plot) pp.getMeta("lastplot");
       if (id == null) {
         if (lastPlot == null) {
           return;
         }
         if (!PlotListener.plotExit(pp, lastPlot)) {
           MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
           if (lastPlot.equals(MainUtil.getPlot(SpongeUtil.getLocation(worldname, from)))) {
             event.setNewLocation(from);
           } else {
             event.setNewLocation(world.getSpawnLocation());
           }
           return;
         }
       } else if (lastPlot != null && id.equals(lastPlot.id)) {
         return;
       } else {
         Plot plot = MainUtil.getPlot(worldname, id);
         if (!PlotListener.plotEntry(pp, plot)) {
           MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
           if (!plot.equals(MainUtil.getPlot(SpongeUtil.getLocation(worldname, from)))) {
             event.setNewLocation(from);
           } else {
             event.setNewLocation(world.getSpawnLocation());
           }
           return;
         }
       }
       Integer border = MainUtil.worldBorder.get(worldname);
       if (border != null) {
         if (x2 > border) {
           Vector3d pos = to.getPosition();
           to = to.setPosition(new Vector3d(border - 4, pos.getY(), pos.getZ()));
           event.setNewLocation(to);
           MainUtil.sendMessage(pp, C.BORDER);
         } else if (x2 < -border) {
           Vector3d pos = to.getPosition();
           to = to.setPosition(new Vector3d(-border + 4, pos.getY(), pos.getZ()));
           event.setNewLocation(to);
           MainUtil.sendMessage(pp, C.BORDER);
         }
       }
       return;
     }
     int z2;
     if (getInt(from.getZ()) != (z2 = getInt(to.getZ()))) {
       Player player = (Player) entity;
       PlotPlayer pp = SpongeUtil.getPlayer(player);
       Extent extent = to.getExtent();
       if (!(extent instanceof World)) {
         pp.deleteMeta("location");
         return;
       }
       pp.setMeta("location", SpongeUtil.getLocation(player));
       World world = (World) extent;
       String worldname = ((World) extent).getName();
       PlotWorld plotworld = PS.get().getPlotWorld(worldname);
       if (plotworld == null) {
         return;
       }
       PlotManager plotManager = PS.get().getPlotManager(worldname);
       PlotId id = plotManager.getPlotId(plotworld, x2, 0, z2);
       Plot lastPlot = (Plot) pp.getMeta("lastplot");
       if (id == null) {
         if (lastPlot == null) {
           return;
         }
         if (!PlotListener.plotExit(pp, lastPlot)) {
           MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
           if (lastPlot.equals(MainUtil.getPlot(SpongeUtil.getLocation(worldname, from)))) {
             event.setNewLocation(from);
           } else {
             event.setNewLocation(player.getWorld().getSpawnLocation());
           }
           return;
         }
       } else if (lastPlot != null && id.equals(lastPlot.id)) {
         return;
       } else {
         Plot plot = MainUtil.getPlot(worldname, id);
         if (!PlotListener.plotEntry(pp, plot)) {
           MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
           if (!plot.equals(MainUtil.getPlot(SpongeUtil.getLocation(worldname, from)))) {
             event.setNewLocation(from);
           } else {
             event.setNewLocation(player.getWorld().getSpawnLocation());
           }
           return;
         }
       }
       Integer border = MainUtil.worldBorder.get(worldname);
       if (border != null) {
         if (z2 > border) {
           Vector3d pos = to.getPosition();
           to = to.setPosition(new Vector3d(pos.getX(), pos.getY(), border - 4));
           event.setNewLocation(to);
           MainUtil.sendMessage(pp, C.BORDER);
         } else if (z2 < -border) {
           Vector3d pos = to.getPosition();
           to = to.setPosition(new Vector3d(pos.getX(), pos.getY(), -border + 4));
           event.setNewLocation(to);
           MainUtil.sendMessage(pp, C.BORDER);
         }
       }
     }
   }
 }
Ejemplo n.º 25
0
 @Override
 public void unregister(PlotPlayer player) {
   SpongeUtil.removePlayer(player.getName());
 }
Ejemplo n.º 26
0
 @Override
 public boolean onCommand(final PlotPlayer plr, final String... args) {
   final Location loc = plr.getLocation();
   final Plot plot;
   if (args.length == 1) {
     if (args[0].equalsIgnoreCase("mine")) {
       Set<Plot> plots = plr.getPlots();
       if (plots.size() > 0) {
         plot = plots.iterator().next();
       } else {
         MainUtil.sendMessage(plr, C.NO_PLOTS);
         return false;
       }
     } else {
       plot = MainUtil.getPlotFromString(plr, args[0], true);
     }
     if (plot == null) {
       MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
       return false;
     }
   } else if (args.length == 0) {
     plot = MainUtil.getPlotAbs(loc);
     if (plot == null) {
       MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
       C.NOT_IN_PLOT.send(plr);
       return false;
     }
   } else {
     MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
     return false;
   }
   if ((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))
       && !Permissions.hasPermission(plr, "plots.admin.command.clear")) {
     return sendMessage(plr, C.NO_PLOT_PERMS);
   }
   if (plot.getRunning() != 0) {
     MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
     return false;
   }
   if ((FlagManager.getPlotFlagRaw(plot, "done") != null)
       && (!Permissions.hasPermission(plr, "plots.continue")
           || (Settings.DONE_COUNTS_TOWARDS_LIMIT
               && (MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr))))) {
     MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE);
     return false;
   }
   final Runnable runnable =
       new Runnable() {
         @Override
         public void run() {
           final long start = System.currentTimeMillis();
           final boolean result =
               MainUtil.clearAsPlayer(
                   plot,
                   plot.owner == null,
                   new Runnable() {
                     @Override
                     public void run() {
                       plot.unlink();
                       SetBlockQueue.addNotify(
                           new Runnable() {
                             @Override
                             public void run() {
                               plot.removeRunning();
                               // If the state changes, then mark it as no longer done
                               if (FlagManager.getPlotFlagRaw(plot, "done") != null) {
                                 FlagManager.removePlotFlag(plot, "done");
                               }
                               if (FlagManager.getPlotFlagRaw(plot, "analysis") != null) {
                                 FlagManager.removePlotFlag(plot, "analysis");
                               }
                               MainUtil.sendMessage(
                                   plr,
                                   C.CLEARING_DONE,
                                   "" + (System.currentTimeMillis() - start));
                             }
                           });
                     }
                   });
           if (!result) {
             MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
           } else {
             plot.addRunning();
           }
         }
       };
   if (Settings.CONFIRM_CLEAR && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) {
     CmdConfirm.addPending(plr, "/plot clear " + plot.id, runnable);
   } else {
     TaskManager.runTask(runnable);
   }
   return true;
 }
Ejemplo n.º 27
0
  @Override
  public boolean execute(final PlotPlayer player, final String... args) {
    if (args.length == 1) {
      if (args[0].equalsIgnoreCase("next")) {
        ArrayList<Plot> plots = new ArrayList<>(PlotSquared.getPlots());
        Collections.sort(
            plots,
            new Comparator<Plot>() {
              @Override
              public int compare(Plot p1, Plot p2) {
                int v1 = 0;
                int v2 = 0;
                if (p1.settings.ratings != null) {
                  for (Entry<UUID, Integer> entry : p1.settings.ratings.entrySet()) {
                    v1 -= 11 - entry.getValue();
                  }
                }
                if (p2.settings.ratings != null) {
                  for (Entry<UUID, Integer> entry : p2.settings.ratings.entrySet()) {
                    v2 -= 11 - entry.getValue();
                  }
                }
                return v2 - v1;
              }
            });
        UUID uuid = player.getUUID();
        for (Plot p : plots) {
          if (p.settings.ratings == null || !p.settings.ratings.containsKey(uuid)) {
            MainUtil.teleportPlayer(player, player.getLocation(), p);
            MainUtil.sendMessage(player, C.RATE_THIS);
            return true;
          }
        }
        MainUtil.sendMessage(player, C.FOUND_NO_PLOTS);
        return false;
      }
    }
    final Location loc = player.getLocation();
    final Plot plot = MainUtil.getPlot(loc);
    if (plot == null) {
      return !sendMessage(player, C.NOT_IN_PLOT);
    }
    if (!plot.hasOwner()) {
      sendMessage(player, C.RATING_NOT_OWNED);
      return true;
    }
    if (plot.isOwner(player.getUUID())) {
      sendMessage(player, C.RATING_NOT_YOUR_OWN);
      return true;
    }
    if (Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() != 0) {
      final Runnable run =
          new Runnable() {
            @Override
            public void run() {
              if (plot.settings.ratings.containsKey(player.getUUID())) {
                sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
                return;
              }
              final MutableInt index = new MutableInt(0);
              final MutableInt rating = new MutableInt(0);
              String title = Settings.RATING_CATEGORIES.get(0);
              PlotInventory inventory =
                  new PlotInventory(player, 1, title) {
                    public boolean onClick(int i) {
                      rating.add((i + 1) * Math.pow(10, index.intValue()));
                      index.increment();
                      if (index.intValue() >= Settings.RATING_CATEGORIES.size()) {
                        close();
                        // set rating!
                        plot.settings.ratings.put(player.getUUID(), rating.intValue());
                        DBFunc.setRating(plot, player.getUUID(), rating.intValue());
                        sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
                        sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
                        return false;
                      }
                      setTitle(Settings.RATING_CATEGORIES.get(index.intValue()));
                      return false;
                    }
                  };
              inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8", null));
              inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8", null));
              inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8", null));
              inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8", null));
              inventory.setItem(4, new PlotItemStack(35, (short) 5, 4, "4/8", null));
              inventory.setItem(5, new PlotItemStack(35, (short) 9, 5, "5/8", null));
              inventory.setItem(6, new PlotItemStack(35, (short) 11, 6, "6/8", null));
              inventory.setItem(7, new PlotItemStack(35, (short) 10, 7, "7/8", null));
              inventory.setItem(8, new PlotItemStack(35, (short) 2, 8, "8/8", null));
              inventory.openInventory();
            }
          };
      if (plot.settings.ratings == null) {
        TaskManager.runTaskAsync(
            new Runnable() {
              @Override
              public void run() {
                plot.settings.ratings = DBFunc.getRatings(plot);
                run.run();
              }
            });
        return true;
      }
      run.run();
      return true;
    }
    if (args.length < 1) {
      sendMessage(player, C.RATING_NOT_VALID);
      return true;
    }
    final String arg = args[0];

    if (arg.equalsIgnoreCase("next")) {}

    final int rating;
    if (StringUtils.isNumeric(arg) && arg.length() < 3 && arg.length() > 0) {
      rating = Integer.parseInt(arg);
      if (rating > 10) {
        sendMessage(player, C.RATING_NOT_VALID);
        return false;
      }
    } else {
      sendMessage(player, C.RATING_NOT_VALID);
      return false;
    }
    final UUID uuid = player.getUUID();
    final Runnable run =
        new Runnable() {
          @Override
          public void run() {
            if (plot.settings.ratings.containsKey(uuid)) {
              sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
              return;
            }
            plot.settings.ratings.put(uuid, rating);
            DBFunc.setRating(plot, uuid, rating);
            sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
          }
        };
    if (plot.settings.ratings == null) {
      TaskManager.runTaskAsync(
          new Runnable() {
            @Override
            public void run() {
              plot.settings.ratings = DBFunc.getRatings(plot);
              run.run();
            }
          });
      return true;
    }
    run.run();
    return true;
  }
Ejemplo n.º 28
0
 @Override
 public boolean onCommand(PlotPlayer player, String... args) {
   if (args.length == 1) {
     if ("next".equalsIgnoreCase(args[0])) {
       ArrayList<Plot> plots = new ArrayList<>(PS.get().getBasePlots());
       Collections.sort(
           plots,
           (p1, p2) -> {
             double v1 = 0;
             if (!p1.getRatings().isEmpty()) {
               for (Map.Entry<UUID, Rating> entry : p1.getRatings().entrySet()) {
                 v1 -= 11 - entry.getValue().getAverageRating();
               }
             }
             double v2 = 0;
             if (!p2.getRatings().isEmpty()) {
               for (Map.Entry<UUID, Rating> entry : p2.getRatings().entrySet()) {
                 v2 -= 11 - entry.getValue().getAverageRating();
               }
             }
             if (v1 == v2) {
               return -0;
             }
             return v2 > v1 ? 1 : -1;
           });
       UUID uuid = player.getUUID();
       for (Plot p : plots) {
         if ((!Settings.Done.REQUIRED_FOR_RATINGS || p.hasFlag(Flags.DONE))
             && p.isBasePlot()
             && (p.hasRatings() || !p.getRatings().containsKey(uuid))
             && !p.isAdded(uuid)) {
           p.teleportPlayer(player);
           MainUtil.sendMessage(player, C.RATE_THIS);
           return true;
         }
       }
       MainUtil.sendMessage(player, C.FOUND_NO_PLOTS);
       return false;
     }
   }
   Plot plot = player.getCurrentPlot();
   if (plot == null) {
     return !this.sendMessage(player, C.NOT_IN_PLOT);
   }
   if (!plot.hasOwner()) {
     this.sendMessage(player, C.RATING_NOT_OWNED);
     return false;
   }
   if (plot.isOwner(player.getUUID())) {
     this.sendMessage(player, C.RATING_NOT_YOUR_OWN);
     return false;
   }
   if (Settings.Done.REQUIRED_FOR_RATINGS && !plot.hasFlag(Flags.DONE)) {
     this.sendMessage(player, C.RATING_NOT_DONE);
     return false;
   }
   if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) {
     Runnable run =
         new Runnable() {
           @Override
           public void run() {
             if (plot.getRatings().containsKey(player.getUUID())) {
               Rate.this.sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
               return;
             }
             MutableInt index = new MutableInt(0);
             MutableInt rating = new MutableInt(0);
             String title = Settings.Ratings.CATEGORIES.get(0);
             PlotInventory inventory =
                 new PlotInventory(player, 1, title) {
                   @Override
                   public boolean onClick(int i) {
                     rating.add((i + 1) * Math.pow(10, index.getValue()));
                     index.increment();
                     if (index.getValue() >= Settings.Ratings.CATEGORIES.size()) {
                       int rV = rating.getValue();
                       Rating result =
                           EventUtil.manager.callRating(this.player, plot, new Rating(rV));
                       plot.addRating(this.player.getUUID(), result);
                       Rate.this.sendMessage(
                           this.player, C.RATING_APPLIED, plot.getId().toString());
                       if (Permissions.hasPermission(this.player, "plots.comment")) {
                         Command command = MainCommand.getInstance().getCommand(Comment.class);
                         if (command != null) {
                           MainUtil.sendMessage(this.player, C.COMMENT_THIS, command.getUsage());
                         }
                       }
                       return false;
                     }
                     this.setTitle(Settings.Ratings.CATEGORIES.get(index.getValue()));
                     return true;
                   }
                 };
             inventory.setItem(0, new PlotItemStack(35, (short) 12, 0, "0/8"));
             inventory.setItem(1, new PlotItemStack(35, (short) 14, 1, "1/8"));
             inventory.setItem(2, new PlotItemStack(35, (short) 1, 2, "2/8"));
             inventory.setItem(3, new PlotItemStack(35, (short) 4, 3, "3/8"));
             inventory.setItem(4, new PlotItemStack(35, (short) 5, 4, "4/8"));
             inventory.setItem(5, new PlotItemStack(35, (short) 9, 5, "5/8"));
             inventory.setItem(6, new PlotItemStack(35, (short) 11, 6, "6/8"));
             inventory.setItem(7, new PlotItemStack(35, (short) 10, 7, "7/8"));
             inventory.setItem(8, new PlotItemStack(35, (short) 2, 8, "8/8"));
             inventory.openInventory();
           }
         };
     if (plot.getSettings().ratings == null) {
       if (!Settings.Enabled_Components.RATING_CACHE) {
         TaskManager.runTaskAsync(
             () -> {
               plot.getSettings().ratings = DBFunc.getRatings(plot);
               run.run();
             });
         return true;
       }
       plot.getSettings().ratings = new HashMap<>();
     }
     run.run();
     return true;
   }
   if (args.length < 1) {
     this.sendMessage(player, C.RATING_NOT_VALID);
     return true;
   }
   String arg = args[0];
   int rating;
   if (MathMan.isInteger(arg) && arg.length() < 3 && !arg.isEmpty()) {
     rating = Integer.parseInt(arg);
     if (rating > 10 || rating < 1) {
       this.sendMessage(player, C.RATING_NOT_VALID);
       return false;
     }
   } else {
     this.sendMessage(player, C.RATING_NOT_VALID);
     return false;
   }
   UUID uuid = player.getUUID();
   Runnable run =
       () -> {
         if (plot.getRatings().containsKey(uuid)) {
           this.sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString());
           return;
         }
         Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating));
         plot.addRating(uuid, result);
         this.sendMessage(player, C.RATING_APPLIED, plot.getId().toString());
       };
   if (plot.getSettings().ratings == null) {
     if (!Settings.Enabled_Components.RATING_CACHE) {
       TaskManager.runTaskAsync(
           () -> {
             plot.getSettings().ratings = DBFunc.getRatings(plot);
             run.run();
           });
       return true;
     }
     plot.getSettings().ratings = new HashMap<>();
   }
   run.run();
   return true;
 }
 @Override
 public UUID getUUID(final PlotPlayer player) {
   return UUID.nameUUIDFromBytes(
       ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
 }
Ejemplo n.º 30
0
  /**
   * Format a string with plot information.
   *
   * @param info
   * @param plot
   * @param player
   * @param full
   * @param whenDone
   */
  public static void format(
      String info, Plot plot, PlotPlayer player, boolean full, RunnableVal<String> whenDone) {
    int num = plot.getConnectedPlots().size();
    String alias = !plot.getAlias().isEmpty() ? plot.getAlias() : C.NONE.s();
    Location bot = plot.getCorners()[0];
    String biome = WorldUtil.IMP.getBiome(plot.getArea().worldname, bot.getX(), bot.getZ());
    String trusted = getPlayerList(plot.getTrusted());
    String members = getPlayerList(plot.getMembers());
    String denied = getPlayerList(plot.getDenied());
    String seen;
    if (Settings.Enabled_Components.PLOT_EXPIRY) {
      if (plot.isOnline()) {
        seen = C.NOW.s();
      } else {
        int time = (int) (ExpireManager.IMP.getAge(plot) / 1000);
        seen = time != 0 ? secToTime(time) : C.UNKNOWN.s();
      }
    } else {
      seen = C.NEVER.s();
    }
    Optional<String> descriptionFlag = plot.getFlag(Flags.DESCRIPTION);
    String description =
        descriptionFlag.isPresent()
            ? Flags.DESCRIPTION.valueToString(descriptionFlag.get())
            : C.NONE.s();

    StringBuilder flags = new StringBuilder();
    HashMap<Flag<?>, Object> flagMap =
        FlagManager.getPlotFlags(plot.getArea(), plot.getSettings(), true);
    if (flagMap.isEmpty()) {
      flags.append(C.NONE.s());
    } else {
      String prefix = "";
      for (Map.Entry<Flag<?>, Object> entry : flagMap.entrySet()) {
        flags.append(prefix).append(C.PLOT_FLAG_LIST.f(entry.getKey().getName(), entry.getValue()));
        prefix = ", ";
      }
    }
    boolean build = plot.isAdded(player.getUUID());
    String owner = plot.getOwners().isEmpty() ? "unowned" : getPlayerList(plot.getOwners());
    info = info.replace("%id%", plot.getId().toString());
    info = info.replace("%alias%", alias);
    info = info.replace("%num%", String.valueOf(num));
    info = info.replace("%desc%", description);
    info = info.replace("%biome%", biome);
    info = info.replace("%owner%", owner);
    info = info.replace("%members%", members);
    info = info.replace("%player%", player.getName());
    info = info.replace("%trusted%", trusted);
    info = info.replace("%helpers%", members);
    info = info.replace("%denied%", denied);
    info = info.replace("%seen%", seen);
    info = info.replace("%flags%", flags);
    info = info.replace("%build%", String.valueOf(build));
    info = info.replace("%desc%", "No description set.");
    if (info.contains("%rating%")) {
      String newInfo = info;
      TaskManager.runTaskAsync(
          () -> {
            int max = 10;
            if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) {
              max = 8;
            }
            String info1;
            if (full
                && Settings.Ratings.CATEGORIES != null
                && Settings.Ratings.CATEGORIES.size() > 1) {
              double[] ratings = getAverageRatings(plot);
              String rating = "";
              String prefix = "";
              for (int i = 0; i < ratings.length; i++) {
                rating +=
                    prefix
                        + Settings.Ratings.CATEGORIES.get(i)
                        + '='
                        + String.format("%.1f", ratings[i]);
                prefix = ",";
              }
              info1 = newInfo.replaceAll("%rating%", rating);
            } else {
              info1 =
                  newInfo.replaceAll(
                      "%rating%", String.format("%.1f", plot.getAverageRating()) + '/' + max);
            }
            whenDone.run(info1);
          });
      return;
    }
    whenDone.run(info);
  }