Exemple #1
0
public class Jail extends Cmd implements TabCompleter {
  BottomLine pl = BottomLine.getInstance();
  Jails j = Jails.getInstance();
  PlayerData pd;
  String prefix = "§8[§eLaw§8] ";

  public Jail() {
    super("jail", Permissions.JAIL);
  }

  public void run(CommandSender sender, String[] args) {
    if (args.length < 3) {
      Util.invalidArgCount(
          sender,
          "Jail",
          "Send a player to a place where they cannot speak, place blocks, etc.",
          "/jail [player] [timestamp] [jail]",
          "/jail [player] [timestamp] [jail] <reason>",
          "/jail unjail [player]");
      return;
    }

    if (args[0].equalsIgnoreCase("unjail")) {
      if (args.length == 1) {
        Util.invalidArgCount(sender, "Jail", "Unjail a jailed player.", "/jail unjail [player]");
        return;
      }

      Player target = Bukkit.getPlayer(args[1]);
      if (target == null) {
        Util.offline(sender, "Jail", args[1]);
        return;
      }
      pd = new PlayerData(target.getUniqueId());

      if (!(Store.muted.contains(target.getName()))) {
        sender.sendMessage(
            "§cJail: §4The chosen player §o(" + target.getName() + ") §4is not jailed!");
        return;
      } else if (Store.muted.contains(target.getName())) {
        Store.muted.remove(target.getName());
        Bukkit.broadcastMessage(
            prefix + "§ePlayer §c" + sender.getName() + "§e unjailed §c" + target.getDisplayName());
      }

      target.teleport(pd.getLocation());
      return;
    }

    args[1] = args[1].toLowerCase();

    final Player target = Bukkit.getPlayer(args[0]);
    if (target == null) {
      Util.offline(sender, "Jail", args[0]);
      return;
    }

    if (target.isOp()) {
      Util.punishOps(sender, "Jail");
      return;
    }

    if (Store.jailed.contains(target.getName())) {
      sender.sendMessage(
          "§cJail: §4The selected player §o(" + target.getName() + ") §cis already jailed!");
      return;
    }

    String regex = "(?:(?<h>\\d+)h)?(?:(?<m>\\d+)m)?(?:(?<s>\\d+)s)?(?:(?<d>\\d+)d)?";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(args[1].toString());

    String timeValue = args[1].replaceFirst(".*?(\\d+).*", "$1");

    if (m.matches()) {
      if (m.group(1) != null) {
        long time = Integer.parseInt(timeValue) * 72000;
        Bukkit.getScheduler()
            .scheduleSyncDelayedTask(
                pl,
                new Runnable() {

                  @Override
                  public void run() {
                    Store.jailed.remove(target.getName());
                    target.teleport(pd.getLocation());
                    target.sendMessage("§cJail: §4You've been unjailed with a warning.");
                  }
                },
                time);
      } else if (m.group(2) != null) {
        long time = Integer.parseInt(timeValue) * 1200;
        Bukkit.getScheduler()
            .scheduleSyncDelayedTask(
                pl,
                new Runnable() {

                  @Override
                  public void run() {
                    Store.jailed.remove(target.getName());
                    target.teleport(pd.getLocation());
                    target.sendMessage("§cJail: §4You've been unjailed with a warning.");
                  }
                },
                time);
      } else if (m.group(3) != null) {
        long time = Integer.parseInt(timeValue) * 20;
        Bukkit.getScheduler()
            .scheduleSyncDelayedTask(
                pl,
                new Runnable() {

                  @Override
                  public void run() {
                    Store.jailed.remove(target.getName());
                    target.teleport(pd.getLocation());
                    target.sendMessage("§cJail: §4You've been unjailed with a warning.");
                  }
                },
                time);
      } else if (m.group(4) != null) {
        long time = Integer.parseInt(timeValue) * 1728000;
        Bukkit.getScheduler()
            .scheduleSyncDelayedTask(
                pl,
                new Runnable() {

                  @Override
                  public void run() {
                    Store.jailed.remove(target.getName());
                    target.teleport(pd.getLocation());
                    target.sendMessage("§cJail: §4You've been unjailed with a warning.");
                  }
                },
                time);
      }
    } else {
      Util.invalidTimestamp(sender, "Jail", args[1]);
      return;
    }

    if (j.getConfig().getConfigurationSection(args[2]) == null) {
      sender.sendMessage("§cJail: §4The jail §o(" + args[2] + ") §4does not exist!");
      if (j.getConfig().getStringList("existing").size() == 0) {
        sender.sendMessage("§4There are no existing jails, please create one!");
      } else {
        sender.sendMessage("§4Existing jails:");
        for (int i = 0; i < j.getConfig().getStringList("existing").size(); i++) {
          sender.sendMessage("§c- " + j.getConfig().getStringList("existing").get(i));
        }
      }
      return;
    }

    Location loc = j.getLocation(args[2]);
    target.teleport(loc);

    SimpleDateFormat sdf = new SimpleDateFormat("(z) dd/MM/yy hh:mm:ss a");
    Date date = new Date();

    if (args.length == 3) {
      pd = new PlayerData(target.getUniqueId());
      pd.addHistory(Types.JAIL, "Misconduct", sender.getName(), sdf.format(date), args[1]);

      Bukkit.broadcastMessage(
          prefix
              + "§ePlayer §c"
              + sender.getName()
              + " §ejailed §c"
              + pd.getDisplayName()
              + " §efor "
              + args[1]
              + "!");
    } else {
      String msg = "";
      for (int i = 3; i < args.length; i++) {
        msg = msg + args[i] + " ";
      }

      pd = new PlayerData(target.getUniqueId());
      pd.addHistory(Types.JAIL, msg.trim(), sender.getName(), sdf.format(date), args[1]);

      Bukkit.broadcastMessage(
          prefix
              + "§ePlayer §c"
              + sender.getName()
              + " §ejailed §c"
              + pd.getDisplayName()
              + " §efor "
              + args[1]
              + " because "
              + msg.trim()
              + "!");
    }

    Store.jailed.add(target.getName());

    Util.sendActionBar(target, prefix + "§eJail expires in " + args[1] + "!");
  }

  @EventHandler
  public void blockCommands(PlayerCommandPreprocessEvent e) {
    if (Store.jailed.contains(e.getPlayer().getName())) {
      if (e.getMessage().toLowerCase().contains("/")) {
        if (Store.jailBlocked.contains("**")) {
          e.setCancelled(true);
          e.getPlayer().sendMessage(Util.colour(pl.getConfig().getString("law.crimeMessage")));
        } else {
          for (int i = 0; i < Store.jailBlocked.size(); i++) {
            if (e.getMessage().toLowerCase().contains(Store.jailBlocked.get(i))) {
              e.setCancelled(true);
              e.getPlayer().sendMessage(Util.colour(pl.getConfig().getString("law.crimeMessage")));
            }
          }
        }
      }
    }
  }

  @EventHandler
  public void onPlayerChat(AsyncPlayerChatEvent e) {
    if (Store.jailed.contains(e.getPlayer().getName())) {
      e.setCancelled(true);
      e.getPlayer().sendMessage(Util.colour(pl.getConfig().getString("law.jail.noSpeak")));
    }
  }

  @EventHandler
  public void onBlockPlace(BlockPlaceEvent e) {
    if (Store.jailed.contains(e.getPlayer().getName())) {
      e.setCancelled(true);
      e.getPlayer().sendMessage(Util.colour(pl.getConfig().getString("law.crimeMessage")));
    }
  }

  @EventHandler
  public void onBlockBreak(BlockBreakEvent e) {
    if (Store.jailed.contains(e.getPlayer().getName())) {
      e.setCancelled(true);
      e.getPlayer().sendMessage(Util.colour(pl.getConfig().getString("law.crimeMessage")));
    }
  }

  @Override
  public List<String> onTabComplete(CommandSender sender, Command cmd, String lbl, String[] args) {
    if (cmd.getName().equalsIgnoreCase("jail")) {
      if (args.length == 1 && args.length < 2) {
        ArrayList<String> players = new ArrayList<>();

        if (!args[0].equalsIgnoreCase("")) {
          for (Player player : Bukkit.getOnlinePlayers()) {
            if (player.getName().toLowerCase().startsWith(args[0].toLowerCase())) {
              players.add(player.getName());
            }
          }
        } else {
          for (Player player : Bukkit.getOnlinePlayers()) {
            players.add(player.getName());
          }
        }

        Collections.sort(players);
        return players;
      }
    }
    return null;
  }
}
/**
 * <code>BottomLine.java</code> </br> <code>BottomLine</code> </br> </br> Created by Banjo226 on 31
 * Oct 2015 at 4:45 pm AEST </br> Copyright © 2015-2016 Banjo226. All rights reserved.
 *
 * @see {@link https://github.com/Banjo-226/bottom-line/wiki}
 * @author Banjo226
 * @version 1.2 major
 */
public class BottomLine extends JavaPlugin implements Listener {
  public static BottomLine bl;

  public PluginDescriptionFile pdf;
  public String vers;
  public String servervs;
  public File file;
  public FileConfiguration conf;

  static Chat chat = null;
  static Permission perm = null;

  public static boolean update = false;

  Data d = Data.getInstance();
  Money e = Money.getInstance();
  Jails j = Jails.getInstance();
  Warps w = Warps.getInstance();
  Spawns s = Spawns.getInstance();
  TextFiles txt = TextFiles.getInstance();

  public void onEnable() {
    bl = this;
    pdf = this.getDescription();
    vers = pdf.getVersion();
    servervs = Bukkit.getServer().getClass().getPackage().getName();
    servervs = servervs.substring(servervs.lastIndexOf(".") + 1);
    file = new File(this.getDataFolder(), "config.yml");

    registerEvents(
        this,
        new MOTD(),
        new JoinLeaveListener(),
        new AdminChat(),
        new God(),
        new AFK(),
        new ConfigListener(),
        new WeatherListener(),
        new Mute(),
        new Jail(),
        new NewPlayerListener(),
        new Plugins(),
        new Version(),
        new Freeze(),
        new BanJoinListener(),
        new Open(),
        new Item(),
        new ClicksPerSecondListener(),
        new CommandSpy(),
        new PowerTool(),
        new DeathListener(),
        new ChatEventManager(),
        new FeedSign(),
        new HealSign(),
        new RespawnListener(),
        new QuickGM(),
        new FormatSigns(),
        new KitSign(),
        new QuickTime(),
        new QuickWeather());
    setup();

    Bukkit.getScheduler()
        .scheduleSyncRepeatingTask(this, new TicksPerSecond(), 100L, 1L); // updates the tps
    Bukkit.getScheduler()
        .scheduleSyncRepeatingTask(
            this, new ClicksPerSecond(), 0L, 20L); // Updating the rates for CPS

    debug("Enabled Bottom Line (" + pdf.getDescription() + ") v" + vers + ".");

    Bukkit.getScheduler()
        .runTaskTimerAsynchronously(
            this,
            new Runnable() {
              public void run() {
                if (Bukkit.getServer().getPluginManager().getPlugin("Vault") != null) {
                  try {
                    setupChat();
                  } catch (Exception e) {
                    debug("No chat dependency found!");
                  }

                  try {
                    setupPermissions();
                  } catch (Exception e) {
                    debug("No permissions dependency found!");
                  }

                  try {
                    Updater u = new Updater(15348, bl);
                    u.start();
                  } catch (Exception e) {
                    error("Could not check for update (no connection?)");
                  }
                }
              }
            },
            0,
            432020);
  }

  public void onDisable() {
    bl = null;
    Store.spam.clear();
    Store.reply.clear();
  }

  protected void registerEvents(Plugin plugin, Listener... listeners) {
    for (Listener listener : listeners) {
      Bukkit.getServer().getPluginManager().registerEvents(listener, plugin);
    }
  }

  protected void setup() {
    commands();
    config();
    new Store();
    new Util();
    new Permissions();

    if (getConfig().getBoolean("metrics") == true) {
      try {
        HttpURLConnection url = (HttpURLConnection) new URL("http://mcstats.org").openConnection();
        url.setRequestMethod("HEAD");
        url.setConnectTimeout(5000);
        int response = url.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
          Metrics m = new Metrics(this);
          m.start();

          debug("Started metrics!");
        } else {
          warning("Metrics is currently down (response code " + response + ")");
        }
      } catch (Exception e) {
        warning("Could not connect to metrics; server is most likely down!");
      }
    }

    if (Bukkit.getServer().getPluginManager().getPlugin("Vault") != null) {
      debug("Enabled Vault connection!");
      Bukkit.getServicesManager()
          .register(Economy.class, new VaultConnector(), this, ServicePriority.Highest);
    } else {
      error(
          "Could not find vault! This plugin can no longer find Vault and may throw errors into console. It is highly recommended you download vault.");
    }
  }

  protected boolean setupChat() {
    RegisteredServiceProvider<Chat> rsp =
        getServer().getServicesManager().getRegistration(Chat.class);
    chat = rsp.getProvider();
    debug("Found chat plugin: " + rsp.getProvider().getName());
    return chat != null;
  }

  protected boolean setupPermissions() {
    RegisteredServiceProvider<Permission> rsp =
        getServer().getServicesManager().getRegistration(Permission.class);
    perm = rsp.getProvider();
    debug("Found permissions plugin: " + rsp.getProvider().getName());
    return perm != null;
  }

  protected void commands() {
    // Our command manager instance
    CommandManager cmd = new CommandManager();

    /*
     * A loop that loops through everything in the plugin.yml file, if its a command, we'll register it.
     */
    for (Entry<String, Map<String, Object>> entry : pdf.getCommands().entrySet()) {
      String command = entry.getKey();
      this.getCommand(command).setExecutor(cmd);
      this.getCommand(command).setPermissionMessage(PermissionMessages.CMD.toString());
      this.getCommand(command).setTabCompleter(cmd);
    }

    /*
     * Checks if the commands have been registered for the law systems
     */
    if (Bukkit.getPluginManager().getPlugin("LiteBans") != null) {
      String[] punishments = {"ban", "unban", "tempban", "kick"};

      for (String s : punishments) {
        if (getCommand(s).isRegistered()) {
          this.getCommand(s).setExecutor(null);
        }
      }
    }
  }

  protected void config() {
    if (!file.exists()) {
      warning("Creating new configuration file for Bottom Line");
    }

    conf = YamlConfiguration.loadConfiguration(file);

    if (file.exists()) {
      saveDefaultConfig();

      if (Updater.compareVersions(vers, getConfig().getString("version")) == 1) {
        File configFolder = new File(this.getDataFolder() + File.separator + "archives");
        if (!configFolder.exists()) {
          configFolder.mkdirs();
        }

        File oldConfig =
            new File(configFolder.getPath(), "config " + getConfig().getString("version") + ".txt");

        try {
          if (oldConfig.getName().equals("config " + vers + ".txt")) {
            configFolder.delete();
            oldConfig.delete();
          } else {
            if (!configFolder.exists()) {
              configFolder.mkdirs();
            }
            oldConfig.createNewFile();

            warning("Crearted new configuration file, renamed old file to " + oldConfig.getName());
          }
        } catch (IOException e) {
          e.printStackTrace();
          error("Failed to create a copy of the old config file while generating new one!");
        }

        file.renameTo(oldConfig);
      }
    }

    saveDefaultConfig();
    d.setup(this);
    e.setup(this);
    j.setup(this);
    w.setup(this);
    s.setup(this);
    txt.setup(this);

    debug("Enabled configuration!");
  }

  public static void debug(String msg) {
    System.out.println("[BottomLine] " + msg);
  }

  public static void warning(String msg) {
    debug("[!] " + msg);
  }

  public static void error(String msg) {
    System.err.println("[BottomLine] [!] [EXCEPTION] " + msg);
  }

  public static BottomLine getInstance() {
    return bl;
  }

  public Chat getChat() {
    return chat;
  }

  public Permission getPerms() {
    return perm;
  }
}