diff --git a/pom.xml b/pom.xml index 2e0bb4e..6e22e09 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.rammelkast.anticheatreloaded AntiCheatReloaded - 1.9.5 + alpha-2-b1 AntiCheatReloaded https://www.spigotmc.org/resources/anticheatreloaded.23799/ @@ -70,12 +70,6 @@ ProtocolLib 4.6.0-SNAPSHOT - - org.spigotmc - spigot - 1.8.8-R0.1-SNAPSHOT - provided - org.spigotmc spigot diff --git a/src/main/java/com/rammelkast/anticheatreloaded/AntiCheatReloaded.java b/src/main/java/com/rammelkast/anticheatreloaded/AntiCheatReloaded.java deleted file mode 100644 index 1c58bcc..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/AntiCheatReloaded.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded; - -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.Callable; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; - -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.rammelkast.anticheatreloaded.command.CommandHandler; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.event.BlockListener; -import com.rammelkast.anticheatreloaded.event.EntityListener; -import com.rammelkast.anticheatreloaded.event.InventoryListener; -import com.rammelkast.anticheatreloaded.event.PlayerListener; -import com.rammelkast.anticheatreloaded.event.VehicleListener; -import com.rammelkast.anticheatreloaded.manage.AntiCheatManager; -import com.rammelkast.anticheatreloaded.metrics.Metrics; -import com.rammelkast.anticheatreloaded.util.PacketListener; -import com.rammelkast.anticheatreloaded.util.UpdateManager; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class AntiCheatReloaded extends JavaPlugin { - - public static final List MUTE_ENABLED_MODS = new ArrayList(); - - private static AntiCheatManager manager; - private static AntiCheatReloaded plugin; - private static List eventList = new ArrayList(); - private static Configuration config; - private static boolean verbose; - private static ProtocolManager protocolManager; - private static SecureRandom random; - private static Long loadTime; - private static UpdateManager updateManager; - - private double tps = -1; - private String symbiosisMetric = "None"; - - @Override - public void onEnable() { - plugin = this; - random = new SecureRandom(); - loadTime = System.currentTimeMillis(); - manager = new AntiCheatManager(this, getLogger()); - eventList.add(new PlayerListener()); - eventList.add(new BlockListener()); - eventList.add(new EntityListener()); - eventList.add(new VehicleListener()); - eventList.add(new InventoryListener()); - // Order is important in some cases, don't screw with these unless - // needed, especially config - this.setupConfig(); - this.setupEvents(); - this.setupCommands(); - // Enterprise must come before levels - this.setupEnterprise(); - this.restoreLevels(); - - if (Bukkit.getPluginManager().getPlugin("ProtocolLib") != null) { - this.setupProtocol(); - } else { - Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.DARK_GRAY + "> " + ChatColor.RED - + "Could not find ProtocolLib. Shutting down!"); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - - Bukkit.getConsoleSender() - .sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.DARK_GRAY + "> " + ChatColor.GRAY - + "Running Minecraft version " + VersionUtil.getVersion() + " " - + (VersionUtil.isSupported() ? (ChatColor.GREEN + "(supported)") - : (ChatColor.RED + "(NOT SUPPORTED!)"))); - - getLogger().info("Enabling packet listeners"); - PacketListener.listenMovementPackets(); - PacketListener.listenKeepAlivePackets(); - PacketListener.listenUseItemPackets(); - - updateManager = new UpdateManager(); - - // End tests - verboseLog("Finished loading."); - - // Metrics - getServer().getScheduler().runTaskLater(this, new Runnable() { - @Override - public void run() { - checkForSymbiosis(); - try { - Metrics metrics = new Metrics(AntiCheatReloaded.this, 202); - metrics.addCustomChart(new Metrics.SingleLineChart("cheaters_kicked", new Callable() { - @Override - public Integer call() throws Exception { - int kicked = playersKicked; - // Reset so we don't keep sending the same value - playersKicked = 0; - return kicked; - } - })); - metrics.addCustomChart(new Metrics.SimplePie("protocollib_version", new Callable() { - @Override - public String call() throws Exception { - return Bukkit.getPluginManager().getPlugin("ProtocolLib").getDescription().getVersion(); - } - })); - metrics.addCustomChart(new Metrics.SimplePie("nms_version", new Callable() { - @Override - public String call() throws Exception { - return VersionUtil.getVersion(); - } - })); - metrics.addCustomChart(new Metrics.SimplePie("symbiosis", new Callable() { - @Override - public String call() throws Exception { - return symbiosisMetric; - } - })); - } catch (Exception e) { - e.printStackTrace(); - } - } - }, 90L); - - // Launch TPS check - new BukkitRunnable() { - long sec; - long currentSec; - int ticks; - - public void run() { - sec = (System.currentTimeMillis() / 1000L); - if (currentSec == sec) { - ticks += 1; - } else { - currentSec = sec; - tps = (tps == 0.0D ? ticks : (tps + ticks) / 2.0D); - ticks = 1; - } - - // Check for updates every 12 hours - if (ticks % 864000 == 0) - updateManager.update(); - } - }.runTaskTimer(this, 40L, 1L); - } - - @Override - public void onDisable() { - verboseLog("Saving user levels..."); - config.getLevels().saveLevelsFromUsers(getManager().getUserManager().getUsers()); - - AntiCheatManager.close(); - getServer().getScheduler().cancelTasks(this); - cleanup(); - } - - private void setupProtocol() { - protocolManager = ProtocolLibrary.getProtocolManager(); - verboseLog("Hooked into ProtocolLib"); - } - - private void setupEvents() { - for (Listener listener : eventList) { - getServer().getPluginManager().registerEvents(listener, this); - verboseLog("Registered events for ".concat(listener.toString().split("@")[0].split(".anticheat.")[1])); - } - } - - private void setupCommands() { - getCommand("anticheat").setExecutor(new CommandHandler()); - verboseLog("Registered commands."); - } - - private void setupConfig() { - config = manager.getConfiguration(); - verboseLog("Setup the config."); - } - - private void setupEnterprise() { - if (config.getConfig().enterprise.getValue()) { - if (config.getEnterprise().loggingEnabled.getValue()) { - config.getEnterprise().database.cleanEvents(); - } - } - } - - private void restoreLevels() { - for (Player player : getServer().getOnlinePlayers()) { - UUID uuid = player.getUniqueId(); - - User user = new User(uuid); - user.setIsWaitingOnLevelSync(true); - config.getLevels().loadLevelToUser(user); - - manager.getUserManager().addUser(user); - verboseLog("Data for " + uuid + " loaded"); - } - } - - public static AntiCheatReloaded getPlugin() { - return plugin; - } - - public static AntiCheatManager getManager() { - return manager; - } - - public static SecureRandom getRandom() { - return random; - } - - public static String getVersion() { - return manager.getPlugin().getDescription().getVersion(); - } - - private void cleanup() { - eventList = null; - manager = null; - config = null; - } - - public static void debugLog(final String string) { - Bukkit.getScheduler().runTask(getPlugin(), new Runnable() { - public void run() { - if (getManager().getConfiguration().getConfig().debugMode.getValue()) { - manager.debugLog("[DEBUG] " + string); - } - } - }); - } - - public void verboseLog(final String string) { - if (verbose) { - getLogger().info(string); - } - } - - public void setVerbose(boolean b) { - verbose = b; - } - - public Long getLoadTime() { - return loadTime; - } - - public static ProtocolManager getProtocolManager() { - return protocolManager; - } - - /** - * Amount of players kicked since start - */ - private int playersKicked = 0; - - public void onPlayerKicked() { - this.playersKicked++; - } - - /** - * Creates metric that checks for anti-cheat symbiosis - * I use this to see if AntiCheatReloaded is actively being used - * together with other anti-cheats, so I can account for that. - */ - protected void checkForSymbiosis() { - if (Bukkit.getPluginManager().getPlugin("NoCheatPlus") != null) { - if (this.symbiosisMetric.equals("None")) { - this.symbiosisMetric = "NoCheatPlus"; - } else { - this.symbiosisMetric += ", NoCheatPlus"; - } - } - if (Bukkit.getPluginManager().getPlugin("Matrix") != null) { - if (this.symbiosisMetric.equals("None")) { - this.symbiosisMetric = "Matrix"; - } else { - this.symbiosisMetric += ", Matrix"; - } - } - if (Bukkit.getPluginManager().getPlugin("AAC") != null) { - if (this.symbiosisMetric.equals("None")) { - this.symbiosisMetric = "AAC"; - } else { - this.symbiosisMetric += ", AAC"; - } - } - if (Bukkit.getPluginManager().getPlugin("Spartan") != null) { - if (this.symbiosisMetric.equals("None")) { - this.symbiosisMetric = "Spartan"; - } else { - this.symbiosisMetric += ", Spartan"; - } - } - if (Bukkit.getPluginManager().getPlugin("Negativity") != null) { - if (this.symbiosisMetric.equals("None")) { - this.symbiosisMetric = "Negativity"; - } else { - this.symbiosisMetric += ", Negativity"; - } - } - } - - public static void sendToMainThread(Runnable runnable) { - Bukkit.getScheduler().runTask(AntiCheatReloaded.getPlugin(), runnable); - } - - public void sendToStaff(String message) { - Bukkit.getOnlinePlayers().forEach(player -> { - if (player.hasPermission("anticheat.system.alert")) { - if (!MUTE_ENABLED_MODS.contains(player.getUniqueId())) { - player.sendMessage(message); - } - } - }); - } - - public static UpdateManager getUpdateManager() { - return updateManager; - } - - public double getTPS() { - if (this.tps < 0 || this.tps > 20) { - return 20; - } - return this.tps; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/api/AntiCheatAPI.java b/src/main/java/com/rammelkast/anticheatreloaded/api/AntiCheatAPI.java deleted file mode 100644 index 0cb26b1..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/api/AntiCheatAPI.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.api; - -import java.util.List; - -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.manage.AntiCheatManager; -import com.rammelkast.anticheatreloaded.manage.CheckManager; -import com.rammelkast.anticheatreloaded.manage.UserManager; -import com.rammelkast.anticheatreloaded.util.Group; - -/** - * Developer's interface for all things AntiCheat. - */ - -public class AntiCheatAPI { - private static CheckManager chk = AntiCheatReloaded.getManager().getCheckManager(); - private static UserManager umr = AntiCheatReloaded.getManager().getUserManager(); - - // CheckManager API - - /** - * Start running a certain check - * - * @param type Check to start watching for - */ - public static void activateCheck(CheckType type, Class caller) { - chk.activateCheck(type, caller.getName()); - } - - /** - * Stop running a certain check - * - * @param type Check to stop watching for - */ - public static void deactivateCheck(CheckType type, Class caller) { - chk.deactivateCheck(type, caller.getName()); - } - - /** - * Find out if a check is currently being watched for - * - * @param type Type to check - * @return true if plugin is watching for this check - */ - public static boolean isActive(CheckType type) { - return chk.isActive(type); - } - - /** - * Allow a player to skip a certain check - * - * @param player Player to stop watching - * @param type Check to stop watching for - */ - public static void exemptPlayer(Player player, CheckType type, Class caller) { - chk.exemptPlayer(player, type, caller.getName()); - } - - /** - * Stop allowing a player to skip a certain check - * - * @param player Player to start watching - * @param type Check to start watching for - */ - public static void unexemptPlayer(Player player, CheckType type, Class caller) { - chk.unexemptPlayer(player, type, caller.getName()); - } - - /** - * Find out if a player is currently exempt from a certain check - * - * @param player Player to check - * @param type Type to check - * @return true if plugin is ignoring this check on this player - */ - public static boolean isExempt(Player player, CheckType type) { - return chk.isExempt(player, type); - } - - /** - * Find out if a check will occur for a player. This checks if they are being tracked, the check is active, the player isn't exempt from the check, and the player doesn't have override permission. - * - * @param player Player to check - * @param type Type to check - * @return true if plugin will check this player, and that all things allow it to happen. - */ - public boolean willCheck(Player player, CheckType type) { - return chk.willCheck(player, type); - } - - // PlayerManager API - - /** - * Reset a player's hack level to 0 - * - * @param player Player to reset - */ - public static void resetPlayer(Player player) { - umr.getUser(player.getUniqueId()).resetLevel(); - } - - /** - * Get a user's {@link com.rammelkast.anticheatreloaded.util.Group} - * - * @param player Player whose group to find - * @return The player's group - */ - public static Group getGroup(Player player) { - return umr.getUser(player.getUniqueId()).getGroup(); - } - - /** - * Get all configured Groups - * - * @return List of all groups - * @see com.rammelkast.anticheatreloaded.util.Group - */ - public static List getGroups() { - return getManager().getConfiguration().getGroups().getGroups(); - } - - // Advanced Users Only API. - - /** - * Get access to all the other managers, advanced users ONLY - * - * @return the AntiCheat Manager - */ - public static AntiCheatManager getManager() { - return AntiCheatReloaded.getManager(); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/api/CheckFailEvent.java b/src/main/java/com/rammelkast/anticheatreloaded/api/CheckFailEvent.java deleted file mode 100644 index 242ba64..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/api/CheckFailEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.api; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.util.User; - -/** - * Fired when a player fails an AntiCheat check - */ - -public class CheckFailEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - - private final User user; - private final CheckType type; - - public CheckFailEvent(User user, CheckType type) { - this.user = user; - this.type = type; - } - - /** - * Get the {@link com.rammelkast.anticheatreloaded.util.User} who failed the check - * - * @return a {@link com.rammelkast.anticheatreloaded.util.User} - */ - public User getUser() { - return user; - } - - /** - * Get the {@link com.rammelkast.anticheatreloaded.check.CheckType} failed - * - * @return a {@link com.rammelkast.anticheatreloaded.check.CheckType} - */ - public CheckType getCheck() { - return type; - } - - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/Backend.java b/src/main/java/com/rammelkast/anticheatreloaded/check/Backend.java deleted file mode 100644 index 7ac195c..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/Backend.java +++ /dev/null @@ -1,723 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerToggleSprintEvent; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck; -import com.rammelkast.anticheatreloaded.check.combat.VelocityCheck; -import com.rammelkast.anticheatreloaded.check.movement.AimbotCheck; -import com.rammelkast.anticheatreloaded.check.movement.ElytraCheck; -import com.rammelkast.anticheatreloaded.check.movement.FlightCheck; -import com.rammelkast.anticheatreloaded.check.movement.NoSlowCheck; -import com.rammelkast.anticheatreloaded.check.packet.MorePacketsCheck; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.config.providers.Lang; -import com.rammelkast.anticheatreloaded.config.providers.Magic; -import com.rammelkast.anticheatreloaded.manage.AntiCheatManager; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class Backend { - public Map velocitized = new HashMap(); - private Map levitatingEnd = new HashMap(); - private Map chatLevel = new HashMap(); - private Map commandLevel = new HashMap(); - private Map nofallViolation = new HashMap(); - private Map blockBreakHolder = new HashMap(); - private Map fastPlaceViolation = new HashMap(); - private Map lastBlockPlaced = new HashMap(); - private Map lastBlockPlaceTime = new HashMap(); - private Map blockPunches = new HashMap(); - private Map projectilesShot = new HashMap(); - private Map velocitytrack = new HashMap(); - private Map startEat = new HashMap(); - private Map lastHeal = new HashMap(); - private Map projectileTime = new HashMap(); - private Map bowWindUp = new HashMap(); - private Map sprinted = new HashMap(); - private Map brokenBlock = new HashMap(); - public Map placedBlock = new HashMap(); - private Map blockTime = new HashMap(); - private Map blocksDropped = new HashMap(); - private Map lastInventoryTime = new HashMap(); - private Map inventoryTime = new HashMap(); - private Map inventoryClicks = new HashMap(); - private HashSet transparent = new HashSet(); - private Map lastFallPacket = new HashMap(); - private Map fastSneakViolations = new HashMap(); - private Map lastSneak = new HashMap(); - - private Magic magic; - private Checks checksConfig; - private AntiCheatManager manager = null; - private Lang lang = null; - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public Backend(AntiCheatManager instance) { - magic = instance.getConfiguration().getMagic(); - checksConfig = instance.getConfiguration().getChecks(); - manager = instance; - lang = manager.getConfiguration().getLang(); - transparent.add((byte) -1); - } - - public Magic getMagic() { - return magic; - } - - public void updateConfig(Configuration config) { - magic = config.getMagic(); - lang = config.getLang(); - } - - public void resetChatLevel(User user) { - chatLevel.put(user.getUUID(), 0); - } - - public void garbageClean(Player player) { - UUID uuid = player.getUniqueId(); - - blocksDropped.remove(uuid); - blockTime.remove(uuid); - brokenBlock.remove(uuid); - placedBlock.remove(uuid); - bowWindUp.remove(uuid); - startEat.remove(uuid); - lastHeal.remove(uuid); - sprinted.remove(uuid); - nofallViolation.remove(uuid); - blockBreakHolder.remove(uuid); - fastPlaceViolation.remove(uuid); - lastBlockPlaced.remove(uuid); - lastBlockPlaceTime.remove(uuid); - blockPunches.remove(uuid); - projectilesShot.remove(uuid); - velocitized.remove(uuid); - velocitytrack.remove(uuid); - startEat.remove(uuid); - lastHeal.remove(uuid); - projectileTime.remove(uuid); - bowWindUp.remove(uuid); - sprinted.remove(uuid); - brokenBlock.remove(uuid); - placedBlock.remove(uuid); - blockTime.remove(uuid); - blocksDropped.remove(uuid); - lastInventoryTime.remove(uuid); - inventoryTime.remove(uuid); - inventoryClicks.remove(uuid); - lastFallPacket.remove(uuid); - fastSneakViolations.remove(uuid); - lastSneak.remove(uuid); - levitatingEnd.remove(uuid); - AimbotCheck.LAST_DELTA_YAW.remove(uuid); - VelocityCheck.VIOLATIONS.remove(uuid); - MorePacketsCheck.LAST_PACKET_TIME.remove(uuid); - MorePacketsCheck.PACKET_BALANCE.remove(uuid); - MorePacketsCheck.EXEMPT_TIMINGS.remove(uuid); - ElytraCheck.JUMP_Y_VALUE.remove(uuid); - KillAuraCheck.ANGLE_FLAGS.remove(uuid); - KillAuraCheck.PACKETORDER_FLAGS.remove(uuid); - FlightCheck.MOVING_EXEMPT.remove(uuid); - NoSlowCheck.LAST_RELEASE.remove(uuid); - NoSlowCheck.VIOLATIONS.remove(uuid); - } - - public CheckResult checkFastBow(Player player, float force) { - // Ignore magic numbers here, they are minecrafty vanilla stuff. - if (!bowWindUp.containsKey(player.getUniqueId())) { - return PASS; - } - int ticks = (int) ((((System.currentTimeMillis() - bowWindUp.get(player.getUniqueId())) * 20) / 1000) + 3); - bowWindUp.remove(player.getUniqueId()); - float f = (float) ticks / 20.0F; - f = (f * f + f * 2.0F) / 3.0F; - f = f > 1.0F ? 1.0F : f; - double bowError = checksConfig.getDouble(CheckType.FAST_BOW, "bowError"); - if (Math.abs(force - f) > bowError) { - return new CheckResult(CheckResult.Result.FAILED, - "fired their bow too fast (actual force=" + force + ", calculated force=" + f + ")"); - } else { - return PASS; - } - } - - public CheckResult checkProjectile(Player player) { - incrementOld(player, projectilesShot, 10); - int projectilesToWait = checksConfig.getInteger(CheckType.FAST_PROJECTILE, "projectilesToWait"); - if (!projectileTime.containsKey(player.getUniqueId())) { - projectileTime.put(player.getUniqueId(), System.currentTimeMillis()); - return new CheckResult(CheckResult.Result.PASSED); - } else if (projectilesShot.get(player.getUniqueId()) == projectilesToWait) { - long time = System.currentTimeMillis() - projectileTime.get(player.getUniqueId()); - int minimumTime = checksConfig.getInteger(CheckType.FAST_PROJECTILE, "minimumTime"); - projectileTime.remove(player.getUniqueId()); - projectilesShot.remove(player.getUniqueId()); - if (time < minimumTime) { - return new CheckResult(CheckResult.Result.FAILED, - "wound up a bow too fast (actual time=" + time + ", min time=" + minimumTime + ")"); - } - } - return PASS; - } - - public CheckResult checkFastDrop(Player player) { - incrementOld(player, blocksDropped, 10); - int dropsToWait = checksConfig.getInteger(CheckType.ITEM_SPAM, "dropsToWait"); - if (!blockTime.containsKey(player.getUniqueId())) { - blockTime.put(player.getUniqueId(), System.currentTimeMillis()); - return new CheckResult(CheckResult.Result.PASSED); - } else if (blocksDropped.get(player.getUniqueId()) == dropsToWait) { - long time = System.currentTimeMillis() - blockTime.get(player.getUniqueId()); - int minimumTime = checksConfig.getInteger(CheckType.ITEM_SPAM, "minimumTime"); - blockTime.remove(player.getUniqueId()); - blocksDropped.remove(player.getUniqueId()); - if (time < minimumTime) { - return new CheckResult(CheckResult.Result.FAILED, - "dropped an item too fast (actual time=" + time + ", min time=" + minimumTime + ")"); - } - } - return PASS; - } - - public CheckResult checkSpider(Player player, double y) { - if (y <= 0.11761 && y >= 0.11759 && !Utilities.isClimbableBlock(player.getLocation().getBlock()) - && !Utilities.isClimbableBlock(player.getEyeLocation().getBlock()) - && !Utilities.isClimbableBlock(player.getLocation().clone().add(0, -0.98, 0).getBlock()) - && !Utilities.isNearClimbable(player)) { - return new CheckResult(CheckResult.Result.FAILED, - "tried to climb a non-climbable block (" + player.getLocation().getBlock().getType() + ")"); - } else { - return PASS; - } - } - - public CheckResult checkNoFall(Player player, double y) { - UUID uuid = player.getUniqueId(); - if (player.getGameMode() != GameMode.CREATIVE && !player.isInsideVehicle() && !player.isSleeping() - && !isMovingExempt(player) && !justPlaced(player) && !Utilities.isNearWater(player) - && !Utilities.isInWeb(player) && !player.getLocation().getBlock().getType().name().endsWith("TRAPDOOR") - && !VersionUtil.isSlowFalling(player) && !Utilities - .isNearShulkerBox(player.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation()) && !Utilities.isNearClimbable(player)) { - if (player.getFallDistance() == 0) { - if (nofallViolation.get(uuid) == null) { - nofallViolation.put(uuid, 1); - } else { - nofallViolation.put(uuid, nofallViolation.get(player.getUniqueId()) + 1); - } - - int i = nofallViolation.get(uuid); - int vlBeforeFlag = checksConfig.getInteger(CheckType.NOFALL, "vlBeforeFlag"); - if (i >= vlBeforeFlag) { - nofallViolation.put(player.getUniqueId(), 1); - return new CheckResult(CheckResult.Result.FAILED, "tried to avoid fall damage (fall distance = 0 " - + i + " times in a row, max=" + vlBeforeFlag + ")"); - } else { - return PASS; - } - } else { - nofallViolation.put(uuid, 0); - return PASS; - } - } - return PASS; - } - - public CheckResult checkSneakToggle(Player player) { - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - final long lastSneak = this.lastSneak.getOrDefault(player.getUniqueId(), (long) 0); - this.lastSneak.put(player.getUniqueId(), System.currentTimeMillis()); - if (System.currentTimeMillis() - lastSneak < checksConfig.getInteger(CheckType.SNEAK, "minToggleTime") - && (AntiCheatReloaded.getPlugin().getTPS() > checksConfig.getInteger(CheckType.SNEAK, "minimumTps"))) { - if (user.isLagging() && checksConfig.getBoolean(CheckType.SNEAK, "disableForLagging")) - return PASS; - - if (!this.silentMode()) - player.teleport(user.getGoodLocation(player.getLocation())); - - return new CheckResult(Result.FAILED, - "toggled sneak too fast (time=" + (System.currentTimeMillis() - lastSneak) + ")"); - } - return PASS; - } - - public CheckResult checkSprintHungry(PlayerToggleSprintEvent event) { - Player player = event.getPlayer(); - int sprintFoodMin = checksConfig.getInteger(CheckType.SPRINT, "sprintFoodMin"); - if (event.isSprinting() && player.getGameMode() != GameMode.CREATIVE - && player.getFoodLevel() <= sprintFoodMin) { - return new CheckResult(CheckResult.Result.FAILED, - "sprinted while hungry (food=" + player.getFoodLevel() + ", min=" + sprintFoodMin + ")"); - } else { - return PASS; - } - } - - public CheckResult checkVClip(Player player, Distance distance) { - double from = Math.round(distance.fromY()); - double to = Math.round(distance.toY()); - - if (player.isInsideVehicle() || (from == to || from < to) || Math.round(distance.getYDifference()) < 2) { - return PASS; - } - - for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++) { - Block block = new Location(player.getWorld(), player.getLocation().getX(), to + i, - player.getLocation().getZ()).getBlock(); - if (block.getType() != Material.AIR && block.getType().isSolid()) { - return new CheckResult(CheckResult.Result.FAILED, "tried to move through a solid block", - (int) from + 3); - } - } - - return PASS; - } - - public CheckResult checkFastPlace(Player player) { - int vlBeforeFlagSurvival = checksConfig.getInteger(CheckType.FAST_PLACE, "vlBeforeFlagSurvival"); - int vlBeforeFlagCreative = checksConfig.getInteger(CheckType.FAST_PLACE, "vlBeforeFlagCreative"); - int blockPlacementTime = checksConfig.getInteger(CheckType.FAST_PLACE, "blockPlacementTime"); - int violations = player.getGameMode() == GameMode.CREATIVE ? vlBeforeFlagCreative : vlBeforeFlagSurvival; - long time = System.currentTimeMillis(); - UUID uuid = player.getUniqueId(); - if (!lastBlockPlaceTime.containsKey(uuid) || !fastPlaceViolation.containsKey(uuid)) { - lastBlockPlaceTime.put(uuid, 0L); - if (!fastPlaceViolation.containsKey(uuid)) { - fastPlaceViolation.put(uuid, 0); - } - } else if (fastPlaceViolation.containsKey(uuid) && fastPlaceViolation.get(uuid) > violations) { - Long math = System.currentTimeMillis() - lastBlockPlaced.get(uuid); - if (lastBlockPlaced.get(uuid) > 0 && math < blockPlacementTime) { - lastBlockPlaced.put(uuid, time); - return new CheckResult(CheckResult.Result.FAILED, "placed blocks too fast " - + fastPlaceViolation.get(uuid) + " times in a row (max=" + violations + ")"); - } else if (lastBlockPlaced.get(uuid) > 0 && math > blockPlacementTime) { - fastPlaceViolation.put(uuid, 0); - } - } else if (lastBlockPlaced.containsKey(uuid)) { - long last = lastBlockPlaced.get(uuid); - long lastTime = lastBlockPlaceTime.get(uuid); - long thisTime = time - last; - int minimumTime = checksConfig.getInteger(CheckType.FAST_PLACE, "minimumTime"); - - if (lastTime != 0 && thisTime < minimumTime) { - lastBlockPlaceTime.put(uuid, (time - last)); - lastBlockPlaced.put(uuid, time); - fastPlaceViolation.put(uuid, fastPlaceViolation.get(uuid) + 1); - return new CheckResult(CheckResult.Result.FAILED, - "tried to place a block " + thisTime + " ms after the last one (min=" + minimumTime + " ms)"); - } - lastBlockPlaceTime.put(uuid, (time - last)); - } - lastBlockPlaced.put(uuid, time); - return PASS; - } - - public void logBowWindUp(Player player) { - bowWindUp.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public void logEatingStart(Player player) { - startEat.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public boolean isEating(Player player) { - return startEat.containsKey(player.getUniqueId()) - && startEat.get(player.getUniqueId()) < checksConfig.getInteger(CheckType.FAST_EAT, "eatTimeMin"); - } - - public void logHeal(Player player) { - lastHeal.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public CheckResult checkChatSpam(Player player, String msg) { - UUID uuid = player.getUniqueId(); - User user = manager.getUserManager().getUser(uuid); - if (user.getLastMessageTime() != -1) { - for (int i = 0; i < 2; i++) { - String m = user.getMessage(i); - if (m == null) { - break; - } - Long l = user.getMessageTime(i); - - int repeatIgnore = checksConfig.getInteger(CheckType.CHAT_SPAM, "repeatIgnore"); - if (System.currentTimeMillis() - l > repeatIgnore) { - user.clearMessages(); - break; - } else { - int timeMin = checksConfig.getInteger(CheckType.CHAT_SPAM, "timeMin"); - if (manager.getConfiguration().getConfig().blockChatSpamRepetition.getValue() - && m.equalsIgnoreCase(msg) && i == 1) { - manager.getLoggingManager().logFineInfo(player.getName() + " spam-repeated \"" + msg + "\""); - return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING()); - } else if (manager.getConfiguration().getConfig().blockChatSpamSpeed.getValue() - && System.currentTimeMillis() - user.getLastCommandTime() < timeMin) { - manager.getLoggingManager().logFineInfo(player.getName() + " spammed quickly \"" + msg + "\""); - return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING()); - } - } - } - } - user.addMessage(msg); - return PASS; - } - - public CheckResult checkChatUnicode(Player player, String msg) { - UUID uuid = player.getUniqueId(); - User user = manager.getUserManager().getUser(uuid); - for (char ch : msg.toCharArray()) { - if (Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.BASIC_LATIN - && Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.LATIN_1_SUPPLEMENT - && Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.LATIN_EXTENDED_A - && Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.GENERAL_PUNCTUATION - && Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.CYRILLIC - && Character.UnicodeBlock.of(ch) != Character.UnicodeBlock.CYRILLIC_EXTENDED_A) { - return new CheckResult(CheckResult.Result.FAILED, "Unicode chat is not allowed."); - } - } - user.addMessage(msg); - return PASS; - } - - public CheckResult checkCommandSpam(Player player, String cmd) { - UUID uuid = player.getUniqueId(); - User user = manager.getUserManager().getUser(uuid); - if (user.getLastCommandTime() != -1) { - for (int i = 0; i < 2; i++) { - String m = user.getCommand(i); - if (m == null) { - break; - } - Long l = user.getCommandTime(i); - - int repeatIgnore = checksConfig.getInteger(CheckType.COMMAND_SPAM, "repeatIgnore"); - if (System.currentTimeMillis() - l > repeatIgnore) { - user.clearCommands(); - break; - } else { - int timeMin = checksConfig.getInteger(CheckType.COMMAND_SPAM, "timeMin"); - if (manager.getConfiguration().getConfig().blockCommandSpamRepetition.getValue() - && m.equalsIgnoreCase(cmd) && i == 1) { - return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING()); - } else if (manager.getConfiguration().getConfig().blockCommandSpamSpeed.getValue() - && System.currentTimeMillis() - user.getLastCommandTime() < timeMin) { - return new CheckResult(CheckResult.Result.FAILED, lang.SPAM_WARNING()); - } - } - } - } - user.addCommand(cmd); - return PASS; - } - - public CheckResult checkInventoryClicks(Player player) { - if (player.getGameMode() == GameMode.CREATIVE) { - return PASS; - } - UUID uuid = player.getUniqueId(); - int clicks = 1; - if (inventoryClicks.containsKey(uuid)) { - clicks = inventoryClicks.get(uuid) + 1; - } - inventoryClicks.put(uuid, clicks); - int clicksToWait = checksConfig.getInteger(CheckType.FAST_INVENTORY, "clicksToWait"); - if (clicks == 1) { - inventoryTime.put(uuid, System.currentTimeMillis()); - } else if (clicks == clicksToWait) { - int minimumTime = checksConfig.getInteger(CheckType.FAST_INVENTORY, "clicksToWait"); - long time = System.currentTimeMillis() - inventoryTime.get(uuid); - inventoryClicks.put(uuid, 0); - if (time < minimumTime) { - return new CheckResult(CheckResult.Result.FAILED, "clicked inventory slots " + clicks + " times in " - + time + " ms (max=" + clicksToWait + " in " + minimumTime + " ms)"); - } - } - return PASS; - } - - public CheckResult checkFastHeal(Player player) { - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - if (lastHeal.containsKey(player.getUniqueId())) // Otherwise it was modified by a plugin, don't worry about it. - { - double tps = AntiCheatReloaded.getPlugin().getTPS(); - if (tps < checksConfig.getDouble(CheckType.FAST_HEAL, "minimumTps") - || (user.isLagging() && checksConfig.getBoolean(CheckType.FAST_HEAL, "disableForLagging"))) { - return PASS; - } - long minHealTime = checksConfig.getInteger(CheckType.FAST_HEAL, "minHealTime"); - long lastHealTime = lastHeal.get(player.getUniqueId()); - int ping = user.getPing(); - double pingCompensation = checksConfig.getInteger(CheckType.FAST_HEAL, "pingCompensation"); - long allowedHealTime = (long) (minHealTime - (ping * pingCompensation)); - lastHeal.remove(player.getUniqueId()); - if ((System.currentTimeMillis() - lastHealTime) < allowedHealTime) { - return new CheckResult(CheckResult.Result.FAILED, "healed too quickly (time=" - + (System.currentTimeMillis() - lastHealTime) + " ms, min=" + allowedHealTime + " ms)"); - } - } - return PASS; - } - - public CheckResult checkFastEat(Player player) { - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - if (startEat.containsKey(player.getUniqueId())) // Otherwise it was modified by a plugin, don't worry about it. - { - if (AntiCheatReloaded.getPlugin().getTPS() < 17.5 || user.isLagging()) { - return PASS; - } - long l = startEat.get(player.getUniqueId()); - startEat.remove(player.getUniqueId()); - int eatTimeMin = checksConfig.getInteger(CheckType.FAST_EAT, "eatTimeMin"); - if ((System.currentTimeMillis() - l) < eatTimeMin) { - return new CheckResult(CheckResult.Result.FAILED, "ate too quickly (time=" - + (System.currentTimeMillis() - l) + " ms, min=" + eatTimeMin + " ms)"); - } - } - return PASS; - } - - public void logSprint(final Player player) { - sprinted.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public void logBlockBreak(final Player player) { - brokenBlock.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public boolean justBroke(Player player) { - // TODO config?? - return isDoing(player, brokenBlock, 0.1); - } - - public void logVelocity(final Player player) { - velocitized.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public void logLevitating(final Player player, final int duration) { - levitatingEnd.put(player.getUniqueId(), System.currentTimeMillis() + (duration * 1000L)); - } - - public boolean justVelocity(Player player) { - return (velocitized.containsKey(player.getUniqueId()) - ? (System.currentTimeMillis() - velocitized.get(player.getUniqueId())) < magic.VELOCITY_TIME() - : false); - } - - public boolean justLevitated(Player player) { - return (levitatingEnd.containsKey(player.getUniqueId()) - ? (System.currentTimeMillis() - levitatingEnd.get(player.getUniqueId())) < magic.VELOCITY_TIME() - : false); - } - - public boolean extendVelocityTime(final Player player) { - if (velocitytrack.containsKey(player.getUniqueId())) { - velocitytrack.put(player.getUniqueId(), velocitytrack.get(player.getUniqueId()) + 1); - if (velocitytrack.get(player.getUniqueId()) > magic.VELOCITY_MAXTIMES()) { - velocitized.put(player.getUniqueId(), System.currentTimeMillis() + magic.VELOCITY_PREVENT()); - manager.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(manager.getPlugin(), - new Runnable() { - @Override - public void run() { - velocitytrack.put(player.getUniqueId(), 0); - } - }, magic.VELOCITY_EXTENSION() * 20L); - return true; - } - } else { - velocitytrack.put(player.getUniqueId(), 0); - } - - return false; - } - - public void logBlockPlace(final Player player) { - placedBlock.put(player.getUniqueId(), System.currentTimeMillis()); - } - - public boolean justPlaced(Player player) { - // TODO config?? - return isDoing(player, placedBlock, 0.1); - } - - public void logDamage(final Player player, int type) { - long time; - switch (type) { - case 1: - time = magic.DAMAGE_TIME(); - break; - case 2: - time = magic.KNOCKBACK_DAMAGE_TIME(); - break; - case 3: - time = magic.EXPLOSION_DAMAGE_TIME(); - break; - default: - time = magic.DAMAGE_TIME(); - break; - - } - FlightCheck.MOVING_EXEMPT.put(player.getUniqueId(), System.currentTimeMillis() + time); - // Only map in which termination time is calculated beforehand. - } - - public void logEnterExit(final Player player) { - FlightCheck.MOVING_EXEMPT.put(player.getUniqueId(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME()); - } - - public void logTeleport(final Player player) { - manager.getUserManager().getUser(player.getUniqueId()).getMovementManager().lastTeleport = System - .currentTimeMillis(); - /* Data for fly/speed should be reset */ - nofallViolation.remove(player.getUniqueId()); - ElytraCheck.JUMP_Y_VALUE.remove(player.getUniqueId()); - } - - public void logBoatCollision(final Player player) { - // TODO config?? - FlightCheck.MOVING_EXEMPT.put(player.getUniqueId(), System.currentTimeMillis() + 100 /* 2 ticks */); - } - - public void logJoin(final Player player) { - FlightCheck.MOVING_EXEMPT.put(player.getUniqueId(), System.currentTimeMillis() + magic.JOIN_TIME()); - MorePacketsCheck.EXEMPT_TIMINGS.put(player.getUniqueId(), System.currentTimeMillis() + magic.JOIN_TIME()); - } - - public boolean isMovingExempt(Player player) { - return isDoing(player, FlightCheck.MOVING_EXEMPT, -1); - } - - public boolean isDoing(Player player, Map map, double max) { - if (map.containsKey(player.getUniqueId())) { - if (max != -1) { - if (((System.currentTimeMillis() - map.get(player.getUniqueId())) / 1000) > max) { - map.remove(player.getUniqueId()); - return false; - } else { - return true; - } - } else { - // Termination time has already been calculated - if (map.get(player.getUniqueId()) < System.currentTimeMillis()) { - map.remove(player.getUniqueId()); - return false; - } else { - return true; - } - } - } else { - return false; - } - } - - public boolean hasJumpPotion(Player player) { - return player.hasPotionEffect(PotionEffectType.JUMP); - } - - public boolean hasSpeedPotion(Player player) { - return player.hasPotionEffect(PotionEffectType.SPEED); - } - - public void processChatSpammer(Player player) { - User user = manager.getUserManager().getUser(player.getUniqueId()); - int level = chatLevel.containsKey(user.getUUID()) ? chatLevel.get(user.getUUID()) : 0; - int levelActionOne = checksConfig.getInteger(CheckType.CHAT_SPAM, "levelActionOne"); - int levelActionTwo = checksConfig.getInteger(CheckType.CHAT_SPAM, "levelActionTwo"); - if (player != null && player.isOnline() && level >= levelActionOne) { - String event = level >= levelActionTwo ? manager.getConfiguration().getConfig().chatSpamActionTwo.getValue() - : manager.getConfiguration().getConfig().chatSpamActionOne.getValue(); - manager.getUserManager().execute(manager.getUserManager().getUser(player.getUniqueId()), - Utilities.stringToList(event), CheckType.CHAT_SPAM, lang.SPAM_KICK_REASON(), - Utilities.stringToList(lang.SPAM_WARNING()), lang.SPAM_BAN_REASON()); - } - chatLevel.put(user.getUUID(), level + 1); - } - - public void processCommandSpammer(Player player) { - User user = manager.getUserManager().getUser(player.getUniqueId()); - int level = commandLevel.containsKey(user.getUUID()) ? commandLevel.get(user.getUUID()) : 0; - int levelActionOne = checksConfig.getInteger(CheckType.COMMAND_SPAM, "levelActionOne"); - int levelActionTwo = checksConfig.getInteger(CheckType.COMMAND_SPAM, "levelActionTwo"); - if (player != null && player.isOnline() && level >= levelActionOne) { - String event = level >= levelActionTwo - ? manager.getConfiguration().getConfig().commandSpamActionTwo.getValue() - : manager.getConfiguration().getConfig().commandSpamActionOne.getValue(); - manager.getUserManager().execute(manager.getUserManager().getUser(player.getUniqueId()), - Utilities.stringToList(event), CheckType.COMMAND_SPAM, lang.SPAM_KICK_REASON(), - Utilities.stringToList(lang.SPAM_WARNING()), lang.SPAM_BAN_REASON()); - } - commandLevel.put(user.getUUID(), level + 1); - } - - public int increment(Player player, Map map, int num) { - UUID name = player.getUniqueId(); - if (map.get(name) == null) { - map.put(name, 1); - return 1; - } else { - int amount = map.get(name) + 1; - if (amount < num + 1) { - map.put(name, amount); - return amount; - } else { - map.put(name, num); - return num; - } - } - } - - public int incrementOld(Player player, Map map, int num) { - UUID uuid = player.getUniqueId(); - if (map.get(uuid) == null) { - map.put(uuid, 1); - return 1; - } else { - int amount = map.get(uuid) + 1; - if (amount < num + 1) { - map.put(uuid, amount); - return amount; - } else { - map.put(uuid, num); - return num; - } - } - } - - public boolean silentMode() { - return manager.getConfiguration().getConfig().silentMode.getValue(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckResult.java b/src/main/java/com/rammelkast/anticheatreloaded/check/CheckResult.java deleted file mode 100644 index 7c8366a..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckResult.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.check; - -public class CheckResult { - - public enum Result { - PASSED, FAILED - } - - private Result result; - private String subCheck; - private String message; - private int data; - - public CheckResult(Result result, String message, int data) { - this(result, message); - this.data = data; - } - - public CheckResult(Result result, String subcheck, String message) { - this(result); - this.subCheck = subcheck; - this.message = message; - } - - public CheckResult(Result result, String message) { - this(result); - this.message = message; - } - - public CheckResult(Result result) { - this.result = result; - } - - public boolean failed() { - return result == Result.FAILED; - } - - public String getSubCheck() { - return subCheck; - } - - public String getMessage() { - return message; - } - - public Result getResult() { - return result; - } - - public int getData() { - return data; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java b/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java deleted file mode 100644 index 96fe8a0..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/CheckType.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.check; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.api.CheckFailEvent; -import com.rammelkast.anticheatreloaded.util.Permission; -import com.rammelkast.anticheatreloaded.util.User; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - *

- * All the types of checks and their corresponding permission nodes. - */ - -public enum CheckType { - FLIGHT(Permission.CHECK_FLIGHT, "Flight"), - ELYTRAFLY(Permission.CHECK_FLIGHT, "ElytraFly"), - WATER_WALK(Permission.CHECK_WATERWALK, "WaterWalk"), - FAST_PLACE(Permission.CHECK_FASTPLACE, "FastPlace"), - CHAT_SPAM(Permission.CHECK_CHATSPAM, "ChatSpam"), - COMMAND_SPAM(Permission.CHECK_COMMANDSPAM, "CommandSpam"), - SPRINT(Permission.CHECK_SPRINT, "Sprint"), - SNEAK(Permission.CHECK_SNEAK, "Sneak"), - SPEED(Permission.CHECK_SPEED, "Speed"), - VCLIP(Permission.CHECK_VCLIP, "vClip"), - SPIDER(Permission.CHECK_SPIDER, "Spider"), - NOFALL(Permission.CHECK_NOFALL, "NoFall"), - FAST_BOW(Permission.CHECK_FASTBOW, "FastBow"), - FAST_EAT(Permission.CHECK_FASTEAT, "FastEat"), - FAST_HEAL(Permission.CHECK_FASTHEAL, "FastHeal"), - KILLAURA(Permission.CHECK_KILLAURA, "KillAura"), - FAST_PROJECTILE(Permission.CHECK_FASTPROJECTILE, "FastProjectile"), - ITEM_SPAM(Permission.CHECK_ITEMSPAM, "ItemSpam"), - FAST_INVENTORY(Permission.CHECK_FASTINVENTORY, "FastInventory"), - MOREPACKETS(Permission.CHECK_MOREPACKETS, "MorePackets"), - BADPACKETS(Permission.CHECK_BADPACKETS, "BadPackets"), - VELOCITY(Permission.CHECK_VELOCITY, "Velocity"), - CRITICALS(Permission.CHECK_CRITICALS, "Criticals"), - CHAT_UNICODE(Permission.CHECK_UNICODE, "ChatUnicode"), - ILLEGAL_INTERACT(Permission.CHECK_ILLEGALINTERACT, "IllegalInteract"), - FASTLADDER(Permission.CHECK_FASTLADDER, "FastLadder"), - AIMBOT(Permission.CHECK_AIMBOT, "Aimbot"), - STRAFE(Permission.CHECK_STRAFE, "Strafe"), - NOSLOW(Permission.CHECK_NOSLOW, "NoSlow"), - BOATFLY(Permission.CHECK_BOATFLY, "BoatFly"); - - private final Permission permission; - private final String displayName; - private final Map level = new HashMap(); - - /** - * Initialize a CheckType - * - * @param permission Permission that applies to this check - * @peram displayName The chat display name - */ - private CheckType(Permission permission, String displayName) { - this.permission = permission; - this.displayName = displayName; - } - - /** - * Determine whether a player has permission to bypass this check - * - * @param player Player to check - * @return true if the player can bypass - */ - public boolean checkPermission(Player player) { - return permission.get(player); - } - - /** - * Log the failure of this check - * - * @param user User who failed the check - */ - public void logUse(User user) { - int amount = level.get(user.getUUID()) == null ? 1 : level.get(user.getUUID()) + 1; - level.put(user.getUUID(), amount); - Bukkit.getServer().getPluginManager().callEvent(new CheckFailEvent(user, this)); - } - - /** - * Clear failure history of this check for a user - * - * @param UUID User's UUID to clear - */ - public void clearUse(UUID uuid) { - level.put(uuid, 0); - } - - /** - * Get how many times a user has failed this check - * - * @param UUID User's UUID - * @return number of times failed - */ - public int getUses(UUID uuid) { - return level.get(uuid) != null ? level.get(uuid) : 0; - } - - /** - * Get the reference name of a check - * - * @return reference name - */ - public String getName() { - return this.displayName; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/CriticalsCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/combat/CriticalsCheck.java deleted file mode 100644 index e46ebc8..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/CriticalsCheck.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.combat; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.event.EventListener; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class CriticalsCheck { - - public static void doDamageEvent(EntityDamageByEntityEvent event, Player damager) { - if (!(event.getDamager() instanceof Player) || event.getCause() != DamageCause.ENTITY_ATTACK) - return; - Player player = (Player) event.getDamager(); - if (isCritical(player)) { - if ((player.getLocation().getY() % 1.0 == 0 || player.getLocation().getY() % 0.5 == 0) - && player.getLocation().clone().subtract(0, 1.0, 0).getBlock().getType().isSolid()) { - event.setCancelled(true); - EventListener.log(new CheckResult(CheckResult.Result.FAILED, "tried to do a critical without needed conditions") - .getMessage(), - player, CheckType.CRITICALS, null); - } - } - } - - @SuppressWarnings("deprecation") - private static boolean isCritical(Player player) { - return player.getFallDistance() > 0.0f && !player.isOnGround() && !player.isInsideVehicle() - && !player.hasPotionEffect(PotionEffectType.BLINDNESS) - && !Utilities.isHoveringOverWater(player.getLocation()) - && player.getEyeLocation().getBlock().getType() != Material.LADDER; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/KillAuraCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/combat/KillAuraCheck.java deleted file mode 100644 index fb151e7..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/KillAuraCheck.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.combat; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.util.Vector; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class KillAuraCheck { - - // Angle check - public static final Map ANGLE_FLAGS = new HashMap(); - // PacketOrder check - public static final Map PACKETORDER_FLAGS = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult checkReach(Player player, Entity target) { - if (!(target instanceof LivingEntity)) - return PASS; - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - - // Check if enabled - if (!checksConfig.isSubcheckEnabled(CheckType.KILLAURA, "reach")) - return PASS; - - double allowedReach = target.getVelocity().length() < 0.08 - ? checksConfig.getDouble(CheckType.KILLAURA, "reach", "baseMaxValue.normal") - : checksConfig.getDouble(CheckType.KILLAURA, "reach", "baseMaxValue.velocitized"); - if (player.getGameMode() == GameMode.CREATIVE) - allowedReach += 1.5D; - // Lag compensation - double lagExtraReach = checksConfig.getDouble(CheckType.KILLAURA, "reach", "lagCompensation.lagExtraReach"); - double pingCompensation = checksConfig.getDouble(CheckType.KILLAURA, "reach", - "lagCompensation.pingCompensation"); - allowedReach += user.getPing() * pingCompensation; - if (user.isLagging()) - allowedReach += lagExtraReach; - if (target instanceof Player) { - User targetUser = AntiCheatReloaded.getManager().getUserManager().getUser(target.getUniqueId()); - allowedReach += targetUser.getPing() * pingCompensation; - if (targetUser.isLagging()) - allowedReach += lagExtraReach; - } - // Velocity compensation - double velocityMultiplier = checksConfig.getDouble(CheckType.KILLAURA, "reach", "velocityMultiplier"); - allowedReach += Math.abs(target.getVelocity().length()) * velocityMultiplier; - double reachedDistance = ((LivingEntity) target).getLocation().toVector() - .distance(player.getLocation().toVector()); - if (reachedDistance > allowedReach) - return new CheckResult(CheckResult.Result.FAILED, "Reach", - "reached too far (distance=" + Utilities.roundDouble(reachedDistance, 6) + ", max=" + Utilities.roundDouble(allowedReach, 6) + ")"); - return PASS; - } - - public static CheckResult checkAngle(Player player, EntityDamageEvent event) { - UUID uuid = player.getUniqueId(); - Entity entity = event.getEntity(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - - // Check if enabled - if (!checksConfig.isSubcheckEnabled(CheckType.KILLAURA, "angle")) - return PASS; - - if (entity instanceof LivingEntity) { - LivingEntity living = (LivingEntity) entity; - Location eyeLocation = player.getEyeLocation(); - - double yawDifference = calculateYawDifference(eyeLocation, living.getLocation()); - double playerYaw = player.getEyeLocation().getYaw(); - - double angleDifference = Math.abs(180 - Math.abs(Math.abs(yawDifference - playerYaw) - 180)); - int maxDifference = checksConfig.getInteger(CheckType.KILLAURA, "angle", "maxDifference"); - if (Math.round(angleDifference) > maxDifference) { - if (!ANGLE_FLAGS.containsKey(uuid)) { - ANGLE_FLAGS.put(uuid, 1); - return PASS; - } - - int flags = ANGLE_FLAGS.get(uuid); - int vlBeforeFlag = checksConfig.getInteger(CheckType.KILLAURA, "angle", "vlBeforeFlag"); - if (flags >= vlBeforeFlag) { - ANGLE_FLAGS.remove(uuid); - return new CheckResult(CheckResult.Result.FAILED, "Angle", - "tried to attack from an illegal angle (angle=" + Math.round(angleDifference) + ")"); - } - - ANGLE_FLAGS.put(uuid, flags + 1); - } - } - - return PASS; - } - - public static CheckResult checkPacketOrder(Player player, Entity entity) { - UUID uuid = player.getUniqueId(); - User user = AntiCheatReloaded.getManager().getUserManager().getUser(uuid); - MovementManager movementManager = user.getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - - // Check if enabled - if (!checksConfig.isSubcheckEnabled(CheckType.KILLAURA, "packetOrder")) - return PASS; - - if (user.isLagging() || (System.currentTimeMillis() - movementManager.lastTeleport) <= 100 - || AntiCheatReloaded.getPlugin().getTPS() < checksConfig.getDouble(CheckType.KILLAURA, "packetOrder", "minimumTps")) - return PASS; - - long elapsed = System.currentTimeMillis() - movementManager.lastUpdate; - if (elapsed < checksConfig.getInteger(CheckType.KILLAURA, "packetOrder", "minElapsedTime")) { - if (!PACKETORDER_FLAGS.containsKey(uuid)) { - PACKETORDER_FLAGS.put(uuid, 1); - return PASS; - } - - int flags = PACKETORDER_FLAGS.get(uuid); - int vlBeforeFlag = checksConfig.getInteger(CheckType.KILLAURA, "packetOrder", "vlBeforeFlag"); - if (flags >= vlBeforeFlag) { - PACKETORDER_FLAGS.remove(uuid); - return new CheckResult(Result.FAILED, "PacketOrder", "suspicious packet order (elapsed=" + elapsed + ")"); - } - - PACKETORDER_FLAGS.put(uuid, flags + 1); - } - return PASS; - } - - public static double calculateYawDifference(Location from, Location to) { - Location clonedFrom = from.clone(); - Vector startVector = clonedFrom.toVector(); - Vector targetVector = to.toVector(); - clonedFrom.setDirection(targetVector.subtract(startVector)); - return clonedFrom.getYaw(); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/VelocityCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/combat/VelocityCheck.java deleted file mode 100644 index 9ebcdef..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/combat/VelocityCheck.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.combat; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class VelocityCheck { - - public static final Map VIOLATIONS = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, Distance distance) { - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - MovementManager movementManager = user.getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - final int minimumPercentage = checksConfig.getInteger(CheckType.VELOCITY, "minimumPercentage"); - final int vlBeforeFlag = checksConfig.getInteger(CheckType.VELOCITY, "vlBeforeFlag"); - - if (movementManager.velocityExpectedMotionY > 0 && !movementManager.onGround) { - double percentage = (movementManager.motionY / movementManager.velocityExpectedMotionY) * 100; - if (percentage < 0) - percentage = 0; - // Reset expected Y motion - movementManager.velocityExpectedMotionY = 0; - if (percentage < minimumPercentage) { - int vl = VIOLATIONS.getOrDefault(player.getUniqueId(), 0) + 1; - VIOLATIONS.put(player.getUniqueId(), vl); - if (vl >= vlBeforeFlag) - return new CheckResult(Result.FAILED, "ignored server velocity (pct=" + Utilities.roundDouble(percentage, 2) + ")"); - } else { - VIOLATIONS.remove(player.getUniqueId()); - } - } else if (movementManager.airTicks > 5 && movementManager.velocityExpectedMotionY > 0) - movementManager.velocityExpectedMotionY = 0; - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/AimbotCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/AimbotCheck.java deleted file mode 100644 index e9392cf..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/AimbotCheck.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerMoveEvent; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; - -public class AimbotCheck { - - public static final Map LAST_DELTA_YAW = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, PlayerMoveEvent event) { - Backend backend = AntiCheatReloaded.getManager().getBackend(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - if (backend.isMovingExempt(player)) { - return PASS; - } - - UUID uuid = player.getUniqueId(); - float dYaw = Math.abs(event.getTo().getYaw() - event.getFrom().getYaw()); - float dPitch = Math.abs(event.getTo().getPitch() - event.getFrom().getPitch()); - // Not interesting - if (dYaw < 0.05 && dPitch < 0.05) { - return PASS; - } - - final float lastDeltaYaw = LAST_DELTA_YAW.getOrDefault(uuid, -1F); - if (lastDeltaYaw == -1F) { - LAST_DELTA_YAW.put(uuid, dYaw); - return PASS; - } - LAST_DELTA_YAW.put(uuid, dYaw); - - float absoluteYawDifference = Math.abs(dYaw - lastDeltaYaw); - int minYaw = checksConfig.getInteger(CheckType.AIMBOT, "minYaw"); - int maxYaw = checksConfig.getInteger(CheckType.AIMBOT, "maxYaw"); - if (absoluteYawDifference < 1E-8 && minYaw > 30 && dYaw < maxYaw) - return new CheckResult(CheckResult.Result.FAILED, "repeated yaw difference (dYaw=" + dYaw + ")"); - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/BoatFlyCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/BoatFlyCheck.java deleted file mode 100644 index bd62e02..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/BoatFlyCheck.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class BoatFlyCheck { - - public static final Map VIOLATIONS = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, MovementManager movementManager, Location to) { - if (movementManager.distanceXZ <= 0 || movementManager.motionY <= 1E-3 - || (System.currentTimeMillis() - movementManager.lastTeleport <= 50) || VersionUtil.isFlying(player) - || !player.isInsideVehicle()) - return PASS; - - UUID uuid = player.getUniqueId(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - if (player.getVehicle().getType() == EntityType.BOAT) { - Block bottom = player.getWorld().getBlockAt(to.getBlockX(), to.getBlockY() - 1, to.getBlockZ()); - if (!Utilities.cantStandAt(bottom)) - return PASS; - int violations = VIOLATIONS.getOrDefault(uuid, 1); - if (violations++ >= checksConfig.getInteger(CheckType.BOATFLY, "vlBeforeFlag")) { - violations = 0; - return new CheckResult(Result.FAILED, "tried to fly in a boat (mY=" + movementManager.motionY - + ", bottom=" + bottom.getType().name().toLowerCase() + ")"); - } - VIOLATIONS.put(uuid, violations); - } - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java deleted file mode 100644 index 92a0da4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/ElytraCheck.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class ElytraCheck { - - public static final HashMap JUMP_Y_VALUE = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, Distance distance) { - // No elytra in server version or not relevant - if (VersionUtil.isBountifulUpdate() || Utilities.isNearWater(player)) - return PASS; - - UUID uuid = player.getUniqueId(); - if (distance.getYDifference() > AntiCheatReloaded.getManager().getBackend().getMagic().TELEPORT_MIN()) { - // This was a teleport, so skip check. - JUMP_Y_VALUE.remove(uuid); - return PASS; - } - - if (player.isFlying() || player.hasPotionEffect(PotionEffectType.LEVITATION) || !player.isGliding()) { - JUMP_Y_VALUE.remove(uuid); - return PASS; - } - - double changeY = distance.toY() - distance.fromY(); - boolean upwardMovement = changeY > 0; - if (player.getInventory().getItemInMainHand().getType() == Material.TRIDENT) { - if (upwardMovement) { - // TODO continue check here - JUMP_Y_VALUE.remove(uuid); - return PASS; - } - } - - if (changeY == 0.0D) { - // Seen no false positives here yet - return new CheckResult(CheckResult.Result.FAILED, "had no Y-axis dropoff when gliding with Elytra"); - } - - if (!JUMP_Y_VALUE.containsKey(uuid)) { - JUMP_Y_VALUE.put(uuid, distance.toY()); - return PASS; - } - double lastY = JUMP_Y_VALUE.get(uuid); - if (lastY < distance.toY()) { - double diff = distance.toY() - lastY; - if (diff > 0.7675) { - if (!AntiCheatReloaded.getManager().getBackend().silentMode()) { - Location to = player.getLocation(); - to.setY(to.getY() - diff); - player.teleport(to); - } - return new CheckResult(CheckResult.Result.FAILED, "tried to glide above jump level"); - } - } - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FastLadderCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FastLadderCheck.java deleted file mode 100644 index f88cddc..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FastLadderCheck.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class FastLadderCheck { - - public static final Map VIOLATIONS = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, double y) { - // Only check if fully on ladder - // Liquids are climbable blocks, so we have to add a seperate check - if (!Utilities.isClimbableBlock(player.getLocation().getBlock()) - || !Utilities.isClimbableBlock(player.getEyeLocation().getBlock()) - || player.getLocation().getBlock().isLiquid()) { - return PASS; - } - - int vlCount = VIOLATIONS.getOrDefault(player.getUniqueId(), 0); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - int vlBeforeFlag = checksConfig.getInteger(CheckType.FASTLADDER, "vlBeforeFlag"); - if (y > 0) { - // Check moving up - double max = checksConfig.getDouble(CheckType.FASTLADDER, "speedUpMax"); - // Check if going faster than max Y climbing speed - if (y - max > 0) { - if (vlCount++ > vlBeforeFlag) { - vlCount = 0; - return new CheckResult(Result.FAILED, - "tried to climb up too fast (speed=" + y + ", max=" + max + ")"); - } - } else { - if (vlCount > 0) - vlCount--; - } - } else if (y < 0) { - // Check moving down - double max = checksConfig.getDouble(CheckType.FASTLADDER, "speedDownMax"); - if (Math.abs(y) > max + 6E-9) { - if (vlCount++ > vlBeforeFlag) { - vlCount = 0; - return new CheckResult(Result.FAILED, "tried to climb down too fast (speed=" + Math.abs(y) - + ", max=" + max + ")"); - } - } else { - if (vlCount > 0) - vlCount--; - } - } else { - if (vlCount > 0) - vlCount--; - } - - VIOLATIONS.put(player.getUniqueId(), vlCount); - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java deleted file mode 100644 index 5d84db4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/FlightCheck.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -/** - * @author Rammelkast - */ -public class FlightCheck { - - public static final Map MOVING_EXEMPT = new HashMap(); - public static final Map GRAVITY_VIOLATIONS = new HashMap(); - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - private static final double GRAVITY_FRICTION = 0.9800000190734863D; - - public static CheckResult runCheck(Player player, Distance distance) { - if (distance.getYDifference() >= AntiCheatReloaded.getManager().getBackend().getMagic().TELEPORT_MIN() - || VersionUtil.isFlying(player) || player.getVehicle() != null - || AntiCheatReloaded.getManager().getBackend().isMovingExempt(player)) { - // This was a teleport or user is flying/using elytra/in a vehicle, so we don't - // care - // about it. - return PASS; - } - - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - MovementManager movementManager = user.getMovementManager(); - Backend backend = AntiCheatReloaded.getManager().getBackend(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - - if (movementManager.nearLiquidTicks > 0 || movementManager.halfMovement || Utilities.isNearClimbable(player)) - return PASS; - - int minAirTicks = 13; - if (player.hasPotionEffect(PotionEffectType.JUMP)) - minAirTicks += VersionUtil.getPotionLevel(player, PotionEffectType.JUMP) * 3; - - if (movementManager.halfMovementHistoryCounter > 25) - minAirTicks += 5; - - // Start AirFlight - if (checksConfig.isSubcheckEnabled(CheckType.FLIGHT, "airFlight") && movementManager.airTicks > minAirTicks - && !backend.justVelocity(player) && movementManager.elytraEffectTicks <= 25) { - // Config default base is 1200ms - // Ping clamped to max. 1000 to prevent spoofing for an advantage - int blockPlaceAccountingTime = (int) (checksConfig.getInteger(CheckType.FLIGHT, "airFlight", - "accountForBlockPlacement") + (0.25 * (user.getPing() > 1000 ? 1000 : user.getPing()))); - // Config default account is 250ms - if (AntiCheatReloaded.getPlugin().getTPS() < 18.0) - blockPlaceAccountingTime += checksConfig.getInteger(CheckType.FLIGHT, "airFlight", - "accountForTpsDrops"); - long lastPlacedBlock = AntiCheatReloaded.getManager().getBackend().placedBlock - .containsKey(player.getUniqueId()) - ? AntiCheatReloaded.getManager().getBackend().placedBlock.get(player.getUniqueId()) - : (blockPlaceAccountingTime + 1); - double maxMotionY = System.currentTimeMillis() - lastPlacedBlock > blockPlaceAccountingTime ? 0 : 0.42; - // Fixes snow false positive - if (movementManager.motionY < 0.004 && Utilities - .isNearHalfblock(distance.getFrom().getBlock().getRelative(BlockFace.DOWN).getLocation())) - maxMotionY = 0.004D; - if (movementManager.motionY > maxMotionY && movementManager.slimeInfluenceTicks <= 0 - && !Utilities.isNearClimbable(distance.getTo().clone().subtract(0, 1.25, 0))) - return new CheckResult(CheckResult.Result.FAILED, "AirFlight", - "tried to fly on the Y-axis (mY=" + movementManager.motionY + ", max=" + maxMotionY + ")"); - - if (Math.abs(movementManager.motionY - movementManager.lastMotionY) < 0.01 - && !Utilities.couldBeOnBoat(player) - && (System.currentTimeMillis() - movementManager.lastTeleport >= checksConfig - .getInteger(CheckType.FLIGHT, "airFlight", "accountForTeleports")) - && !VersionUtil.isSlowFalling(player) && !Utilities.isNearWeb(player) - && movementManager.elytraEffectTicks <= 25) - return new CheckResult(CheckResult.Result.FAILED, "AirFlight", "had too little Y dropoff (diff=" - + Math.abs(movementManager.motionY - movementManager.lastMotionY) + ")"); - } - // End AirFlight - - // Start AirClimb - // TODO three hardcoded values here shouldn't be there, temp against false - // positive - if (checksConfig.isSubcheckEnabled(CheckType.FLIGHT, "airClimb") && movementManager.lastMotionY > 0 - && movementManager.motionY > 0 && movementManager.airTicks == 2 - && Math.round(movementManager.lastMotionY * 1000) != 420 - && Math.round(movementManager.motionY * 1000) != 248 - && !(Math.round(movementManager.motionY * 1000) == 333 - && Math.round(movementManager.lastMotionY * 1000) != 333) - && !AntiCheatReloaded.getManager().getBackend().justVelocity(player) - && !player.hasPotionEffect(PotionEffectType.JUMP) - && (System.currentTimeMillis() - movementManager.lastTeleport >= checksConfig - .getInteger(CheckType.FLIGHT, "airClimb", "accountForTeleports")) - && (!Utilities.isNearBed(distance.getTo()) - || (Utilities.isNearBed(distance.getTo()) && movementManager.motionY > 0.12675)) - && movementManager.slimeInfluenceTicks == 0 && movementManager.elytraEffectTicks <= 25) - return new CheckResult(CheckResult.Result.FAILED, "AirClimb", - "tried to climb air (mY=" + movementManager.motionY + ")"); - - // TODO hardcoded value against false again.. - if (checksConfig.isSubcheckEnabled(CheckType.FLIGHT, "airClimb") && movementManager.motionY > 0.42 - && movementManager.airTicks > 2 && !AntiCheatReloaded.getManager().getBackend().justVelocity(player) - && !player.hasPotionEffect(PotionEffectType.JUMP) - && !(Math.round(movementManager.motionY * 1000) == 425 && movementManager.airTicks == 11) - && (System.currentTimeMillis() - movementManager.lastTeleport >= checksConfig - .getInteger(CheckType.FLIGHT, "airClimb", "accountForTeleports")) - && movementManager.slimeInfluenceTicks == 0 && movementManager.elytraEffectTicks <= 25) { - return new CheckResult(CheckResult.Result.FAILED, "AirClimb", - "tried to climb air (mY=" + movementManager.motionY + ", at=" + movementManager.airTicks + ")"); - } - // End AirClimb - - // Start GroundFlight - if (checksConfig.isSubcheckEnabled(CheckType.FLIGHT, "groundFlight") && movementManager.onGround - && Utilities.cantStandAt(distance.getTo().getBlock().getRelative(BlockFace.DOWN)) - && Utilities.cantStandAt(distance.getFrom().getBlock().getRelative(BlockFace.DOWN)) - && Utilities.cantStandAt(distance.getTo().getBlock())) { - return new CheckResult(CheckResult.Result.FAILED, "GroundFlight", - "faked ground to fly (mY=" + movementManager.motionY + ", gt=" + movementManager.groundTicks + ")"); - } - // End GroundFlight - - // Start Gravity - if (checksConfig.isSubcheckEnabled(CheckType.FLIGHT, "gravity") && !movementManager.onGround - && movementManager.motionY < 0 && !backend.justVelocity(player) - && (System.currentTimeMillis() - movementManager.lastTeleport >= checksConfig - .getInteger(CheckType.FLIGHT, "gravity", "accountForTeleports")) - && !Utilities.isNearWeb(player) && movementManager.elytraEffectTicks <= 25 - && !VersionUtil.isSlowFalling(player)) { - double gravitatedY = (movementManager.lastMotionY - 0.08) * GRAVITY_FRICTION; - double offset = Math.abs(gravitatedY - movementManager.motionY); - double maxOffset = checksConfig.getDouble(CheckType.FLIGHT, "gravity", "maxOffset"); - if (offset > maxOffset && movementManager.airTicks > 2) { - int vl = GRAVITY_VIOLATIONS.getOrDefault(player.getUniqueId(), 0) + 1; - GRAVITY_VIOLATIONS.put(player.getUniqueId(), vl); - int vlBeforeFlag = checksConfig.getInteger(CheckType.FLIGHT, "gravity", "vlBeforeFlag"); - if (vl >= vlBeforeFlag) - return new CheckResult(CheckResult.Result.FAILED, "Gravity", - "ignored gravity (offset=" + offset + ", at=" + movementManager.airTicks + ")"); - } else { - GRAVITY_VIOLATIONS.remove(player.getUniqueId()); - } - } - // End Gravity - - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/NoSlowCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/NoSlowCheck.java deleted file mode 100644 index a9fe51a..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/NoSlowCheck.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.entity.Player; - -import com.comphenix.protocol.events.PacketEvent; -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.event.EventListener; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; - -public class NoSlowCheck { - - public static final Map LAST_RELEASE = new HashMap(); - public static final Map VIOLATIONS = new HashMap(); - - public static void runCheck(Player player, PacketEvent event) { - if (!AntiCheatReloaded.getManager().getCheckManager().willCheck(player, CheckType.NOSLOW)) - return; - UUID uuid = player.getUniqueId(); - User user = AntiCheatReloaded.getManager().getUserManager().getUser(uuid); - MovementManager movementManager = user.getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - final long time = System.currentTimeMillis(); - final long lastRelease = LAST_RELEASE.getOrDefault(uuid, 0L); - LAST_RELEASE.put(uuid, time); - if (lastRelease == 0L) - return; - - long difference = time - lastRelease; - long minimumDifference = checksConfig.getInteger(CheckType.NOSLOW, "minimumDifference"); - if (difference < minimumDifference - && movementManager.distanceXZ >= checksConfig.getDouble(CheckType.NOSLOW, "minimumDistXZ")) { - int violations = VIOLATIONS.getOrDefault(uuid, 1); - if (violations++ >= checksConfig.getInteger(CheckType.NOSLOW, "vlBeforeFlag")) { - violations = 0; - flag(player, event, - "toggled use item too fast (diff=" + difference + ", min=" + minimumDifference + ")"); - } - VIOLATIONS.put(uuid, violations); - } - } - - private static void flag(Player player, PacketEvent event, String message) { - event.setCancelled(true); - // We are currently not in the main server thread, so switch - AntiCheatReloaded.sendToMainThread(new Runnable() { - @Override - public void run() { - EventListener.log(new CheckResult(CheckResult.Result.FAILED, message).getMessage(), player, - CheckType.NOSLOW, null); - player.teleport(player.getLocation()); - } - }); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/SpeedCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/SpeedCheck.java deleted file mode 100644 index 1970c63..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/SpeedCheck.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -/** - * @author Rammelkast TODO soulsand speed - */ -public class SpeedCheck { - - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static boolean isSpeedExempt(Player player, Backend backend) { - return backend.isMovingExempt(player) || backend.justVelocity(player) || VersionUtil.isFlying(player); - } - - public static CheckResult checkXZSpeed(Player player, double x, double z, Location movingTowards) { - Backend backend = AntiCheatReloaded.getManager().getBackend(); - if (isSpeedExempt(player, backend) || player.getVehicle() != null || Utilities.isInWater(player)) - return PASS; - - MovementManager movementManager = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()) - .getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double distanceXZ = movementManager.distanceXZ; - boolean boxedIn = movementManager.topSolid && movementManager.bottomSolid; - - // AirSpeed - if (checksConfig.isSubcheckEnabled(CheckType.SPEED, "airSpeed") && movementManager.airTicks > 1 - && movementManager.elytraEffectTicks <= 0 && !Utilities.isNearClimbable(player)) { - double multiplier = 0.985D; - double predict = 0.36 * Math.pow(multiplier, movementManager.airTicks + 1); - double limit = checksConfig.getDouble(CheckType.SPEED, "airSpeed", "baseLimit"); // Default 0.03125 - // Adjust for ice - if (movementManager.iceInfluenceTicks > 0) { - double iceIncrement = 0.025 * Math.pow(1.038, movementManager.iceInfluenceTicks); - // Clamp to max value - if (iceIncrement > 0.18D) - iceIncrement = 0.18D; - if (boxedIn) - iceIncrement += 0.45D; - if (!Utilities.couldBeOnIce(movingTowards)) - iceIncrement *= 2.5D; - predict += iceIncrement; - } - // Leniency when boxed in - if (boxedIn && movementManager.airTicks < 3) - predict *= 1.2D; - // Adjust for slime - if (movementManager.slimeInfluenceTicks > 0) { - double slimeIncrement = 0.022 * Math.pow(1.0375, movementManager.slimeInfluenceTicks); - // Clamp to max value - if (slimeIncrement > 0.12D) - slimeIncrement = 0.12D; - predict += slimeIncrement; - } - // Adjust for speed effects - if (movementManager.hasSpeedEffect) - predict += VersionUtil.getPotionLevel(player, PotionEffectType.SPEED) * 0.05D; - if (movementManager.hadSpeedEffect && !movementManager.hasSpeedEffect) - limit *= 1.2D; - // Adjust for jump boost effects - if (player.hasPotionEffect(PotionEffectType.JUMP)) - predict += VersionUtil.getPotionLevel(player, PotionEffectType.JUMP) * 0.05D; - // Adjust for custom walking speed - double walkSpeedMultiplier = checksConfig.getDouble(CheckType.SPEED, "airSpeed", "walkSpeedMultiplier"); // Default - // 1.4 - predict += walkSpeedMultiplier * (Math.pow(1.1, ((player.getWalkSpeed() / 0.20) - 1)) - 1); - // Slabs sometimes allow for a slight boost after jump - if (movementManager.halfMovementHistoryCounter > 0) - predict *= 2.125D; - if (Utilities.couldBeOnHalfblock(movingTowards) && movementManager.halfMovementHistoryCounter == 0) - predict *= 1.25D; - // Boats sometimes give a false positive - if (Utilities.couldBeOnBoat(player, 0.5, true)) - predict *= 1.25D; - // Strafing in air when nearing terminal velocity gives false positives - // This fixes the issue but gives hackers some leniency which means we need - // another check for this - double deltaMotionY = movementManager.motionY - movementManager.lastMotionY; - if ((deltaMotionY < 0 && deltaMotionY >= -0.08) || movementManager.airTicks >= 40 - && (movingTowards.getBlockY() - player.getWorld().getHighestBlockYAt(movingTowards)) <= 1.5) - predict *= (movementManager.airTicks > 60 ? 4.0D : (movementManager.airTicks > 30 ? 3.0D : 2.0D)); - // Players can move faster in air with slow falling - if (VersionUtil.isSlowFalling(player)) - predict *= 1.25D; - // Prevent NoSlow - if (movementManager.blockingTicks > 3 && movementManager.airTicks > 2) - predict *= 0.8D; - if (movementManager.blockingTicks > 10 && movementManager.airTicks > 2) - predict *= 0.5D; - // Fixes false positive when coming out of water - if (movementManager.nearLiquidTicks >= 7 && movementManager.airTicks >= 14 - && movementManager.motionY < -0.18 && movementManager.motionY > -0.182) - predict += Math.abs(movementManager.motionY); - - if (distanceXZ - predict > limit) { - return new CheckResult(CheckResult.Result.FAILED, "AirSpeed", - "moved too fast in air (speed=" + distanceXZ + ", limit=" + predict + ", block=" - + movementManager.blockingTicks + ", box=" + boxedIn + ", at=" - + movementManager.airTicks + ")"); - } - } - - // AirAcceleration - // As of right now, this falses sometimes, dont know why - if (checksConfig.isSubcheckEnabled(CheckType.SPEED, "airAcceleration") && movementManager.airTicks > 1 - && movementManager.iceInfluenceTicks <= 0 && movementManager.slimeInfluenceTicks <= 0 - && movementManager.elytraEffectTicks <= 0) { - double initialAcceleration = movementManager.acceleration; - double limit = checksConfig.getDouble(CheckType.SPEED, "airAcceleration", "baseLimit"); // Default 0.3725 - // Slight increase when boxed in - if (boxedIn) - limit *= 1.08D; - // Adjust for speed effects - if (player.hasPotionEffect(PotionEffectType.SPEED)) - limit += VersionUtil.getPotionLevel(player, PotionEffectType.SPEED) * 0.0225D; - // Adjust for slabs - if (movementManager.halfMovementHistoryCounter > 15) - limit *= 2.0D; - // Adjust for custom walking speed - double walkSpeedMultiplier = checksConfig.getDouble(CheckType.SPEED, "airAcceleration", - "walkSpeedMultiplier"); // Default 1.4 - limit += walkSpeedMultiplier * (Math.pow(1.1, ((player.getWalkSpeed() / 0.20) - 1)) - 1); - // Boats sometimes give a false positive - if (Utilities.couldBeOnBoat(player)) - limit *= 1.25D; - if (initialAcceleration > limit) { - return new CheckResult(CheckResult.Result.FAILED, "AirAcceleration", - "exceeded acceleration limits (acceleration=" + initialAcceleration + ", max=" + limit + ")"); - } - } - - // JumpBehaviour - // Works against YPorts and mini jumps - if (checksConfig.isSubcheckEnabled(CheckType.SPEED, "jumpBehaviour") && movementManager.touchedGroundThisTick - && !boxedIn && movementManager.slimeInfluenceTicks <= 10) { - // This happens naturally - if (movementManager.airTicksBeforeGrounded == movementManager.groundTicks) { - double minimumDistXZ = checksConfig.getDouble(CheckType.SPEED, "jumpBehaviour", "minimumDistXZ"); // Default - - if (distanceXZ >= minimumDistXZ || movementManager.lastDistanceXZ >= minimumDistXZ) { - return new CheckResult(CheckResult.Result.FAILED, "JumpBehaviour", - "had unexpected jumping behaviour (dXZ=" + Utilities.roundDouble(distanceXZ, 4) + ", lXZ=" - + Utilities.roundDouble(movementManager.lastDistanceXZ, 4) + ")"); - } - } - } - - // GroundSpeed - if (checksConfig.isSubcheckEnabled(CheckType.SPEED, "groundSpeed") && movementManager.groundTicks > 1) { - double initialLimit = checksConfig.getDouble(CheckType.SPEED, "groundSpeed", "initialLimit"); // Default - // 0.34 - double limit = initialLimit - 0.0055 * Math.min(9, movementManager.groundTicks); - // Leniency when moving back on ground - if (movementManager.groundTicks < 5) - limit += 0.1D; - // Slab leniency - if (movementManager.halfMovementHistoryCounter > 8) - limit += 0.2D; - // LivingEntities can give players a small push boost - if (!movingTowards.getWorld().getNearbyEntities(movingTowards, 0.3, 0.3, 0.3).isEmpty()) - limit += 0.2D; - // Leniency when boxed in - if (boxedIn) - limit *= 1.1D; - // Adjust for speed effects - if (movementManager.hasSpeedEffect) - limit += VersionUtil.getPotionLevel(player, PotionEffectType.SPEED) * 0.06D; - if (movementManager.hasSpeedEffect && movementManager.groundTicks > 3) - limit *= 1.4D; - if (movementManager.hadSpeedEffect && !movementManager.hasSpeedEffect) - limit *= 1.2D; - if (movementManager.iceInfluenceTicks >= 50) { - // When moving off ice - if (!Utilities.couldBeOnIce(movingTowards)) - limit *= 2.5D; - else { - // When boxed in and spamming space for boost - if (movementManager.topSolid && movementManager.bottomSolid) - limit *= 3.0D; - else - limit *= 1.25D; - } - } - // Increased speed when stepping on/off half blocks - if (Utilities.isNearBed(movingTowards) || Utilities.couldBeOnHalfblock(movingTowards) - || Utilities.isNearBed(movingTowards.clone().add(0, -0.5, 0))) - limit *= 2.0D; - // Increased speed when stepping on/off boat - if (Utilities.couldBeOnBoat(player)) - limit += 0.2D; - // Adjust for custom walk speed - limit += (player.getWalkSpeed() - 0.2) * 2.0D; - // Prevent NoSlow - if (player.isBlocking() && movementManager.groundTicks > 2) - limit *= 0.45D; - // Prevent NoWeb - // TODO config - if (Utilities.isInWeb(player)) - limit *= 0.65D; - // Sneak speed check - // TODO config - if (movementManager.sneakingTicks > 1) - limit *= 0.68D; - - if (distanceXZ - limit > 0) { - return new CheckResult(CheckResult.Result.FAILED, "GroundSpeed", - "moved too fast on ground (speed=" + distanceXZ + ", limit=" + limit + ", blocking=" - + player.isBlocking() + ", gt=" + movementManager.groundTicks + ")"); - } - } - - return PASS; - } - - public static CheckResult checkVerticalSpeed(Player player, Distance distance) { - Backend backend = AntiCheatReloaded.getManager().getBackend(); - if (isSpeedExempt(player, backend) || player.getVehicle() != null || player.isSleeping() - || VersionUtil.isRiptiding(player) || Utilities.isNearWater(player)) - return PASS; - MovementManager movementManager = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()) - .getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - if (!checksConfig.isSubcheckEnabled(CheckType.SPEED, "verticalSpeed")) - return PASS; - - double maxMotionY = getMaxAcceptableMotionY(player, Utilities.isNearBed(distance.getTo()), - Utilities.couldBeOnBoat(player), - Utilities.isClimbableBlock(distance.getFrom().getBlock()) - || Utilities.isClimbableBlock(distance.getFrom().getBlock().getRelative(BlockFace.DOWN)), - movementManager.halfMovement, checksConfig); - // Fix false positive with soulsand boost - if (movementManager.nearLiquidTicks > 6) - maxMotionY *= 1.0525D; - if (movementManager.motionY > maxMotionY && movementManager.slimeInfluenceTicks <= 0) { - return new CheckResult(CheckResult.Result.FAILED, "VerticalSpeed", - "exceeded vertical speed limit (mY=" + movementManager.motionY + ", max=" + maxMotionY + ")"); - } - return PASS; - } - - private static double getMaxAcceptableMotionY(Player player, boolean nearBed, boolean couldBeOnBoat, - boolean fromClimbable, boolean halfMovement, Checks checksConfig) { - // TODO config for these values - // TODO something funky vanilla stuff going on with 0.42, like 0.445.., check - // this.. - double base = couldBeOnBoat ? 0.600000025 - : (nearBed ? 0.5625 : ((halfMovement || VersionUtil.isBountifulUpdate()) ? 0.6 : 0.42)); - if (fromClimbable) - base += checksConfig.getDouble(CheckType.SPEED, "verticalSpeed", "climbableCompensation"); // Default 0.04 - - if (player.hasPotionEffect(PotionEffectType.JUMP)) - base += VersionUtil.getPotionLevel(player, PotionEffectType.JUMP) * 0.2D; - return base; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/StrafeCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/StrafeCheck.java deleted file mode 100644 index 3bf2229..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/StrafeCheck.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -/** - * - * @author Rammelkast - * - */ -public class StrafeCheck { - - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, double x, double z, Location from, Location to) { - if (!Utilities.cantStandAtExp(from) || !Utilities.cantStandAtExp(to) || Utilities.isNearWater(player) - || Utilities.isNearClimbable(player) || VersionUtil.isFlying(player) || player.isDead() - || Utilities.isHalfblock(to.getBlock().getRelative(BlockFace.DOWN))) - return PASS; - - MovementManager movementManager = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()) - .getMovementManager(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - - if (System.currentTimeMillis() - movementManager.lastTeleport <= checksConfig.getInteger(CheckType.STRAFE, - "accountForTeleports") || movementManager.elytraEffectTicks >= 20 - || movementManager.halfMovementHistoryCounter >= 20) - return PASS; - - Vector oldAcceleration = new Vector(movementManager.lastDistanceX, 0, movementManager.lastDistanceZ); - Vector newAcceleration = new Vector(x, 0, z); - - float angle = newAcceleration.angle(oldAcceleration); - double distance = newAcceleration.lengthSquared(); - if (angle > checksConfig.getDouble(CheckType.STRAFE, "maxAngleChange") - && distance > checksConfig.getDouble(CheckType.STRAFE, "minActivationDistance") - && Utilities.cantStandFar(to.getBlock())) - return new CheckResult(Result.FAILED, "switched angle in air (angle=" + angle + ", dist=" + distance + ")"); - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/WaterWalkCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/movement/WaterWalkCheck.java deleted file mode 100644 index f21b5cc..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/movement/WaterWalkCheck.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.movement; - -import java.util.UUID; - -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckResult.Result; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class WaterWalkCheck { - - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult runCheck(Player player, double x, double y, double z) { - UUID uuid = player.getUniqueId(); - User user = AntiCheatReloaded.getManager().getUserManager().getUser(uuid); - MovementManager movementManager = user.getMovementManager(); - - if (movementManager.distanceXZ <= 0 || player.getVehicle() != null || Utilities.isOnLilyPad(player) - || VersionUtil.isRiptiding(player) || VersionUtil.isSwimming(player) || VersionUtil.isFlying(player)) - return PASS; - - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - Block blockBeneath = player.getLocation().clone().subtract(0, 0.1, 0).getBlock(); - if (checksConfig.isSubcheckEnabled(CheckType.WATER_WALK, "walk") && blockBeneath.isLiquid() - && Utilities.isSurroundedByWater(player) - && ((movementManager.motionY == 0 && movementManager.lastMotionY == 0) - || movementManager.motionY == Utilities.JUMP_MOTION_Y) - && movementManager.distanceXZ > checksConfig.getDouble(CheckType.WATER_WALK, "walk", "minimumDistXZ") - && !movementManager.topSolid && !Utilities.couldBeOnBoat(player, 3, false)) - return new CheckResult(Result.FAILED, "Walk", - "tried to walk on water (xz=" + Utilities.roundDouble(movementManager.distanceXZ, 5) + ")"); - - if (checksConfig.isSubcheckEnabled(CheckType.WATER_WALK, "hop") && blockBeneath.isLiquid() - && Utilities.isSurroundedByWater(player) && movementManager.onGround - && Math.abs(movementManager.motionY) < checksConfig.getDouble(CheckType.WATER_WALK, "hop", "maxMotionY") - && !Utilities.couldBeOnBoat(player, 0.3, false)) - return new CheckResult(Result.FAILED, "Hop", - "tried to hop on water (mY=" + Utilities.roundDouble(movementManager.motionY, 5) + ")"); - - double minAbsMotionY = 0.12D; - if (player.hasPotionEffect(PotionEffectType.SPEED)) - minAbsMotionY += VersionUtil.getPotionLevel(player, PotionEffectType.SPEED) * 0.05D; - if (checksConfig.isSubcheckEnabled(CheckType.WATER_WALK, "lunge") && blockBeneath.isLiquid() - && Utilities.isSurroundedByWater(player) - && Math.abs(movementManager.lastMotionY - movementManager.motionY) > minAbsMotionY - && movementManager.distanceXZ > checksConfig.getDouble(CheckType.WATER_WALK, "lunge", "minimumDistXZ") - && movementManager.lastMotionY > -0.25 - && !Utilities.couldBeOnBoat(player, 0.3, false)) - return new CheckResult(Result.FAILED, "Lunge", "tried to lunge in water (xz=" - + Utilities.roundDouble(movementManager.distanceXZ, 5) + ", absMotionY=" - + Utilities.roundDouble(Math.abs(movementManager.lastMotionY - movementManager.motionY), 5) + ")"); - - return PASS; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/packet/BadPacketsCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/packet/BadPacketsCheck.java deleted file mode 100644 index e4479ff..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/packet/BadPacketsCheck.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.packet; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.events.PacketEvent; -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.event.EventListener; -import com.rammelkast.anticheatreloaded.util.MovementManager; -import com.rammelkast.anticheatreloaded.util.User; - -public class BadPacketsCheck { - - public static void runCheck(Player player, PacketEvent event) { - Backend backend = AntiCheatReloaded.getManager().getBackend(); - // Confirm if we should even check for BadPackets - if (!AntiCheatReloaded.getManager().getCheckManager().willCheck(player, CheckType.BADPACKETS) - || backend.isMovingExempt(player) || player.isDead()) - return; - - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - PacketContainer packet = event.getPacket(); - float pitch = packet.getFloat().read(1); - // Check for derp - if (Math.abs(pitch) > 90) { - flag(player, event, "had an illegal pitch"); - return; - } - - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double tps = AntiCheatReloaded.getPlugin().getTPS(); - MovementManager movementManager = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()) - .getMovementManager(); - if (user.isLagging() || tps < checksConfig.getDouble(CheckType.MOREPACKETS, "minimumTps") - || (System.currentTimeMillis() - movementManager.lastTeleport <= 150)) - return; - - double x = packet.getDoubles().read(0); - double y = packet.getDoubles().read(1); - double z = packet.getDoubles().read(2); - float yaw = packet.getFloat().read(0); - // Create location from new data - Location previous = player.getLocation(); - Location current = new Location(previous.getWorld(), x, y, z, yaw, pitch); - double distance = previous.distanceSquared(current); - double maxDistance = checksConfig.getDouble(CheckType.BADPACKETS, "maxDistance"); - // Fix falling false - if (movementManager.airTicks >= 40 && movementManager.motionY < 0 && movementManager.lastMotionY < 0) - maxDistance *= 1.5D; - boolean hasNewLocation = packet.getBooleans().read(0); - if (distance > maxDistance) { - flag(player, event, "moved too far between packets (distance=" - + new BigDecimal(distance).setScale(1, RoundingMode.HALF_UP) + ", max=" + maxDistance + ", at=" + movementManager.airTicks + ")"); - return; - } else if (distance < 1E-10 && !hasNewLocation) { - // TODO this gives false positives when teleporting - // Only found this in 1.8.8 though - // flag(player, event, "sent the same packet twice"); - return; - } - } - - private static void flag(Player player, PacketEvent event, String message) { - event.setCancelled(true); - // We are currently not in the main server thread, so switch - AntiCheatReloaded.sendToMainThread(new Runnable() { - @Override - public void run() { - EventListener.log(new CheckResult(CheckResult.Result.FAILED, message).getMessage(), player, - CheckType.BADPACKETS, null); - player.teleport(player.getLocation()); - } - }); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/packet/MorePacketsCheck.java b/src/main/java/com/rammelkast/anticheatreloaded/check/packet/MorePacketsCheck.java deleted file mode 100644 index a0feeda..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/packet/MorePacketsCheck.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.check.packet; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.entity.Player; - -import com.comphenix.protocol.events.PacketEvent; -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.event.EventListener; -import com.rammelkast.anticheatreloaded.util.User; - -/** - * @author Rammelkast - */ -public class MorePacketsCheck { - - public static final Map LAST_PACKET_TIME = new HashMap(); - public static final Map EXEMPT_TIMINGS = new HashMap(); - public static final Map PACKET_BALANCE = new HashMap(); - - public static void runCheck(Player player, PacketEvent event) { - // Confirm if we should even check for MorePackets - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double tps = AntiCheatReloaded.getPlugin().getTPS(); - if (!AntiCheatReloaded.getManager().getCheckManager().willCheck(player, CheckType.MOREPACKETS) - || tps < checksConfig.getDouble(CheckType.MOREPACKETS, "minimumTps")) { - return; - } - - UUID uuid = player.getUniqueId(); - User user = AntiCheatReloaded.getManager().getUserManager().getUser(uuid); - int maxPing = checksConfig.getInteger(CheckType.MOREPACKETS, "maxPing"); - boolean disableForLagging = checksConfig.getBoolean(CheckType.MOREPACKETS, "disableForLagging"); - if (AntiCheatReloaded.getManager().getBackend().isDoing(player, EXEMPT_TIMINGS, -1) - || (maxPing > 0 && user.getPing() > maxPing) || (disableForLagging && user.isLagging())) { - return; - } - long packetTimeNow = System.currentTimeMillis(); - long lastPacketTime = LAST_PACKET_TIME.getOrDefault(uuid, packetTimeNow - 50L); - double packetBalance = PACKET_BALANCE.getOrDefault(uuid, 0D); - - long rate = packetTimeNow - lastPacketTime; - packetBalance += 50; - packetBalance -= rate; - int triggerBalance = checksConfig.getInteger(CheckType.MOREPACKETS, "triggerBalance"); - int minimumClamp = checksConfig.getInteger(CheckType.MOREPACKETS, "minimumClamp"); - if (packetBalance >= triggerBalance) { - int ticks = (int) Math.round(packetBalance / 50); - packetBalance = -1 * (triggerBalance / 2); - flag(player, event, "overshot timer by " + ticks + " tick(s)"); - } else if (packetBalance < -1 * minimumClamp) { - // Clamp minimum, 50ms=1tick of lag leniency - packetBalance = -1 * minimumClamp; - } - - LAST_PACKET_TIME.put(uuid, packetTimeNow); - PACKET_BALANCE.put(uuid, packetBalance); - } - - private static void flag(Player player, PacketEvent event, String message) { - event.setCancelled(true); - // We are currently not in the main server thread, so switch - AntiCheatReloaded.sendToMainThread(new Runnable() { - @Override - public void run() { - EventListener.log(new CheckResult(CheckResult.Result.FAILED, message).getMessage(), player, - CheckType.MOREPACKETS, null); - player.teleport(player.getLocation()); - } - }); - } - - public static void compensate(Player player) { - UUID uuid = player.getUniqueId(); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double packetBalance = PACKET_BALANCE.getOrDefault(uuid, 0D); - PACKET_BALANCE.put(uuid, packetBalance - checksConfig.getInteger(CheckType.MOREPACKETS, "teleportCompensation")); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/check/player/IllegalInteract.java b/src/main/java/com/rammelkast/anticheatreloaded/check/player/IllegalInteract.java deleted file mode 100644 index 6b709af..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/check/player/IllegalInteract.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.check.player; - -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.PlayerInteractEvent; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class IllegalInteract { - - private static final CheckResult PASS = new CheckResult(CheckResult.Result.PASSED); - - public static CheckResult performCheck(Player player, Event event) { - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - if (event instanceof BlockPlaceEvent && checksConfig.isSubcheckEnabled(CheckType.ILLEGAL_INTERACT, "place")) { - return checkBlockPlace(player, (BlockPlaceEvent) event); - } else if (event instanceof BlockBreakEvent - && checksConfig.isSubcheckEnabled(CheckType.ILLEGAL_INTERACT, "break")) { - return checkBlockBreak(player, (BlockBreakEvent) event); - } else if (event instanceof PlayerInteractEvent - && checksConfig.isSubcheckEnabled(CheckType.ILLEGAL_INTERACT, "interact")) { - return checkInteract(player, (PlayerInteractEvent) event); - } - return PASS; - } - - private static CheckResult checkInteract(Player player, PlayerInteractEvent event) { - User user = AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()); - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double distance = player.getEyeLocation().toVector().distance(event.getClickedBlock().getLocation().toVector()); - double maxDistance = player.getGameMode() == GameMode.CREATIVE - ? checksConfig.getDouble(CheckType.ILLEGAL_INTERACT, "interact", "creativeRange") - : checksConfig.getDouble(CheckType.ILLEGAL_INTERACT, "interact", "survivalRange"); - - maxDistance += user.isLagging() ? 0.12 : 0; - maxDistance += user.getPing() - * checksConfig.getInteger(CheckType.ILLEGAL_INTERACT, "interact", "pingCompensation"); - maxDistance += player.getVelocity().length() - * checksConfig.getDouble(CheckType.ILLEGAL_INTERACT, "interact", "velocityMultiplier"); - if (distance > maxDistance) { - return new CheckResult(CheckResult.Result.FAILED, "Interact", - "tried to interact out of range (dist=" + distance + ", max=" + maxDistance + ")"); - } - return PASS; - } - - private static CheckResult checkBlockBreak(Player player, BlockBreakEvent event) { - if (!isValidTarget(player, event.getBlock())) { - return new CheckResult(CheckResult.Result.FAILED, "Break", "tried to break a block which was out of view"); - } - return PASS; - } - - private static CheckResult checkBlockPlace(Player player, BlockPlaceEvent event) { - if (!isValidTarget(player, event.getBlock())) { - return new CheckResult(CheckResult.Result.FAILED, "Place", "tried to place a block out of their view"); - } - return PASS; - } - - private static boolean isValidTarget(Player player, Block block) { - Checks checksConfig = AntiCheatReloaded.getManager().getConfiguration().getChecks(); - double distance = player.getGameMode() == GameMode.CREATIVE ? 6.0 - : player.getLocation().getDirection().getY() > 0.9 ? 6.0 : 5.5; - Block targetBlock = VersionUtil.getTargetBlock(player, ((int) Math.ceil(distance))); - if (targetBlock == null) { - // TODO better check here - return true; - } - - if (Utilities.isClimbableBlock(targetBlock)) { - if (targetBlock.getLocation().distance(player.getLocation()) <= distance) { - return true; - } - } - - if (targetBlock.equals(block)) { - return true; - } - - Location eyeLocation = player.getEyeLocation(); - double yawDifference = KillAuraCheck.calculateYawDifference(eyeLocation, block.getLocation()); - double playerYaw = player.getEyeLocation().getYaw(); - double angleDifference = Math.abs(180 - Math.abs(Math.abs(yawDifference - playerYaw) - 180)); - if (Math.round(angleDifference) > checksConfig.getInteger(CheckType.ILLEGAL_INTERACT, "maxAngleDifference")) { - return false; - } - return true; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/CommandBase.java b/src/main/java/com/rammelkast/anticheatreloaded/command/CommandBase.java deleted file mode 100644 index f9692c7..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/CommandBase.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.manage.CheckManager; -import com.rammelkast.anticheatreloaded.manage.UserManager; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandBase { - - public static final Configuration CONFIG = AntiCheatReloaded.getManager().getConfiguration(); - public static final UserManager USER_MANAGER = AntiCheatReloaded.getManager().getUserManager(); - public static final CheckManager CHECK_MANAGER = AntiCheatReloaded.getManager().getCheckManager(); - public static final ChatColor RED = ChatColor.RED; - public static final ChatColor YELLOW = ChatColor.YELLOW; - public static final ChatColor GREEN = ChatColor.GREEN; - public static final ChatColor WHITE = ChatColor.WHITE; - public static final ChatColor GRAY = ChatColor.GRAY; - public static final ChatColor GOLD = ChatColor.GOLD; - public static final ChatColor AQUA = ChatColor.AQUA; - public static final Server SERVER = Bukkit.getServer(); - public static final String PERMISSIONS_ERROR = RED + "You don't have the permissions to use this command."; - public static final String MENU_END = GOLD + "-----------------------------------------------------"; - - private final String name; - private final String command; - private final String usage; - private final String[] help; - private final Permission permission; - - public CommandBase(String name, String command, String usage, String help[], Permission permission) { - this.name = name; - this.command = command; - this.usage = usage; - this.help = help; - this.permission = permission; - } - - public void run(CommandSender cs, String[] args) { - if (permission.get(cs)) { - execute(cs, args); - } else { - if (args == null) { - cs.sendMessage(GRAY + "Running " + GOLD + "" + "AntiCheatReloaded " + GRAY + "version " + AntiCheatReloaded.getVersion()); - } else { - cs.sendMessage(PERMISSIONS_ERROR + " (" + WHITE + permission.toString() + RED + ")"); - } - } - } - - protected void execute(CommandSender cs, String[] args) { - return; // Stub - } - - public void sendHelp(CommandSender cs) { - cs.sendMessage(GOLD + "" + ChatColor.BOLD + "AntiCheatReloaded " + ChatColor.GRAY + "Help Menu"); - cs.sendMessage(GOLD + "Usage: " + GRAY + (cs instanceof Player ? "/" : "") + getUsage()); - cs.sendMessage(GOLD + "Permission: " + GRAY + getPermission().toString()); - for (String string : getHelp()) { - cs.sendMessage(string); - } - } - - public String getName() { - return name; - } - - public String getCommand() { - return command; - } - - public String getUsage() { - return usage; - } - - public String[] getHelp() { - return help; - } - - public Permission getPermission() { - return permission; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/CommandHandler.java b/src/main/java/com/rammelkast/anticheatreloaded/command/CommandHandler.java deleted file mode 100644 index 45e7a6f..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/CommandHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command; - -import java.util.ArrayList; -import java.util.List; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.command.executors.CommandChecks; -import com.rammelkast.anticheatreloaded.command.executors.CommandHelp; -import com.rammelkast.anticheatreloaded.command.executors.CommandLog; -import com.rammelkast.anticheatreloaded.command.executors.CommandMute; -import com.rammelkast.anticheatreloaded.command.executors.CommandReload; -import com.rammelkast.anticheatreloaded.command.executors.CommandReport; -import com.rammelkast.anticheatreloaded.command.executors.CommandReset; -import com.rammelkast.anticheatreloaded.command.executors.CommandVersion; - -public class CommandHandler implements CommandExecutor { - - private List commands = new ArrayList(); - - public CommandHandler() { - commands.add(new CommandHelp()); - commands.add(new CommandChecks()); - commands.add(new CommandLog()); - commands.add(new CommandReload()); - commands.add(new CommandReport()); - commands.add(new CommandMute()); - commands.add(new CommandReset()); - commands.add(new CommandVersion()); - } - - @Override - public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) { - if (args.length >= 1) { - String command = args[0]; - // Shift args down - String[] newArgs = new String[args.length-1]; - for (int i=1;i. - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.manage.CheckManager; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandChecks extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Checks Management"; - private static final String COMMAND = "checks"; - private static final String USAGE = "anticheat checks"; - private static final Permission PERMISSION = Permission.SYSTEM_CHECK; - private static final String[] HELP = new String[2]; - - static { - HELP[0] = GRAY + "Use: " + AQUA + "/anticheat checks" + GRAY + " for a list of checks"; - StringBuilder builder = new StringBuilder(); - CheckManager checkManager = AntiCheatReloaded.getManager().getCheckManager(); - builder.append(GRAY + "Checks: "); - for (int i = 0; i < CheckType.values().length; i++) { - CheckType type = CheckType.values()[i]; - builder.append((checkManager.isActive(type) ? ChatColor.GREEN : ChatColor.RED) + type.getName()); - if (i < CheckType.values().length - 1) { - builder.append(", "); - } - } - HELP[1] = builder.toString(); - } - - public CommandChecks() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - sendHelp(cs); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandHelp.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandHelp.java deleted file mode 100644 index b1ff3f2..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandHelp.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandHelp extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Help"; - private static final String COMMAND = "help"; - private static final String USAGE = "anticheat help"; - private static final Permission PERMISSION = Permission.SYSTEM_HELP; - private static final String[] HELP = { - GOLD + "/acr " + GRAY + "help", - GOLD + "/acr " + GRAY + "reload", - GOLD + "/acr " + GRAY + "version", - GOLD + "/acr " + GRAY + "mute", - GOLD + "/acr " + GRAY + "checks", - GOLD + "/acr " + GRAY + "log " + WHITE + "[file/console] [on/off]", - GOLD + "/acr " + GRAY + "report " + WHITE + "[group/user]", - GOLD + "/acr " + GRAY + "reset " + WHITE + "[user]", - }; - - public CommandHelp() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - sendHelp(cs); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandLog.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandLog.java deleted file mode 100644 index 93368be..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandLog.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandLog extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Logging"; - private static final String COMMAND = "log"; - private static final String USAGE = "anticheat log [file/console] [on/off]"; - private static final Permission PERMISSION = Permission.SYSTEM_LOG; - private static final String[] HELP = { - GRAY + "Use: " + AQUA + "/anticheat log console on" + GRAY + " to enable console logging", - GRAY + "Use: " + AQUA + "/anticheat log file off" + GRAY + " to disable file logging", - }; - - public CommandLog() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - if (args.length == 2) { - ConfigurationFile.ConfigValue value; - String name; - if (args[0].equalsIgnoreCase("file")) { - value = CONFIG.getConfig().logToFile; - name = "File logging"; - } else if (args[0].equalsIgnoreCase("console")) { - value = CONFIG.getConfig().logToConsole; - name = "Console logging"; - } else { - sendHelp(cs); - return; - } - - boolean newValue; - if (args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("enable")) { - newValue = true; - } else if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("disable")) { - newValue = false; - } else { - sendHelp(cs); - return; - } - - String strValue = (newValue ? " enabled" : " disabled"); - if (value.getValue() == newValue) { - cs.sendMessage(GREEN + name + " is already " + strValue + "!"); - } else { - value.setValue(newValue); - cs.sendMessage(GREEN + name + strValue + "."); - CONFIG.getConfig().reload(); - } - } else { - sendHelp(cs); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandMute.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandMute.java deleted file mode 100644 index 1676b68..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandMute.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.command.executors; - -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandMute extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Mute"; - private static final String COMMAND = "mute"; - private static final String USAGE = "anticheat mute"; - private static final Permission PERMISSION = Permission.SYSTEM_MUTE; - private static final String[] HELP = { - GRAY + "Use: " + AQUA + "/anticheat mute" + GRAY + " to mute all notifications", }; - - public CommandMute() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - if (!(cs instanceof Player)) { - cs.sendMessage(ChatColor.BOLD + "" + GOLD + "ACR " + GRAY + "This command is only for players"); - return; - } - UUID uuid = ((Player) cs).getUniqueId(); - if (AntiCheatReloaded.MUTE_ENABLED_MODS.contains(uuid)) { - cs.sendMessage(GOLD + "" + ChatColor.BOLD + "ACR " + GRAY + "Player alerts have been unmuted"); - AntiCheatReloaded.MUTE_ENABLED_MODS.remove(uuid); - return; - } else { - cs.sendMessage(GOLD + "" + ChatColor.BOLD + "ACR " + GRAY + "Player alerts have been muted"); - AntiCheatReloaded.MUTE_ENABLED_MODS.add(uuid); - return; - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReload.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReload.java deleted file mode 100644 index 989abb1..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReload.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Permission; - -public class CommandReload extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Reload"; - private static final String COMMAND = "reload"; - private static final String USAGE = "anticheat reload"; - private static final Permission PERMISSION = Permission.SYSTEM_RELOAD; - private static final String[] HELP = { - GRAY + "Use: " + AQUA + "/anticheat reload" + GRAY + " to reload AntiCheat settings", - }; - - public CommandReload() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - CONFIG.load(); - cs.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.DARK_GRAY + "> " + ChatColor.GRAY + "The configuration was reloaded"); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReport.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReport.java deleted file mode 100644 index 99f0271..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReport.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.command.executors; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Group; -import com.rammelkast.anticheatreloaded.util.Permission; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class CommandReport extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Reports"; - private static final String COMMAND = "report"; - private static final String USAGE = "anticheat report [group/user]"; - private static final Permission PERMISSION = Permission.SYSTEM_REPORT; - private static final String[] HELP = { - GRAY + "Use: " + GOLD + "/anticheat report [group]" + GRAY + " to see all users in a given group", - GRAY + "Use: " + GOLD + "/anticheat report [user]" + GRAY + " to see a single user's report", - GRAY + "Use: " + GOLD + "/anticheat report [user/group] [num]" + GRAY + " to see pages of a report", }; - - public CommandReport() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - if (args.length >= 1) { - int page = 1; - if (args.length == 2) { - if (Utilities.isInt(args[1])) { - page = Integer.parseInt(args[1]); - } else { - cs.sendMessage(RED + "Not a valid page number: " + WHITE + args[1]); - } - } - - if ("low".equalsIgnoreCase(args[0])) { - groupReport(cs, null, page); - } else if ("all".equalsIgnoreCase(args[0])) { - cs.sendMessage(GREEN + "Low: " + WHITE + USER_MANAGER.getUsersInGroup(null).size() + " players"); - for (Group g : CONFIG.getGroups().getGroups()) { - int numPlayers = USER_MANAGER.getUsersInGroup(g).size(); - cs.sendMessage(g.getColor() + g.getName() + WHITE + ": " + numPlayers + " players"); - } - cs.sendMessage(GRAY + "Use " + GOLD + "/anticheat report [group]" + GRAY - + " for a list of players in each group."); - } else { - // Test groups - for (Group group : CONFIG.getGroups().getGroups()) { - if (group.getName().equalsIgnoreCase(args[0]) || "low".equalsIgnoreCase(args[0]) - || "all".equalsIgnoreCase(args[0])) { - groupReport(cs, group, page); - return; - } - } - - @SuppressWarnings("deprecation") - OfflinePlayer targetPlayer = Bukkit.getOfflinePlayer(args[0]); - if (targetPlayer == null) { - cs.sendMessage(RED + "Not a valid group or user: " + WHITE + args[0]); - return; - } - - User user = AntiCheatReloaded.getManager().getUserManager().getUser(targetPlayer.getUniqueId()); - if (user != null) { - playerReport(cs, user, page); - return; - } - - cs.sendMessage(RED + "Not a valid group or user: " + WHITE + args[0]); - } - } else { - sendHelp(cs); - } - } - - private void groupReport(CommandSender cs, Group group, int page) { - List users = USER_MANAGER.getUsersInGroup(group); - ChatColor color = group == null ? GREEN : group.getColor(); - String groupName = group == null ? "Low" : group.getName(); - int pages = (int) Math.ceil(((float) users.size()) / 7); - if (page <= pages && page > 0) { - cs.sendMessage(GOLD + "----------------------[" + GRAY + "Page " + page + "/" + pages + "" + GOLD - + "]----------------------"); - cs.sendMessage(GRAY + "Group: " + color + groupName); - for (int x = 0; x < 7; x++) { - int index = ((page - 1) * 6) + (x + ((page - 1) * 1)); - if (index < users.size()) { - String player = users.get(index).getName(); - cs.sendMessage(GRAY + player); - } - } - cs.sendMessage(MENU_END); - } else { - if (pages == 0) { - cs.sendMessage(GOLD + "----------------------[" + GRAY + "Page 1/1" + GOLD + "]----------------------"); - cs.sendMessage(GRAY + "Group: " + color + groupName); - cs.sendMessage(GRAY + "There are no users in this group."); - cs.sendMessage(MENU_END); - } else { - cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages); - } - } - } - - private void playerReport(CommandSender cs, User user, int page) { - List types = new ArrayList(); - for (CheckType type : CheckType.values()) { - if (type.getUses(user.getUUID()) > 0) { - types.add(type); - } - } - - UUID uuid = user.getUUID(); - String name = user.getName(); - int pages = (int) Math.ceil(((float) types.size()) / 6); - - Group group = user.getGroup(); - String groupString = GREEN + "Low"; - - if (group != null) { - groupString = group.getColor() + group.getName(); - } - groupString += " (" + user.getLevel() + ")"; - - if (page <= pages && page > 0) { - cs.sendMessage(GOLD + "----------------------[" + GRAY + "Page " + page + "/" + pages + "" + GOLD - + "]----------------------"); - cs.sendMessage(GRAY + "Player: " + WHITE + name); - int ping = user.getPing(); - cs.sendMessage(GRAY + "Ping: " + ((ping == -1) ? (RED + "Offline") - : (WHITE + "" + ping + "ms " - + (user.isLagging() ? ChatColor.RED + "(lagging)" : ChatColor.GREEN + "(not lagging)")))); - cs.sendMessage(GRAY + "Group: " + groupString); - for (int x = 0; x < 6; x++) { - int index = ((page - 1) * 5) + (x + ((page - 1))); - if (index < types.size()) { - CheckType type = types.get(index); - int use = type.getUses(uuid); - ChatColor color = WHITE; - if (use >= 20) { - color = YELLOW; - } else if (use > 50) { - color = RED; - } - cs.sendMessage(GRAY + type.getName() + ": " + color + use); - } - } - cs.sendMessage(MENU_END); - } else { - if (pages == 0 && page == 1) { - cs.sendMessage(GOLD + "----------------------[" + GRAY + "Page 1/1" + GOLD + "]----------------------"); - cs.sendMessage(GRAY + "Player: " + WHITE + name); - int ping = user.getPing(); - cs.sendMessage(GRAY + "Ping: " + ((ping == -1) ? (RED + "Offline") - : (WHITE + "" + ping + "ms " - + (user.isLagging() ? ChatColor.RED + "(lagging)" : ChatColor.GREEN + "(not lagging)")))); - cs.sendMessage(GRAY + "Group: " + groupString); - cs.sendMessage(GRAY + "This user has not failed any checks."); - cs.sendMessage(MENU_END); - } else { - cs.sendMessage(RED + "Page not found. Requested " + WHITE + page + RED + ", Max " + WHITE + pages + 1); - } - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReset.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReset.java deleted file mode 100644 index bb3ed5f..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandReset.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Permission; -import com.rammelkast.anticheatreloaded.util.User; - -public class CommandReset extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Resetting"; - private static final String COMMAND = "reset"; - private static final String USAGE = "anticheat reset [user]"; - private static final Permission PERMISSION = Permission.SYSTEM_RESET; - private static final String[] HELP = { - GRAY + "Use: " + AQUA + "/anticheat reset [user]" + GRAY + " to reset this user's hack level", - }; - - public CommandReset() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @SuppressWarnings("deprecation") - @Override - protected void execute(CommandSender cs, String[] args) { - User user; - if (args.length == 1) { - if (Bukkit.getPlayer(args[0]) != null) { - user = USER_MANAGER.getUser(Bukkit.getPlayer(args[0]).getUniqueId()); - } else { - user = USER_MANAGER.getUser(Bukkit.getOfflinePlayer(args[0]).getUniqueId()); - } - if (user != null) { - user.resetLevel(); - user.clearMessages(); - AntiCheatReloaded.getManager().getBackend().resetChatLevel(user); - cs.sendMessage(GOLD + args[0] + GRAY + " has been reset."); - } else { - cs.sendMessage(RED + "Player: " +args[0] + " not found."); - } - } else { - sendHelp(cs); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandVersion.java b/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandVersion.java deleted file mode 100644 index bf130b2..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/command/executors/CommandVersion.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.command.executors; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.command.CommandBase; -import com.rammelkast.anticheatreloaded.util.Permission; -import com.rammelkast.anticheatreloaded.util.UpdateManager; - -public class CommandVersion extends CommandBase { - - private static final String NAME = "AntiCheatReloaded Version"; - private static final String COMMAND = "version"; - private static final String USAGE = "anticheat version"; - private static final Permission PERMISSION = Permission.SYSTEM_VERSION; - private static final String[] HELP = { - GRAY + "Use: " + AQUA + "/anticheat version" + GRAY + " to get update information", }; - - public CommandVersion() { - super(NAME, COMMAND, USAGE, HELP, PERMISSION); - } - - @Override - protected void execute(CommandSender cs, String[] args) { - UpdateManager updateManager = AntiCheatReloaded.getUpdateManager(); - String status = RED + "behind"; - if (updateManager.isLatest()) { - if (updateManager.isAhead()) { - status = GREEN + "ahead"; - } else { - status = GOLD + "up-to-date"; - } - } - cs.sendMessage(GOLD + "" + ChatColor.BOLD + "ACR " + GRAY + "You are running version " + GOLD - + updateManager.getCurrentVersion() + GRAY + ". The latest version is " + GOLD - + updateManager.getLatestVersion() + GRAY + ". This means you are " + status + GRAY + "."); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/Configuration.java b/src/main/java/com/rammelkast/anticheatreloaded/config/Configuration.java deleted file mode 100644 index aa62fc4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/Configuration.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config; - -import java.io.File; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.ArrayList; - -import org.bukkit.configuration.file.YamlConfiguration; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.files.Config; -import com.rammelkast.anticheatreloaded.config.files.Enterprise; -import com.rammelkast.anticheatreloaded.config.holders.mysql.MySQLGroupsHolder; -import com.rammelkast.anticheatreloaded.config.holders.mysql.MySQLLangHolder; -import com.rammelkast.anticheatreloaded.config.holders.mysql.MySQLLevelsHolder; -import com.rammelkast.anticheatreloaded.config.holders.mysql.MySQLMagicHolder; -import com.rammelkast.anticheatreloaded.config.holders.mysql.MySQLRulesHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlChecksHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlGroupsHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlLangHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlLevelsHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlMagicHolder; -import com.rammelkast.anticheatreloaded.config.holders.yaml.YamlRulesHolder; -import com.rammelkast.anticheatreloaded.config.providers.Checks; -import com.rammelkast.anticheatreloaded.config.providers.Groups; -import com.rammelkast.anticheatreloaded.config.providers.Lang; -import com.rammelkast.anticheatreloaded.config.providers.Levels; -import com.rammelkast.anticheatreloaded.config.providers.Magic; -import com.rammelkast.anticheatreloaded.config.providers.Rules; -import com.rammelkast.anticheatreloaded.manage.AntiCheatManager; - -public class Configuration { - - private AntiCheatManager manager; - private Config config; - private Enterprise enterprise; - - private Lang lang; - private Magic magic; - private Groups groups; - private Levels levels; - private Rules rules; - private Checks checks; - - private ArrayList flatfiles; - private ArrayList dbfiles; - - public Configuration(AntiCheatReloaded plugin, AntiCheatManager manager) { - removeOldFiles(); - this.manager = manager; - config = new Config(plugin, this); - plugin.setVerbose(config.verboseStartup.getValue()); - // Now load others - enterprise = new Enterprise(plugin, this); - - flatfiles = new ArrayList() { - private static final long serialVersionUID = 4497798966909062852L; - { - add(config); - add(enterprise); - } - }; - - dbfiles = new ArrayList(); - - // The following values can be configuration from a database, or from flatfile. - if (config.enterprise.getValue() && enterprise.configGroups.getValue()) { - groups = new MySQLGroupsHolder(this); - dbfiles.add((MySQLGroupsHolder) groups); - } else { - groups = new YamlGroupsHolder(plugin, this); - flatfiles.add((YamlGroupsHolder) groups); - } - - if (config.enterprise.getValue() && enterprise.configRules.getValue()) { - rules = new MySQLRulesHolder(this); - dbfiles.add((MySQLRulesHolder) rules); - } else { - rules = new YamlRulesHolder(plugin, this); - flatfiles.add((YamlRulesHolder) rules); - } - - checks = new YamlChecksHolder(plugin, this); - flatfiles.add((YamlChecksHolder) checks); - - InvocationHandler handler; - if (config.enterprise.getValue() && enterprise.configMagic.getValue()) { - handler = new MySQLMagicHolder(this); - magic = (Magic) Proxy.newProxyInstance(Magic.class.getClassLoader(), - new Class[] { Magic.class }, - handler); - dbfiles.add((MySQLMagicHolder) handler); - } else { - handler = new YamlMagicHolder(plugin, this); - magic = (Magic) Proxy.newProxyInstance(Magic.class.getClassLoader(), - new Class[] { Magic.class }, - handler); - flatfiles.add((YamlMagicHolder) handler); - } - - if (config.enterprise.getValue() && enterprise.configLang.getValue()) { - handler = new MySQLLangHolder(this); - lang = (Lang) Proxy.newProxyInstance(Lang.class.getClassLoader(), - new Class[] { Lang.class }, - handler); - dbfiles.add((MySQLLangHolder) handler); - } else { - handler = new YamlLangHolder(plugin, this); - lang = (Lang) Proxy.newProxyInstance(Lang.class.getClassLoader(), - new Class[] { Lang.class }, - handler); - flatfiles.add((YamlLangHolder) handler); - } - - if (config.enterprise.getValue() && enterprise.syncLevels.getValue()) { - levels = new MySQLLevelsHolder(this); - dbfiles.add((MySQLLevelsHolder) levels); - } else { - levels = new YamlLevelsHolder(plugin, this); - flatfiles.add((YamlLevelsHolder) levels); - } - // End - - for (ConfigurationFile file : flatfiles) { - file.save(); - checkReload(file); - } - } - - public void load() { - for (ConfigurationFile file : flatfiles) { - file.load(); - checkReload(file); - } - - for (ConfigurationTable table : dbfiles) - table.load(); - - if (manager.getBackend() != null) - manager.getBackend().updateConfig(this); - - if (manager.getCheckManager() != null) - manager.getCheckManager().loadCheckIgnoreList(this); - } - - private void checkReload(ConfigurationFile file) { - if (file.needsReload()) { - file.reload(); - file.setNeedsReload(false); - } - } - - private void removeOldFiles() { - ArrayList removed = new ArrayList(); - File configFile = new File(AntiCheatReloaded.getPlugin().getDataFolder(), "config.yml"); - if (configFile.exists() && YamlConfiguration.loadConfiguration(configFile).getString("System.Auto update") != null) { - configFile.renameTo(new File(AntiCheatReloaded.getPlugin().getDataFolder(), "config.old")); - removed.add("config.yml has been renamed to config.old and replaced with the new config.yml"); - } - File eventsFile = new File(AntiCheatReloaded.getPlugin().getDataFolder(), "events.yml"); - if (eventsFile.exists()) { - eventsFile.renameTo(new File(AntiCheatReloaded.getPlugin().getDataFolder(), "events.old")); - removed.add("events.yml has been renamed to events.old and replaced with groups.yml and rules.yml"); - } - if (removed.size() > 0) { - AntiCheatReloaded.getPlugin().getLogger().info("You are upgrading from an old version of AntiCheat. Due to configuration changes, the following files have been modified:"); - for (String s : removed) { - AntiCheatReloaded.getPlugin().getLogger().info(s); - } - } - } - - public Config getConfig() { - return config; - } - - public Groups getGroups() { - return groups; - } - - public Rules getRules() { - return rules; - } - - public Lang getLang() { - return lang; - } - - public Enterprise getEnterprise() { - return enterprise; - } - - public Levels getLevels() { - return levels; - } - - public Magic getMagic() { - return magic; - } - - public Checks getChecks() { - return checks; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationFile.java b/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationFile.java deleted file mode 100644 index 7b642bd..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationFile.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.yaml.CommentedConfiguration; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; - -public class ConfigurationFile { - - private File rawFile; - private String fileName; - - private CommentedConfiguration configFile; - private FileConfiguration defaultConfigFile; - private Configuration config; - - private AntiCheatReloaded plugin; - - private boolean saveDefault; - - protected boolean needsReload; - - public ConfigurationFile(AntiCheatReloaded plugin, Configuration config, String fileName) { - this(plugin, config, fileName, true); - } - - public ConfigurationFile(AntiCheatReloaded plugin, Configuration config, String fileName, boolean saveDefault) { - this(plugin, config, fileName, saveDefault, new File(plugin.getDataFolder(), fileName)); - } - - public ConfigurationFile(AntiCheatReloaded plugin, Configuration config, String fileName, boolean saveDefault, File rawFile) { - // Can't change with user editing - this.plugin = plugin; - this.config = config; - this.fileName = fileName; - this.rawFile = rawFile; - this.saveDefault = saveDefault; - - if (saveDefault) { - InputStreamReader reader = new InputStreamReader(plugin.getResource(fileName)); - defaultConfigFile = YamlConfiguration.loadConfiguration(reader); - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - load(); - } - - public void load() { - // Can change with user editing - if (!rawFile.exists()) { - if (saveDefault) { - plugin.saveResource(fileName, true); - } else { - if (!rawFile.getParentFile().exists()) { - rawFile.getParentFile().mkdir(); - } - try { - rawFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - configFile = CommentedConfiguration.loadConfiguration(rawFile); - - open(); - } - - public void open() { - // Nothing to do - } - - public void close() { - // Nothing to do - } - - public void save() { - close(); - try { - configFile.save(rawFile); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void reload() { - save(); - load(); - } - - public File getRawFile() { - return rawFile; - } - - public CommentedConfiguration getConfigFile() { - return configFile; - } - - public FileConfiguration getDefaultConfigFile() { - return defaultConfigFile; - } - - public Configuration getConfiguration() { - return config; - } - - public void setNeedsReload(boolean reload) { - this.needsReload = reload; - } - - public boolean needsReload() { - return needsReload; - } - - public class ConfigValue { - - private String path; - - private Object value = null; - - private boolean didLoadDefault; - - public ConfigValue(String path) { - this(path, true); - } - - public ConfigValue(String path, boolean loadDefault) { - this.path = path; - - if (getConfigFile().contains(path)) { - value = getConfigFile().get(path); - } else if (loadDefault) { - getConfigFile().set(path, getDefaultConfigFile().get(path)); - value = getDefaultConfigFile().get(path); - getConfigFile().set(path, value); - save(); - didLoadDefault = true; - } - } - - public String getPath() { - return path; - } - - @SuppressWarnings("unchecked") - public T getValue() { - return (T) value; - } - - public T setValue(T value) { - getConfigFile().set(path, value); - save(); - return value; - } - - @SuppressWarnings("unchecked") - public T getDefaultValue() { - return (T) getDefaultConfigFile().get(path); - } - - public boolean hasValue() { - return value != null; - } - - public boolean didLoadDefault() { - return didLoadDefault; - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationTable.java b/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationTable.java deleted file mode 100644 index 3614886..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/ConfigurationTable.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config; - -import org.bukkit.Bukkit; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.util.enterprise.Database; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.UUID; - -public class ConfigurationTable { - - private final String table; - private final Configuration config; - - private Database database; - private String prefix; - private String serverName; - - public ConfigurationTable(Configuration config, String table) { - this.config = config; - this.table = table; - - load(); - } - - public void load() { - this.database = config.getEnterprise().database; - this.prefix = database.getPrefix(); - this.serverName = config.getEnterprise().serverName.getValue(); - - open(); - } - - public void open() { - // Nothing to do - } - - public void reload() { - // For after sql inserts have been made - Bukkit.getScheduler().runTask(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - load(); - } - }); - } - - public Database getDatabase() { - return database; - } - - public String getFullTable() { - return prefix + table; - } - - public boolean tableExists() { - try { - return getConnection().getMetaData().getTables(null, null, getFullTable(), null).next(); - } catch (SQLException e) { - e.printStackTrace(); - return false; - } - } - - public boolean isUUIDFormatted(String colName) { - String sqlSelect = "SELECT " + colName + " FROM " + getFullTable() + " LIMIT 1"; - String user; - - try { - ResultSet res = getConnection().prepareStatement(sqlSelect).executeQuery(); - - if (res.next() && (user = res.getString(colName)) != null) { - try { - return UUID.fromString(user) != null; - } catch (IllegalArgumentException e) {} - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return false; - } - - @SuppressWarnings("deprecation") - public void convertToUUID(String colName) { - String sqlSelect = "SELECT " + colName + " FROM " + getFullTable(); - String sqlUpdate = "UPDATE " + getFullTable() + " SET " + colName + " = ? WHERE " + colName + " = ?"; - - try { - ResultSet res = getConnection().prepareStatement(sqlSelect).executeQuery(); - - while (res.next()) { - PreparedStatement stmt = getConnection().prepareStatement(sqlUpdate); - stmt.setString(1, (Bukkit.getOfflinePlayer(res.getString(1)).getUniqueId().toString())); - stmt.setString(2, res.getString(1)); - - stmt.executeUpdate(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public String getServerName() { - return serverName; - } - - public Connection getConnection() { - return database.getConnection(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/files/Config.java b/src/main/java/com/rammelkast/anticheatreloaded/config/files/Config.java deleted file mode 100644 index 1c0a9da..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/files/Config.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.files; - -import java.util.List; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; - -public class Config extends ConfigurationFile { - - public static final String FILENAME = "config.yml"; - - public ConfigValue logToConsole; - public ConfigValue verboseStartup; - public ConfigValue silentMode; - public ConfigValue exemptOp; - public ConfigValue eventChains; - public ConfigValue enterprise; - public ConfigValue debugMode; - public ConfigValue disableBroadcast; - - public ConfigValue blockChatSpamSpeed; - public ConfigValue blockCommandSpamSpeed; - public ConfigValue blockChatSpamRepetition; - public ConfigValue blockCommandSpamRepetition; - public ConfigValue chatSpamActionOne; - public ConfigValue chatSpamActionTwo; - public ConfigValue commandSpamActionOne; - public ConfigValue commandSpamActionTwo; - - public ConfigValue logToFile; - - public ConfigValue> disabledWorlds; - - public ConfigValue notifyEveryVl; - public ConfigValue maxSetbackDistance; - - public Config(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public void open() { - logToConsole = new ConfigValue("system.log-to-console"); - - verboseStartup = new ConfigValue("system.verbose-startup"); - silentMode = new ConfigValue("system.silent-mode"); - exemptOp = new ConfigValue("system.exempt-op"); - eventChains = new ConfigValue("system.event-chains"); - enterprise = new ConfigValue("system.enterprise"); - debugMode = new ConfigValue("system.debug-mode"); - disableBroadcast = new ConfigValue("system.disable-broadcast"); - - blockChatSpamSpeed = new ConfigValue("spam.chat.block-speed"); - blockChatSpamRepetition = new ConfigValue("spam.chat.block-repetition"); - chatSpamActionOne = new ConfigValue("spam.chat.action-one"); - chatSpamActionTwo = new ConfigValue("spam.chat.action-two"); - - blockCommandSpamSpeed = new ConfigValue("spam.command.block-speed"); - blockCommandSpamRepetition = new ConfigValue("spam.command.block-repetition"); - commandSpamActionOne = new ConfigValue("spam.command.action-one"); - commandSpamActionTwo = new ConfigValue("spam.command.action-two"); - - logToFile = new ConfigValue("system.log-to-file"); - - disabledWorlds = new ConfigValue>("disable-in"); - - notifyEveryVl = new ConfigValue("system.notify-every-vl"); - if (notifyEveryVl.getValue() < 1) { - notifyEveryVl.setValue(5); - } - maxSetbackDistance = new ConfigValue("system.max-setback-distance"); - if (maxSetbackDistance.getValue() < 5) { - maxSetbackDistance.setValue(50); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/files/Enterprise.java b/src/main/java/com/rammelkast/anticheatreloaded/config/files/Enterprise.java deleted file mode 100644 index 1683395..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/files/Enterprise.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.files; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.util.enterprise.Database; - -public class Enterprise extends ConfigurationFile { - - public static final String FILENAME = "enterprise.yml"; - - public ConfigValue serverName; - - public ConfigValue loggingEnabled; - public ConfigValue loggingLife; - public ConfigValue loggingInterval; - - public ConfigValue syncLevels; - public ConfigValue syncInterval; - - public ConfigValue configGroups; - public ConfigValue configRules; - public ConfigValue configMagic; - public ConfigValue configLang; - - public Database database; - - public Enterprise(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public void open() { - serverName = new ConfigValue("server.name"); - - loggingEnabled = new ConfigValue("log.enable"); - loggingLife = new ConfigValue("log.life"); - loggingInterval = new ConfigValue("log.interval"); - - syncLevels = new ConfigValue("sync.levels"); - syncInterval = new ConfigValue("sync.interval"); - - configGroups = new ConfigValue("config.groups"); - configRules = new ConfigValue("config.rules"); - configMagic = new ConfigValue("config.magic"); - configLang = new ConfigValue("config.lang"); - - ConfigValue databaseType = new ConfigValue("database.type"); - ConfigValue databaseHostname = new ConfigValue("database.hostname"); - ConfigValue databaseUsername = new ConfigValue("database.username"); - ConfigValue databasePassword = new ConfigValue("database.password"); - ConfigValue databasePrefix = new ConfigValue("database.prefix"); - ConfigValue databaseSchema = new ConfigValue("database.database"); - ConfigValue databasePort = new ConfigValue("database.port"); - - if (getConfiguration().getConfig().enterprise.getValue()) { - // Convert database values to Database - database = new Database( - Database.DatabaseType.valueOf(databaseType.getValue()), - databaseHostname.getValue(), - databasePort.getValue(), - databaseUsername.getValue(), - databasePassword.getValue(), - databasePrefix.getValue(), - databaseSchema.getValue(), - serverName.getValue(), - loggingInterval.getValue(), - loggingLife.getValue(), - syncLevels.getValue(), - syncInterval.getValue() - ); - - database.connect(); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLGroupsHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLGroupsHolder.java deleted file mode 100644 index 173c43e..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLGroupsHolder.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.mysql; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationTable; -import com.rammelkast.anticheatreloaded.config.providers.Groups; -import com.rammelkast.anticheatreloaded.util.Group; - -public class MySQLGroupsHolder extends ConfigurationTable implements Groups { - - private static final String TABLE = "groups"; - - private List groups; - private int highestLevel; - - public MySQLGroupsHolder(Configuration config) { - super(config, TABLE); - } - - @Override - public void open() { - highestLevel = 0; - groups = new ArrayList(); - - String sqlCreate = "CREATE TABLE " + getFullTable() + "(" + - " `id` INT NOT NULL AUTO_INCREMENT," + - " `name` VARCHAR(45) NOT NULL," + - " `level` INT NOT NULL," + - " `color` VARCHAR(45) NOT NULL," + - " `actions` VARCHAR(45) NOT NULL," + - " PRIMARY KEY (`id`));"; - String sqlPopulate = "INSERT INTO " + getFullTable() + - " SELECT t.*" + - " FROM (" + - " (SELECT 1 as id, 'Medium' as name, 20 as level, 'YELLOW' as color, 'WARN' as actions)" + - " UNION ALL " + - " (SELECT 2 as id, 'High' as name, 50 as level, 'RED' as color, 'KICK' as actions)" + - " ) t;"; - String sqlLoad = "SELECT * FROM " + getFullTable(); - - try { - if (!tableExists()) { - getConnection().prepareStatement(sqlCreate).executeUpdate(); - getConnection().prepareStatement(sqlPopulate).executeUpdate(); - getConnection().commit(); - } - - ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); - while (set.next()) { - String name = set.getString("name"); - int level = set.getInt("level"); - String color = set.getString("color"); - List actions = Arrays.asList(set.getString("actions").split(",")); - - groups.add(new Group(name, level, color, actions)); - if (level > highestLevel) { - highestLevel = level; - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public List getGroups() { - return groups; - } - - @Override - public int getHighestLevel() { - return highestLevel; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLangHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLangHolder.java deleted file mode 100644 index acf60f1..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLangHolder.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.mysql; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationTable; -import com.rammelkast.anticheatreloaded.config.providers.Lang; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class MySQLLangHolder extends ConfigurationTable implements InvocationHandler { - - private static final String TABLE = "lang"; - - private HashMap stringValues; - private HashMap> listValues; - - private FileConfiguration defaults; - - public MySQLLangHolder(Configuration config) { - super(config, TABLE); - } - - @Override - public void open() { - InputStreamReader reader = new InputStreamReader(AntiCheatReloaded.getPlugin().getResource("lang.yml")); - defaults = YamlConfiguration.loadConfiguration(reader); - try { - reader.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - - stringValues = new HashMap(); - listValues = new HashMap>(); - - String sqlCreate = "CREATE TABLE " + getFullTable() + "(" + - " `id` INT NOT NULL AUTO_INCREMENT," + - " `key` VARCHAR(45) NOT NULL," + - " `value` TEXT," + - " PRIMARY KEY (`id`));"; - - String sqlPopulate = "INSERT INTO " + getFullTable() + - " (`key`, `value`) " + - "SELECT t.*" + - "FROM ("; - - Method[] methods = Lang.class.getMethods(); - for (int i=1;i<=methods.length;i++) { - sqlPopulate += "(SELECT ? as `key`, ? as `value`)"; - if (i < methods.length) sqlPopulate += " UNION ALL "; - } - sqlPopulate += ") t;"; - - String sqlLoad = "SELECT * FROM " + getFullTable(); - - try { - PreparedStatement insert = getConnection().prepareStatement(sqlPopulate); - int strings = 1; - for (int i=1;i<=methods.length;i++) { - String key = methods[i-1].getName(); - String value = defaults.getString(key); - insert.setString(strings, key); - strings++; - insert.setString(strings, value); - strings++; - } - - if (!tableExists()) { - getConnection().prepareStatement(sqlCreate).executeUpdate(); - insert.executeUpdate(); - getConnection().commit(); - } - - ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); - while (set.next()) { - String key = set.getString("key"); - String value = set.getString("value"); - if (value.matches("^\\[.*\\]$")) { - listValues.put(key, getList(value)); - } else { - stringValues.put(key, value); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public Object invoke(Object proxy, Method method, Object[] args) { - String key = method.getName(); - - if (method.getReturnType() == List.class) { - if (listValues.containsKey(key)) { - return listValues.get(key); - } else if (defaults.getString(key) != null) { - String value = defaults.getString(key); - try { - PreparedStatement s = getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value) VALUES (?, ?)"); - s.setString(1, key); - s.setString(2, value); - } catch (SQLException e) { - e.printStackTrace(); - } - reload(); - return getList(value); - } - } else { - if (stringValues.containsKey(key)) { - return stringValues.get(key); - } else if (defaults.getString(key) != null) { - String value = defaults.getString(key); - try { - PreparedStatement s = getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value) VALUES (?, ?)"); - s.setString(1, key); - s.setString(2, value); - } catch (SQLException e) { - e.printStackTrace(); - } - reload(); - return value; - } - } - AntiCheatReloaded.getPlugin().getLogger().severe("The lang value " + key + " couldn't be found."); - return "Language error. See console for details."; - } - - private List getList(String value) { - value = value.substring(1, value.length() - 1); - ArrayList list = new ArrayList(); - for (String s : value.split(", ")) { - list.add(s); - } - return list; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLevelsHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLevelsHolder.java deleted file mode 100644 index 722a5f9..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLLevelsHolder.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.mysql; - -import org.bukkit.Bukkit; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationTable; -import com.rammelkast.anticheatreloaded.config.providers.Levels; -import com.rammelkast.anticheatreloaded.util.User; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -public class MySQLLevelsHolder extends ConfigurationTable implements Levels { - - private static final String TABLE = "levels"; - private static final String MANUAL_EDIT_TAG = "MANUAL"; - - private String sqlSave; - private String sqlLoad; - private String sqlUpdate; - - public MySQLLevelsHolder(Configuration config) { - super(config, TABLE); - } - - @Override - public void open() { - sqlSave = "INSERT INTO " + getFullTable() + - " (user, level, last_update_server) " + - "VALUES (?, ?, ?) " + - "ON DUPLICATE KEY UPDATE " + - "level = IF(last_update = ?, ?, level+?), " + - "last_update=CURRENT_TIMESTAMP, " + - "last_update_server=?"; - - sqlLoad = "SELECT level, last_update FROM " + getFullTable() + " " + - "WHERE user = ?"; - - sqlUpdate = "SELECT level, last_update FROM " + getFullTable() + " " + - "WHERE user = ? AND last_update <> ? AND last_update_server = ?"; - - String sqlCreate = "CREATE TABLE " + getFullTable() + "(" + - " `user` VARCHAR(45) NOT NULL," + - " `level` INT NOT NULL," + - " `last_update` TIMESTAMP NOT NULL DEFAULT NOW()," + - " `last_update_server` VARCHAR(45) NOT NULL," + - " PRIMARY KEY (`user`));"; - - try { - if (!tableExists()) { - getConnection().prepareStatement(sqlCreate).executeUpdate(); - getConnection().commit(); - } else if (!isUUIDFormatted("user")) { - convertToUUID("user"); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void saveLevelFromUser(final User user) { - Bukkit.getScheduler().runTaskAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - if (!user.isWaitingOnLevelSync()) { - AntiCheatReloaded.debugLog("Saving level from " + user.getUUID() + ". Value: " + user.getLevel()); - try { - PreparedStatement statement = getConnection().prepareStatement(sqlSave); - statement.setString(1, user.getUUID().toString()); - statement.setInt(2, user.getLevel()); - statement.setString(3, getServerName()); - statement.setTimestamp(4, user.getLevelSyncTimestamp()); - statement.setInt(5, user.getLevel()); - statement.setInt(6, user.getLevel()); - statement.setString(7, getServerName()); - - statement.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - AntiCheatReloaded.getManager().getUserManager().remove(user); - } - }); - } - - @Override - public void loadLevelToUser(final User user) { - Bukkit.getScheduler().runTaskAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = getConnection().prepareStatement(sqlLoad); - statement.setString(1, user.getUUID().toString()); - - ResultSet set = statement.executeQuery(); - - boolean has = false; - while (set.next()) { - has = true; - AntiCheatReloaded.debugLog("Syncing level to " + user.getUUID() + ". Value: " + set.getInt("level")); - user.setLevel(set.getInt("level")); - user.setLevelSyncTimestamp(set.getTimestamp("last_update")); - } - if (!has) user.setLevel(0); - } catch (SQLException e) { - e.printStackTrace(); - } - } - }); - } - - @Override - public void saveLevelsFromUsers(List users) { - try { - PreparedStatement statement = getConnection().prepareStatement(sqlSave); - for (User user : users) { - if (!user.isWaitingOnLevelSync()) { - try { - statement.setString(1, user.getUUID().toString()); - statement.setInt(2, user.getLevel()); - statement.setString(3, getServerName()); - statement.setTimestamp(4, user.getLevelSyncTimestamp()); - statement.setInt(5, user.getLevel()); - statement.setInt(6, user.getLevel()); - statement.setString(7, getServerName()); - - statement.addBatch(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - statement.executeBatch(); - getConnection().commit(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void updateLevelToUser(final User user) { - Bukkit.getScheduler().runTaskAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = getConnection().prepareStatement(sqlUpdate); - statement.setString(1, user.getUUID().toString()); - statement.setTimestamp(2, user.getLevelSyncTimestamp()); - statement.setString(3, MANUAL_EDIT_TAG); - - ResultSet set = statement.executeQuery(); - - while (set.next()) { - AntiCheatReloaded.debugLog("Syncing level to " + user.getUUID() + ". Value: " + set.getInt("level")); - user.setLevel(set.getInt("level")); - user.setLevelSyncTimestamp(set.getTimestamp("last_update")); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - }); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLMagicHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLMagicHolder.java deleted file mode 100644 index 857fd46..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLMagicHolder.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.mysql; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationTable; -import com.rammelkast.anticheatreloaded.config.providers.Magic; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; - -public class MySQLMagicHolder extends ConfigurationTable implements InvocationHandler { - - private static final String TABLE = "magic"; - - private HashMap ints; - private HashMap doubles; - - private FileConfiguration defaults; - - public MySQLMagicHolder(Configuration config) { - super(config, TABLE); - } - - @Override - public void open() { - InputStreamReader reader = new InputStreamReader(AntiCheatReloaded.getPlugin().getResource("magic.yml")); - defaults = YamlConfiguration.loadConfiguration(reader); - try { - reader.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - - ints = new HashMap(); - doubles = new HashMap(); - - String sqlCreate = "CREATE TABLE " + getFullTable() + "(" + - " `id` INT NOT NULL AUTO_INCREMENT," + - " `key` VARCHAR(45) NOT NULL," + - " `value_int` INT," + - " `value_double` DOUBLE," + - " PRIMARY KEY (`id`));"; - - String sqlPopulate = "INSERT INTO " + getFullTable() + - " (`key`, `value_int`, `value_double`) " + - "SELECT t.*" + - "FROM ("; - - Method[] methods = Magic.class.getMethods(); - for (int i=1;i<=methods.length;i++) { - String key = methods[i-1].getName(); - Object value = defaults.get(key); - String type1 = methods[i-1].getReturnType().getSimpleName(); - String type2 = type1.equals("int") ? "double" : "int"; - sqlPopulate += "(SELECT '" + key + "' as `key`, " + (type1.equals("int") ? value : "null") + " as value_" + type1 + ", " + (type1.equals("double") ? value : "null") + " as value_" + type2 + ")"; - if (i < methods.length) sqlPopulate += " UNION ALL "; - } - - sqlPopulate += ") t;"; - - String sqlLoad = "SELECT * FROM " + getFullTable(); - - try { - if (!tableExists()) { - getConnection().prepareStatement(sqlCreate).executeUpdate(); - getConnection().prepareStatement(sqlPopulate).executeUpdate(); - getConnection().commit(); - } - - ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); - while (set.next()) { - String key = set.getString("key"); - - if (set.getObject("value_int") != null) { - ints.put(key, set.getInt("value_int")); - } else if (set.getObject("value_double") != null) { - doubles.put(key, set.getDouble("value_double")); - } else { - AntiCheatReloaded.getPlugin().getLogger().severe("The magic value " + key + " loaded from the database did not have a value configured. Using the default value."); - for (int i=1;i<=methods.length;i++) { - String name = methods[i-1].getName(); - if (name.equalsIgnoreCase(key)) { - String type = methods[i-1].getReturnType().getSimpleName(); - if (type.equals("int")) { - ints.put(key, defaults.getInt(key)); - } else if (type.equals("double")) { - doubles.put(key, defaults.getDouble(key)); - } - } - } - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public Object invoke(Object proxy, Method method, Object[] args) { - String key = method.getName(); - - if (ints.containsKey(key)) { - return ints.get(key).intValue(); - } else if (doubles.containsKey(key)) { - return doubles.get(key).doubleValue(); - } else if (defaults.getString(key) != null ) { - if (method.getReturnType().getSimpleName().equals("int")) { - int value = defaults.getInt(key); - try { - getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value_int) VALUES ('" + key + "' , '" + value + "')").executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - reload(); - return value; - } else if (method.getReturnType().getSimpleName().equals("double")) { - double value = defaults.getDouble(key); - try { - getConnection().prepareStatement("INSERT INTO " + getFullTable() + " (key, value_double) VALUES ('" + key + "' , '" + value + "')").executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - reload(); - return value; - } - } - AntiCheatReloaded.getPlugin().getLogger().severe("The magic value " + key + " couldn't be found."); - return 0; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLRulesHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLRulesHolder.java deleted file mode 100644 index 4dac15f..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/mysql/MySQLRulesHolder.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.mysql; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationTable; -import com.rammelkast.anticheatreloaded.config.providers.Rules; -import com.rammelkast.anticheatreloaded.util.rule.Rule; - -public class MySQLRulesHolder extends ConfigurationTable implements Rules { - - private static final String TABLE = "rules"; - - private List rules; - - public MySQLRulesHolder(Configuration config) { - super(config, TABLE); - } - - @Override - public void open() { - String sqlCreate = "CREATE TABLE " + getFullTable() + "(" + - " `id` INT NOT NULL AUTO_INCREMENT," + - " `rule` VARCHAR(256) NOT NULL," + - " PRIMARY KEY (`id`));"; - String sqlPopulate = "INSERT INTO " + getFullTable() + - " VALUES (1, 'Check_SPIDER < 0 ? Player.KICK : null')"; - - String sqlLoad = "SELECT * FROM " + getFullTable(); - - try { - if (!tableExists()) { - getConnection().prepareStatement(sqlCreate).executeUpdate(); - getConnection().prepareStatement(sqlPopulate).executeUpdate(); - getConnection().commit(); - } - - this.rules = new ArrayList(); - ResultSet set = getConnection().prepareStatement(sqlLoad).executeQuery(); - while (set.next()) { - String string = set.getString("rule"); - Rule rule = Rule.load(string); - if (rule != null) { - this.rules.add(rule); - } else { - AntiCheatReloaded.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from the database. Improper format used."); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public List getRules() { - return rules; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlChecksHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlChecksHolder.java deleted file mode 100644 index 704166e..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlChecksHolder.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.config.providers.Checks; - -public class YamlChecksHolder extends ConfigurationFile implements Checks { - - public static final String FILENAME = "checks.yml"; - - public YamlChecksHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public void open() { - - } - - @Override - public boolean getBoolean(CheckType checkType, String subcheck, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getConfigurationSection(subcheck) - .getBoolean(name); - } - - @Override - public boolean isSubcheckEnabled(CheckType checkType, String subcheck) { - return this.getBoolean(checkType, subcheck, "enabled"); - } - - @Override - public double getDouble(CheckType checkType, String subcheck, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getConfigurationSection(subcheck) - .getDouble(name); - } - - @Override - public int getInteger(CheckType checkType, String subcheck, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getConfigurationSection(subcheck) - .getInt(name); - } - - @Override - public boolean getBoolean(CheckType checkType, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getBoolean(name); - } - - @Override - public double getDouble(CheckType checkType, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getDouble(name); - } - - @Override - public int getInteger(CheckType checkType, String name) { - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getInt(name); - } - - @Override - public boolean isEnabled(CheckType checkType) { - // If the root of a check has no enabled or disabled option, it has to be configured on a subcheck basis - if (!this.getConfigFile().isConfigurationSection(checkType.getName().toLowerCase())) { - Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.RED - + "Missing configuration settings for " + checkType.getName() + "!"); - return true; - } - if (!this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).contains("enabled")) - return true; - return this.getConfigFile().getConfigurationSection(checkType.getName().toLowerCase()).getBoolean("enabled"); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlGroupsHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlGroupsHolder.java deleted file mode 100644 index 285c804..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlGroupsHolder.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import java.util.*; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.config.providers.Groups; -import com.rammelkast.anticheatreloaded.util.Group; - -public class YamlGroupsHolder extends ConfigurationFile implements Groups { - - public static final String FILENAME = "groups.yml"; - - private List groups; - - private int highestLevel; - - public YamlGroupsHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public List getGroups() { - return groups; - } - - @Override - public int getHighestLevel() { - return highestLevel; - } - - @Override - public void open() { - ConfigValue> groups = new ConfigValue>("groups"); - - // Convert groups list to Levels - this.groups = new ArrayList(); - for (String string : groups.getValue()) { - Group group = Group.load(string); - if (group == null || group.getLevel() < 0) { - continue; - } - - this.groups.add(group); - highestLevel = group.getLevel() > highestLevel ? group.getLevel() : highestLevel; - } - - // Sort groups - Collections.sort(this.groups, new Comparator() { - public int compare(Group l1, Group l2) { - if (l1.getLevel() == l2.getLevel()) { - return 0; - } else if (l1.getLevel() < l2.getLevel()) { - return -1; - } - return 1; - } - }); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLangHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLangHolder.java deleted file mode 100644 index aecb917..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLangHolder.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.List; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; - -public class YamlLangHolder extends ConfigurationFile implements InvocationHandler { - - public static final String FILENAME = "lang.yml"; - - public YamlLangHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public void open() { - if (new ConfigValue("chat.ban_broadcast").getValue() != null) { - update(); - } - } - - private void update() { - new ConfigValue>("ALERT").setValue(new ConfigValue>("alert").getValue()); - new ConfigValue>("WARNING").setValue(new ConfigValue>("warning.player_warning").getValue()); - new ConfigValue>("alert").setValue(null); - new ConfigValue>("warning.player_warning").setValue(null); - updateValue("ban.ban_reason", "BAN_REASON"); - updateValue("ban.ban_broadcast", "BAN_BROADCAST"); - updateValue("kick.kick_reason", "KICK_REASON"); - updateValue("kick.kick_broadcast", "KICK_BROADCAST"); - updateValue("chat.warning", "SPAM_WARNING"); - updateValue("chat.kick_reason", "SPAM_KICK_REASON"); - updateValue("chat.kick_broadcast", "SPAM_KICK_BROADCAST"); - updateValue("chat.ban_reason", "SPAM_BAN_REASON"); - updateValue("chat.ban_broadcast", "SPAM_BAN_BROADCAST"); - } - - private void updateValue(String oldValue, String newValue) { - new ConfigValue(newValue).setValue(new ConfigValue(oldValue).getValue()); - new ConfigValue(oldValue).setValue(null); - } - - public Object invoke(Object proxy, Method method, Object[] args) { - String key = method.getName(); - - if (method.getReturnType() == List.class) { - ConfigValue> value = new ConfigValue>(key); - if (value.getValue() != null) { - return value.getValue(); - } - } else { - ConfigValue value = new ConfigValue(key); - if (value.getValue() != null) { - return value.getValue(); - } - } - AntiCheatReloaded.getPlugin().getLogger().severe("The lang value " + key + " couldn't be found."); - return "Language error. See console for details."; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLevelsHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLevelsHolder.java deleted file mode 100644 index ce78d00..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlLevelsHolder.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import java.util.List; -import java.util.UUID; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.config.providers.Levels; -import com.rammelkast.anticheatreloaded.util.User; - -public class YamlLevelsHolder extends ConfigurationFile implements Levels { - - public static final String FILENAME = "data/levels.yml"; - - public YamlLevelsHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME, false); - } - - @Override - public void loadLevelToUser(User user) { - user.setLevel(getLevel(user.getUUID())); - } - - @Override - public void saveLevelFromUser(User user) { - saveLevelFromUser(user, true); - } - - private void saveLevelFromUser(User user, boolean remove) { - saveLevel(user.getUUID(), user.getLevel()); - if (remove) AntiCheatReloaded.getManager().getUserManager().remove(user); - } - - @Override - public void saveLevelsFromUsers(List users) { - for (User user : users) { - saveLevelFromUser(user, false); - } - } - - @Override - public void updateLevelToUser(User user) { - // This method intentionally left blank. - return; - } - - private int getLevel(UUID uuid) { - ConfigValue level = new ConfigValue(uuid.toString(), false); - if (level.hasValue()) { - return level.getValue(); - } else { - return 0; - } - } - - private void saveLevel(UUID uuid, int level) { - new ConfigValue(uuid.toString(), false).setValue(level); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlMagicHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlMagicHolder.java deleted file mode 100644 index 7c54d02..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlMagicHolder.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; - -public class YamlMagicHolder extends ConfigurationFile implements InvocationHandler { - - public static final String FILENAME = "magic.yml"; - - public YamlMagicHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - public Object invoke(Object proxy, Method method, Object[] args) { - String key = method.getName(); - - if (method.getReturnType().getSimpleName().equals("int")) { - return new ConfigValue(key).getValue(); - } else if (method.getReturnType().getSimpleName().equals("double")) { - return new ConfigValue(key).getValue(); - } else { - AntiCheatReloaded.getPlugin().getLogger().severe("The magic value " + key + " couldn't be found."); - return -1; - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlRulesHolder.java b/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlRulesHolder.java deleted file mode 100644 index 7e49614..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/holders/yaml/YamlRulesHolder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.holders.yaml; - -import java.util.ArrayList; -import java.util.List; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.config.ConfigurationFile; -import com.rammelkast.anticheatreloaded.config.providers.Rules; -import com.rammelkast.anticheatreloaded.util.rule.Rule; - -public class YamlRulesHolder extends ConfigurationFile implements Rules { - - public static final String FILENAME = "rules.yml"; - - private List rules; - - public YamlRulesHolder(AntiCheatReloaded plugin, Configuration config) { - super(plugin, config, FILENAME); - } - - @Override - public List getRules() { - return rules; - } - - @Override - public void open() { - ConfigValue> rules = new ConfigValue>("rules"); - - // Convert rules list to Rules - this.rules = new ArrayList(); - List tempRules = rules.getValue(); - for (int i = 0; i < tempRules.size(); i++) { - String string = tempRules.get(i); - - if (string.equals("Check_SPIDER < 0 ? Player.KICK : null")) { - // Default rule, won't ever run so we shouldn't load it; only used as example - continue; - } - - Rule rule = Rule.load(string); - if (rule != null) { - this.rules.add(rule); - } else { - AntiCheatReloaded.getPlugin().getLogger().warning("Couldn't load rule '" + string + "' from config. Improper format used."); - } - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Checks.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Checks.java deleted file mode 100644 index 846cdda..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Checks.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.config.providers; - -import com.rammelkast.anticheatreloaded.check.CheckType; - -public interface Checks { - - public boolean getBoolean(CheckType checkType, String name); - - public boolean getBoolean(CheckType checkType, String subcheck, String name); - - public double getDouble(CheckType checkType, String name); - - public double getDouble(CheckType checkType, String subcheck, String name); - - public int getInteger(CheckType checkType, String name); - - public int getInteger(CheckType checkType, String subcheck, String name); - - public boolean isEnabled(CheckType checkType); - - public boolean isSubcheckEnabled(CheckType checkType, String subcheck); - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Groups.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Groups.java deleted file mode 100644 index d9ffaf0..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Groups.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.providers; - -import java.util.List; - -import com.rammelkast.anticheatreloaded.util.Group; - -public interface Groups { - - /** - * Get all groups. - * - * @return List of groups. - */ - public List getGroups(); - - /** - * Get the highest level value assigned to a group. - * Used as a maximum cap to rising hack levels. - * - * @return Highest group level. - */ - public int getHighestLevel(); -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Lang.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Lang.java deleted file mode 100644 index cf795c3..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Lang.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.providers; - -import java.util.List; - -public interface Lang { - - /** - * Get the alert to send when a player's hack group changes. - * - * @return Alert - */ - public List ALERT(); - - /** - * Get the warning to send players when they enter a group. - * - * @return Warning. - */ - public List WARNING(); - - /** - * Get the warning to send players for spamming. - * - * @return Spam warning. - */ - public String SPAM_WARNING(); - - /** - * Get the reason for kicking a player for spam. - * - * @return Spam kicking reason. - */ - public String SPAM_KICK_REASON(); - - /** - * Get the reason for banning a player for spam. - * - * @return Spam banning reason. - */ - public String SPAM_BAN_REASON(); - - /** - * Get the broadcast for kicking a player for spam. - * - * @return Spam kicking broadcast. - */ - public String SPAM_KICK_BROADCAST(); - - /** - * Get the broadcast for banning a player for spam. - * - * @return Spam banning broadcast. - */ - public String SPAM_BAN_BROADCAST(); - - /** - * Get the reason for banning a player. - * - * @return Banning reason. - */ - public String BAN_REASON(); - - /** - * Get the broadcast for banning a player. - * - * @return Banning broadcast. - */ - public String BAN_BROADCAST(); - - /** - * Get the reason for kicking a player. - * - * @return Kicking reason. - */ - public String KICK_REASON(); - - /** - * Get the broadcast for kicking a player. - * - * @return Kicking broadcast. - */ - public String KICK_BROADCAST(); - - - /** - * Get the alert prefix for staff and debug. - * - * @return Alert prefix. - */ - public String ALERT_PREFIX(); -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Levels.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Levels.java deleted file mode 100644 index 86b1345..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Levels.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.providers; - -import java.util.List; - -import com.rammelkast.anticheatreloaded.util.User; - -public interface Levels { - - /** - * Checks for a stored level for this user, and loads it to their object if found. - * - * @param user User to load. - */ - public void loadLevelToUser(User user); - - /** - * Saves the user's level to storage. - * - * @param user User to save. - */ - public void saveLevelFromUser(User user); - - /** - * Saves a list of user's levels to storage. - * Used on server shutdown / reload. - * - * @param users List of users to save. - */ - public void saveLevelsFromUsers(List users); - - /** - * Check to see if the user's level has been manually changed since it was loaded, and update it if needed - * - * @param user User to update. - */ - public void updateLevelToUser(User user); -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Magic.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Magic.java deleted file mode 100644 index f027d68..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Magic.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.providers; - -/** - * Magic number class. Modifications to values in magic.yml will be accepted here. - *

- * Note that although each value is documented, changing it may have unintended side-effects. For instance, setting something to 0 that the plugin then uses as a dividend will result in an error.
- * Also realize that the smaller (more precise) a value is, the less you should change it; it's probably small for a reason. The larger a value is, the safer it is to make larger modifications to it. - *

- * How to read the value documentation: - *

- * First, you will see a description of the value. Then, you will see a type:
- * Type SYSTEM: This is a millisecond value used to compare past and future events with the current SYSTEM time. Remember, 1000 ms = 1 second.
- * Type INTEGER: This is a regular number. It's typically used as something trivial, such as how many times X event can occur.
- * Type DOUBLE: This is a number that has a decimal in it. It's typically used to evaluate speed or distance. - *

- * After the type, you may see a recommendation labeled as 'Leniency'. This means 'In order to add leniency to this value, do X'
- * The suggestion for adding leniency will either be to INCREASE or DECREASE the variable. Doing what it suggests will cause the SYSTEM to not judge the people being checked so vigorously.
- * Some values may not have a leniency recommendation because they are internal numbers used for running checks. Values without these recommendations would be best left alone. - */ - -public interface Magic { - /** - * Time to exempt a player from moving because of entering/exiting a vehicle; Type=SYSTEM, Leniency=INCREASE. - */ - public int ENTERED_EXITED_TIME(); - /** - * Time to exempt a player from moving because of teleporting; Type=SYSTEM, Leniency=INCREASE. - */ - public int TELEPORT_TIME(); - /** - * Time to exempt a player from moving because of joining the server; Type=SYSTEM, Leniency=INCREASE. - */ - public int JOIN_TIME(); - /** - * Time to exempt a player from moving because of taking damage; Type=SYSTEM, Leniency=INCREASE. - */ - public int DAMAGE_TIME(); - /** - * Time to exempt a player from moving because of taking damage with knockback effects; Type=SYSTEM, Leniency=INCREASE. - */ - public int KNOCKBACK_DAMAGE_TIME(); - /** - * Time to exempt a player from moving because of taking damage from an explosion; Type=SYSTEM, Leniency=INCREASE. - */ - public int EXPLOSION_DAMAGE_TIME(); - /** - * Time used to schedule increasing a players velocity count - probably not touching this would be good; Type=INTEGER. - */ - public int VELOCITY_EXTENSION(); - /** - * Time a player is considered to have a change in velocity; Type=SYSTEM, Leniency=INCREASE. - */ - public int VELOCITY_TIME(); - /** - * Time to extend a player's velocity count by; Type=SYSTEM, Leniency=INCREASE. - */ - public int VELOCITY_PREVENT(); - /** - * Maximum amount of velocity tracks; Type=INTEGER, Leniency=INCREASE. - */ - public int VELOCITY_MAXTIMES(); - /** - * Minimum travel distance for move to be considered a teleport and subsequently be ignored; Type=INTEGER, Leniency=INCREASE. - */ - public int TELEPORT_MIN(); - /** - * The change milliseconds between two keepalives before considering a player to be lagging; TYPE=INTEGER, Leniency=DECREASE - */ - public int LAG_DETERMINATION(); -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Rules.java b/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Rules.java deleted file mode 100644 index 097d24e..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/providers/Rules.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.providers; - -import java.util.List; - -import com.rammelkast.anticheatreloaded.util.rule.Rule; - -public interface Rules { - - /** - * Get all rules. - * - * @return List of rules. - */ - public List getRules(); -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/config/yaml/CommentedConfiguration.java b/src/main/java/com/rammelkast/anticheatreloaded/config/yaml/CommentedConfiguration.java deleted file mode 100644 index 64a4cfe..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/config/yaml/CommentedConfiguration.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.config.yaml; - -import org.apache.commons.lang.Validate; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.configuration.file.YamlConstructor; -import org.bukkit.configuration.file.YamlRepresenter; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.error.YAMLException; -import org.yaml.snakeyaml.representer.Representer; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayDeque; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; - -/** - * An extension of {@link org.bukkit.configuration.file.YamlConfiguration} which preserves comments. - * Note that this implementation is not synchronized. - *
- * Some overridden code has been moved to this file from its parent & modified. - */ -public class CommentedConfiguration extends YamlConfiguration { - private Map comments = new HashMap(); - - private final DumperOptions yamlOptions = new DumperOptions(); - private final Representer yamlRepresenter = new YamlRepresenter(); - private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); - - @Override - public void loadFromString(String contents) throws InvalidConfigurationException { - Validate.notNull(contents, "Contents cannot be null"); - - Map input; - try { - input = (Map) yaml.load(contents); - } catch (YAMLException e) { - throw new InvalidConfigurationException(e); - } catch (ClassCastException e) { - throw new InvalidConfigurationException("Top level is not a Map."); - } - - /** - CommentedConfiguration - String header = parseHeader(contents); - if (header.length() > 0) { - options().header(header); - } - **/ - - if (input != null) { - convertMapsToSections(input, this); - } - - // Begin CommentedConfiguration - int i = 0; - int blank = 0; - String[] lines = contents.split("\n"); - while (i < lines.length) { - if (lines[i].trim().equalsIgnoreCase("")) { - i++; - blank++; - continue; - } - if (lines[i].contains(COMMENT_PREFIX)) { - comments.put(i - blank, lines[i]); - } - i++; - } - // End CommentedConfiguration - } - - @Override - public String saveToString() { - yamlOptions.setIndent(options().indent()); - yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - // String header = buildHeader(); - CommentedConfiguration - String dump = yaml.dump(getValues(false)); - - if (dump.equals(BLANK_CONFIG)) { - dump = ""; - } - - // Begin CommentedConfiguration - StringBuilder builder = new StringBuilder(); - - String[] lines = dump.split("\n"); - ArrayDeque queue = new ArrayDeque(); - for (String string : lines) { - queue.add(string); - } - - int i = 0; - while (queue.size() > 0) { - if (comments.containsKey(i)) { - builder.append(comments.get(i)); - - // Handle subsequent comments - int b = i; - while (true) { - b++; - if (comments.containsKey(b)) { - builder.append('\n'); - builder.append(comments.get(b)); - } else { - break; - } - } - builder.append('\n'); - i = b; - } - - builder.append(queue.getFirst()); - builder.append('\n'); - queue.pop(); - i++; - } - // End CommentedConfiguration - - return builder.toString(); - } - - /** - * Creates a new {@link CommentedConfiguration}, loading from the given file. - *

- * Any errors loading the Configuration will be logged and then ignored. - * If the specified input is not a valid config, a blank config will be returned. - * - * @param file Input file - * @return Resulting configuration - * @throws IllegalArgumentException Thrown if file is null - */ - public static CommentedConfiguration loadConfiguration(File file) { - Validate.notNull(file, "File cannot be null"); - - CommentedConfiguration config = new CommentedConfiguration(); - - try { - config.load(file); - } catch (FileNotFoundException ex) { - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); - } - - return config; - } - - /** - * Creates a new {@link CommentedConfiguration}, loading from the given stream. - *

- * Any errors loading the Configuration will be logged and then ignored. - * If the specified input is not a valid config, a blank config will be returned. - * - * @param stream Input stream - * @return Resulting configuration - * @throws IllegalArgumentException Thrown if stream is null - */ - public static CommentedConfiguration loadConfiguration(InputStream stream) { - Validate.notNull(stream, "Stream cannot be null"); - - CommentedConfiguration config = new CommentedConfiguration(); - - try { - InputStreamReader reader = new InputStreamReader(stream); - config.load(reader); - reader.close(); - } catch (IOException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); - } catch (InvalidConfigurationException ex) { - Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); - } - - return config; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/BlockListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/BlockListener.java deleted file mode 100644 index 13c9bfe..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/BlockListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.player.IllegalInteract; - -public class BlockListener extends EventListener { - - @EventHandler(ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - final Player player = event.getPlayer(); - boolean noHack = true; - if (getCheckManager().willCheck(player, CheckType.FAST_PLACE)) { - CheckResult result = getBackend().checkFastPlace(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_PLACE, result.getSubCheck()); - noHack = false; - } - } - - if (getCheckManager().willCheck(player, CheckType.ILLEGAL_INTERACT)) { - CheckResult result = IllegalInteract.performCheck(player, event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.ILLEGAL_INTERACT, result.getSubCheck()); - noHack = false; - } - } - if (noHack) { - decrease(player); - getBackend().logBlockPlace(player); - } - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - final Player player = event.getPlayer(); - boolean noHack = true; - CheckResult result; - if (getCheckManager().willCheck(player, CheckType.ILLEGAL_INTERACT)) { - result = IllegalInteract.performCheck(player, event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.ILLEGAL_INTERACT, result.getSubCheck()); - noHack = false; - } - } - if (noHack) { - decrease(player); - } - getBackend().logBlockBreak(player); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java deleted file mode 100644 index a52c5f4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.event; - -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Player; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.entity.EntityRegainHealthEvent; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; -import org.bukkit.event.entity.EntityShootBowEvent; -import org.bukkit.event.entity.FoodLevelChangeEvent; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.combat.CriticalsCheck; -import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class EntityListener extends EventListener { - - @EventHandler - public void onEntityShootBow(EntityShootBowEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (getCheckManager().willCheck(player, CheckType.FAST_BOW)) { - CheckResult result = getBackend().checkFastBow(player, event.getForce()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_BOW, result.getSubCheck()); - } else { - decrease(player); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onEntityRegainHealth(EntityRegainHealthEvent event) { - if (event.getEntity() instanceof Player && event.getRegainReason() == RegainReason.SATIATED) { - Player player = (Player) event.getEntity(); - if (getCheckManager().willCheck(player, CheckType.FAST_HEAL)) { - CheckResult result = getBackend().checkFastHeal(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_HEAL, result.getSubCheck()); - } else { - decrease(player); - getBackend().logHeal(player); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onFoodLevelChange(FoodLevelChangeEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (player.getFoodLevel() < event.getFoodLevel() && getCheckManager().willCheck(player, CheckType.FAST_EAT)) // Make sure it's them actually gaining a food level - { - CheckResult result = getBackend().checkFastEat(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_EAT, result.getSubCheck()); - } else { - decrease(player); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDamage(EntityDamageEvent event) { - boolean noHack = true; - if (event instanceof EntityDamageByEntityEvent) { - EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; - if (e.getDamager() instanceof Player) { - if (getCheckManager().willCheck((Player)e.getDamager(), CheckType.CRITICALS)) { - CriticalsCheck.doDamageEvent(e, (Player)e.getDamager()); - } - } - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (e.getDamager() instanceof Player) { - Player p = (Player) e.getDamager(); - getBackend().logDamage(p, 1); - int value = VersionUtil.getItemInHand(player).containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1; - getBackend().logDamage(player, value); - } else { - if (e.getDamager() instanceof TNTPrimed || e.getDamager() instanceof Creeper) { - getBackend().logDamage(player, 3); - } else { - getBackend().logDamage(player, 1); - } - } - } - if (e.getDamager() instanceof Player && event.getCause() == DamageCause.ENTITY_ATTACK) { - Player player = (Player) e.getDamager(); - if (getCheckManager().willCheck(player, CheckType.KILLAURA)) { - CheckResult result = KillAuraCheck.checkAngle(player, event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.KILLAURA, result.getSubCheck()); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.KILLAURA)) { - CheckResult result = KillAuraCheck.checkReach(player, event.getEntity()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.KILLAURA, result.getSubCheck()); - noHack = false; - } - } - if (getCheckManager().willCheck(player, CheckType.KILLAURA)) { - CheckResult result = KillAuraCheck.checkPacketOrder(player, event.getEntity()); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.KILLAURA, result.getSubCheck()); - noHack = false; - } - } - if (noHack) { - decrease(player); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/EventListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/EventListener.java deleted file mode 100644 index 5bb4a16..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/EventListener.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.event; - -import java.text.DecimalFormat; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.manage.AntiCheatManager; -import com.rammelkast.anticheatreloaded.manage.CheckManager; -import com.rammelkast.anticheatreloaded.manage.UserManager; -import com.rammelkast.anticheatreloaded.util.User; - -public class EventListener implements Listener { - private static final Map USAGE_LIST = new EnumMap(CheckType.class); - private static final Map DECREASE_LIST = new HashMap(); - private static final CheckManager CHECK_MANAGER = AntiCheatReloaded.getManager().getCheckManager(); - private static final Backend BACKEND = AntiCheatReloaded.getManager().getBackend(); - private static final AntiCheatReloaded PLUGIN = AntiCheatReloaded.getManager().getPlugin(); - private static final UserManager USER_MANAGER = AntiCheatReloaded.getManager().getUserManager(); - private static final Configuration CONFIG = AntiCheatReloaded.getManager().getConfiguration(); - private static final DecimalFormat TPS_FORMAT = new DecimalFormat("##.##"); - - public static void log(String message, Player player, CheckType type, String subcheck) { - User user = getUserManager().getUser(player.getUniqueId()); - if (user == null) - return; - - boolean debugMode = CONFIG.getConfig().debugMode.getValue(); - int vlForType = type.getUses(player.getUniqueId()) + 1; - int notifyEveryVl = CONFIG.getConfig().notifyEveryVl.getValue(); - String prefix = ChatColor.translateAlternateColorCodes('&', CONFIG.getLang().ALERT_PREFIX()); - if (message == null || message.equals("")) { - if (debugMode) { - message = prefix + player.getName() + " failed " - + type.getName(); - } else { - message = prefix + player.getName() + " failed " - + type.getName() + ChatColor.GOLD + " (x" + vlForType + ")"; - } - } else { - if (debugMode) { - message = prefix + player.getName() + " failed " - + type.getName() + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + message - + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "ping: " + user.getPing() + "ms" - + ", tps: " + TPS_FORMAT.format(AntiCheatReloaded.getPlugin().getTPS()); - } else { - message = prefix - + player.getName() + " failed " + type.getName() + ChatColor.GOLD + " (x" + vlForType + ")" - + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY - + (subcheck != null ? ("type: " + subcheck.toLowerCase() + ", ") : "") + "ping: " + user.getPing() + "ms" - + ", tps: " + TPS_FORMAT.format(AntiCheatReloaded.getPlugin().getTPS()); - } - } - - logCheat(type, user); - if (user.increaseLevel(type) && (!debugMode && vlForType % notifyEveryVl == 0)) { - AntiCheatReloaded.getManager().log(message); - } - removeDecrease(user); - - if (debugMode) { - player.sendMessage(message); - return; - } - - if (vlForType % notifyEveryVl == 0) { - AntiCheatReloaded.getPlugin().sendToStaff(message); - } - } - - private static void logCheat(CheckType type, User user) { - USAGE_LIST.put(type, getCheats(type) + 1); - // Ignore plugins that are creating NPCs with no names (why the hell) - if (user != null && user.getUUID() != null) { - type.logUse(user); - if (CONFIG.getConfig().enterprise.getValue() && CONFIG.getEnterprise().loggingEnabled.getValue()) { - CONFIG.getEnterprise().database.logEvent(user, type); - } - } - } - - public void resetCheck(CheckType type) { - USAGE_LIST.put(type, 0); - } - - public static int getCheats(CheckType type) { - int x = 0; - if (USAGE_LIST.get(type) != null) { - x = USAGE_LIST.get(type); - } - return x; - } - - private static void removeDecrease(User user) { - int x = 0; - // Ignore plugins that are creating NPCs with no names - if (user.getUUID() != null) { - if (DECREASE_LIST.get(user.getUUID()) != null) { - x = DECREASE_LIST.get(user.getUUID()); - x -= 2; - if (x < 0) { - x = 0; - } - } - DECREASE_LIST.put(user.getUUID(), x); - } - } - - public static void decrease(Player player) { - User user = getUserManager().getUser(player.getUniqueId()); - // Ignore plugins that are creating NPCs with no names - if (user.getUUID() != null) { - int x = 0; - - if (DECREASE_LIST.get(user.getUUID()) != null) { - x = DECREASE_LIST.get(user.getUUID()); - } - - x += 1; - DECREASE_LIST.put(user.getUUID(), x); - - if (x >= 10) { - user.decreaseLevel(); - DECREASE_LIST.put(user.getUUID(), 0); - } - } - } - - public static CheckManager getCheckManager() { - return CHECK_MANAGER; - } - - public static AntiCheatManager getManager() { - return AntiCheatReloaded.getManager(); - } - - public static Backend getBackend() { - return BACKEND; - } - - public static UserManager getUserManager() { - return USER_MANAGER; - } - - public static AntiCheatReloaded getPlugin() { - return PLUGIN; - } - - public static Configuration getConfig() { - return CONFIG; - } - - public static boolean silentMode() { - return CONFIG.getConfig().silentMode.getValue(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/InventoryListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/InventoryListener.java deleted file mode 100644 index 7aa35b4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/InventoryListener.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.event; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryOpenEvent; -import org.bukkit.event.inventory.InventoryType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.util.User; - -public class InventoryListener extends EventListener { - - @EventHandler - public void onInventoryClick(InventoryClickEvent event) { - if (!event.isRightClick() && !event.isShiftClick() && event.getWhoClicked() instanceof Player) { - Player player = (Player) event.getWhoClicked(); - if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) { - CheckResult result = getBackend().checkInventoryClicks(player); - if (result.failed()) { - if (!silentMode()) { - //getUserManager().getUser(player.getName()).restoreInventory(event.getInventory()); - player.getInventory().clear(); - event.setCancelled(true); - } - log(result.getMessage(), player, CheckType.FAST_INVENTORY, result.getSubCheck()); - } else { - decrease(player); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onInventoryOpen(InventoryOpenEvent event) { - if (event.getInventory().getType() != InventoryType.BEACON) { - getUserManager().getUser(event.getPlayer().getUniqueId()).setInventorySnapshot(event.getInventory().getContents()); - } - } - - @EventHandler - public void onInventoryClose(InventoryCloseEvent event) { - User user = getUserManager().getUser(event.getPlayer().getUniqueId()); - if (user != null) { - user.removeInventorySnapshot(); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java deleted file mode 100644 index ecaccab..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/PlayerListener.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.event; - -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Boat; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.ProjectileLaunchEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerAnimationEvent; -import org.bukkit.event.player.PlayerBedEnterEvent; -import org.bukkit.event.player.PlayerBedLeaveEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerKickEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerToggleFlightEvent; -import org.bukkit.event.player.PlayerToggleSneakEvent; -import org.bukkit.event.player.PlayerToggleSprintEvent; -import org.bukkit.event.player.PlayerVelocityEvent; -import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckResult; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.check.combat.VelocityCheck; -import com.rammelkast.anticheatreloaded.check.movement.AimbotCheck; -import com.rammelkast.anticheatreloaded.check.movement.BoatFlyCheck; -import com.rammelkast.anticheatreloaded.check.movement.ElytraCheck; -import com.rammelkast.anticheatreloaded.check.movement.FastLadderCheck; -import com.rammelkast.anticheatreloaded.check.movement.FlightCheck; -import com.rammelkast.anticheatreloaded.check.movement.SpeedCheck; -import com.rammelkast.anticheatreloaded.check.movement.StrafeCheck; -import com.rammelkast.anticheatreloaded.check.movement.WaterWalkCheck; -import com.rammelkast.anticheatreloaded.check.player.IllegalInteract; -import com.rammelkast.anticheatreloaded.util.Distance; -import com.rammelkast.anticheatreloaded.util.Permission; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; -import com.rammelkast.anticheatreloaded.util.VersionUtil; -import com.rammelkast.anticheatreloaded.util.XMaterial; - -public class PlayerListener extends EventListener { - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.COMMAND_SPAM) - && !Permission.getCommandExempt(player, event.getMessage().split(" ")[0])) { - CheckResult result = getBackend().checkCommandSpam(player, event.getMessage()); - if (result.failed()) { - event.setCancelled(!silentMode()); - if (!silentMode()) - player.sendMessage(ChatColor.translateAlternateColorCodes('&', result.getMessage())); - getBackend().processCommandSpammer(player); - log(null, player, CheckType.COMMAND_SPAM, result.getSubCheck()); - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { - if (!event.isFlying()) { - getBackend().logEnterExit(event.getPlayer()); - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { - if (event.getNewGameMode() != GameMode.CREATIVE) { - getBackend().logEnterExit(event.getPlayer()); - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent event) { - if (event.getEntity().getShooter() instanceof Player) { - Player player = (Player) event.getEntity().getShooter(); - - if (event.getEntity() instanceof Arrow) { - return; - } - - if (getCheckManager().willCheck(player, CheckType.FAST_PROJECTILE)) { - CheckResult result = getBackend().checkProjectile(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.FAST_PROJECTILE, result.getSubCheck()); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerTeleport(PlayerTeleportEvent event) { - getBackend().logTeleport(event.getPlayer()); - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerChangeWorlds(PlayerChangedWorldEvent event) { - getBackend().logTeleport(event.getPlayer()); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerToggleSneak(PlayerToggleSneakEvent event) { - Player player = event.getPlayer(); - if (event.isSneaking()) { - if (getCheckManager().willCheck(player, CheckType.SNEAK)) { - CheckResult result = getBackend().checkSneakToggle(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.SNEAK, result.getSubCheck()); - } - } - // getBackend().logToggleSneak(event.getPlayer()); - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerVelocity(PlayerVelocityEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.FLIGHT)) { - if (getBackend().justVelocity(player) && getBackend().extendVelocityTime(player)) { - event.setCancelled(!silentMode()); - return; - } - getBackend().logVelocity(player); - } - - // Part of Velocity check - User user = AntiCheatReloaded.getManager().getUserManager() - .getUser(event.getPlayer().getUniqueId()); - if (!user.getMovementManager().onGround) - return; - double motionY = event.getVelocity().getY(); - user.getMovementManager().velocityExpectedMotionY = motionY; - // End part of Velocity check - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - Player player = event.getPlayer(); - - if (getCheckManager().willCheck(player, CheckType.CHAT_SPAM)) { - CheckResult result = getBackend().checkChatSpam(player, event.getMessage()); - if (result.failed()) { - event.setCancelled(!silentMode()); - if (!result.getMessage().equals("") && !silentMode()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', result.getMessage())); - } - getBackend().processChatSpammer(player); - AntiCheatReloaded.sendToMainThread(new Runnable() { - @Override - public void run() { - log(null, player, CheckType.CHAT_SPAM, result.getSubCheck()); - } - }); - } - } - - if (getCheckManager().willCheck(player, CheckType.CHAT_UNICODE)) { - CheckResult result = getBackend().checkChatUnicode(player, event.getMessage()); - if (result.failed()) { - event.setCancelled(true); - player.sendMessage(ChatColor.translateAlternateColorCodes('&', result.getMessage())); - AntiCheatReloaded.sendToMainThread(new Runnable() { - @Override - public void run() { - log(null, player, CheckType.CHAT_UNICODE, result.getSubCheck()); - } - }); - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerKick(PlayerKickEvent event) { - getBackend().garbageClean(event.getPlayer()); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - getBackend().garbageClean(event.getPlayer()); - - User user = getUserManager().getUser(event.getPlayer().getUniqueId()); - - getConfig().getLevels().saveLevelFromUser(user); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerVehicleCollide(VehicleEntityCollisionEvent event) { - if (!(event.getVehicle() instanceof Boat) || !(event.getEntity() instanceof Player)) - return; - - Player player = (Player) event.getEntity(); - getBackend().logBoatCollision(player); - } - - @EventHandler - public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.SPRINT)) { - CheckResult result = getBackend().checkSprintHungry(event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.SPRINT, result.getSubCheck()); - } else { - decrease(player); - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerInteract(PlayerInteractEvent event) { - Player player = event.getPlayer(); - PlayerInventory inv = player.getInventory(); - if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { - ItemStack itemInHand; - if (VersionUtil.isBountifulUpdate()) { - itemInHand = VersionUtil.getItemInHand(player); - } else { - itemInHand = ((event.getHand() == EquipmentSlot.HAND) ? inv.getItemInMainHand() - : inv.getItemInOffHand()); - } - - if (itemInHand.getType() == Material.BOW) { - getBackend().logBowWindUp(player); - } else if (Utilities.isFood(itemInHand.getType()) || Utilities.isFood(itemInHand.getType())) { - getBackend().logEatingStart(player); - } - - if (!VersionUtil.isBountifulUpdate()) { - if (itemInHand.getType() == XMaterial.FIREWORK_ROCKET.parseMaterial()) { - ElytraCheck.JUMP_Y_VALUE.remove(player.getUniqueId()); - if (player.isGliding()) { - // TODO config max elytra height? - ElytraCheck.JUMP_Y_VALUE.put(player.getUniqueId(), 9999.99D); - } - } - } - } - - Block block = event.getClickedBlock(); - if (block != null - && (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { - if (getCheckManager().willCheck(player, CheckType.ILLEGAL_INTERACT)) { - CheckResult result = IllegalInteract.performCheck(player, event); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.ILLEGAL_INTERACT, result.getSubCheck()); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerDropItem(PlayerDropItemEvent event) { - Player player = event.getPlayer(); - if (getCheckManager().willCheck(player, CheckType.ITEM_SPAM)) { - CheckResult result = getBackend().checkFastDrop(player); - if (result.failed()) { - event.setCancelled(!silentMode()); - log(result.getMessage(), player, CheckType.ITEM_SPAM, result.getSubCheck()); - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerEnterBed(PlayerBedEnterEvent event) { - if (event.getBed().getType().name().endsWith("BED")) - return; - getBackend().logEnterExit(event.getPlayer()); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onPlayerExitBed(PlayerBedLeaveEvent event) { - if (event.getBed().getType().name().endsWith("BED")) - return; - getBackend().logEnterExit(event.getPlayer()); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerAnimation(PlayerAnimationEvent event) { - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - Player player = event.getPlayer(); - getBackend().logJoin(player); - - User user = new User(player.getUniqueId()); - user.setIsWaitingOnLevelSync(true); - getConfig().getLevels().loadLevelToUser(user); - getUserManager().addUser(user); - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - - if (player.hasPermission("anticheat.admin") && !AntiCheatReloaded.getUpdateManager().isLatest()) { - player.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.GRAY - + "Your version of AntiCheatReloaded is outdated! You can download " - + AntiCheatReloaded.getUpdateManager().getLatestVersion() - + " from the Spigot forums or DevBukkit."); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - final Player player = event.getPlayer(); - if (getCheckManager().checkInWorld(player) && !getCheckManager().isOpExempt(player)) { - final Location from = event.getFrom(); - final Location to = event.getTo(); - - final Distance distance = new Distance(from, to); - final double y = distance.getYDifference(); - - final User user = getUserManager().getUser(player.getUniqueId()); - user.setTo(to.getX(), to.getY(), to.getZ()); - user.getMovementManager().handle(player, from, to, distance); - - if (getCheckManager().willCheckQuick(player, CheckType.FLIGHT) && !VersionUtil.isFlying(player)) { - CheckResult result = FlightCheck.runCheck(player, distance); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.FLIGHT, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.ELYTRAFLY)) { - CheckResult result = ElytraCheck.runCheck(player, distance); - if (result.failed()) { - log(result.getMessage(), player, CheckType.ELYTRAFLY, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.BOATFLY)) { - CheckResult result = BoatFlyCheck.runCheck(player, user.getMovementManager(), to); - if (result.failed()) { - if (!silentMode()) { - player.eject(); - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.BOATFLY, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.VCLIP) - && event.getFrom().getY() > event.getTo().getY()) { - CheckResult result = getBackend().checkVClip(player, new Distance(event.getFrom(), event.getTo())); - if (result.failed()) { - if (!silentMode()) { - int data = result.getData() > 3 ? 3 : result.getData(); - Location newloc = new Location(player.getWorld(), event.getFrom().getX(), - event.getFrom().getY() + data, event.getFrom().getZ()); - if (newloc.getBlock().getType() == Material.AIR) { - event.setTo(newloc); - } else { - event.setTo(user.getGoodLocation(from.clone())); - } - player.damage(3); - } - log(result.getMessage(), player, CheckType.VCLIP, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.NOFALL) - && getCheckManager().willCheck(player, CheckType.FLIGHT) - && !Utilities.isClimbableBlock(player.getLocation().getBlock()) - && event.getFrom().getY() > event.getTo().getY()) { - CheckResult result = getBackend().checkNoFall(player, y); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - // TODO better handling of this - } - log(result.getMessage(), player, CheckType.NOFALL, result.getSubCheck()); - } - } - - if (event.getTo() != event.getFrom()) { - double x = distance.getXDifference(); - double z = distance.getZDifference(); - if (getCheckManager().willCheckQuick(player, CheckType.SPEED) - && getCheckManager().willCheck(player, CheckType.FLIGHT)) { - if (event.getFrom().getY() < event.getTo().getY()) { - CheckResult result = SpeedCheck.checkVerticalSpeed(player, distance); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPEED, result.getSubCheck()); - } - } - CheckResult result = SpeedCheck.checkXZSpeed(player, x, z, event.getTo()); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPEED, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.WATER_WALK)) { - CheckResult result = WaterWalkCheck.runCheck(player, x, y, z); - if (result.failed()) { - if (!silentMode()) { - // TODO check this - player.teleport(player.getLocation().clone().subtract(0, 0.52, 0)); - } - log(result.getMessage(), player, CheckType.WATER_WALK, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.SPIDER)) { - CheckResult result = getBackend().checkSpider(player, y); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.SPIDER, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.FASTLADDER)) { - // Does not use y value created before because that value is absolute - CheckResult result = FastLadderCheck.runCheck(player, - event.getTo().getY() - event.getFrom().getY()); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.FASTLADDER, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.STRAFE)) { - CheckResult result = StrafeCheck.runCheck(player, x, z, event.getFrom(), event.getTo()); - if (result.failed()) { - if (!silentMode()) { - event.setTo(user.getGoodLocation(from.clone())); - } - log(result.getMessage(), player, CheckType.STRAFE, result.getSubCheck()); - } - } - } - if (getCheckManager().willCheckQuick(player, CheckType.AIMBOT)) { - CheckResult result = AimbotCheck.runCheck(player, event); - if (result.failed()) { - log(result.getMessage(), player, CheckType.AIMBOT, result.getSubCheck()); - } - } - if (getCheckManager().willCheckQuick(player, CheckType.VELOCITY)) { - CheckResult result = VelocityCheck.runCheck(player, distance); - if (result.failed()) { - log(result.getMessage(), player, CheckType.VELOCITY, result.getSubCheck()); - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onRespawn(PlayerRespawnEvent event) { - getBackend().logTeleport(event.getPlayer()); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java deleted file mode 100644 index 765f8fa..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/event/VehicleListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.event; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.vehicle.VehicleDestroyEvent; -import org.bukkit.event.vehicle.VehicleEnterEvent; -import org.bukkit.event.vehicle.VehicleExitEvent; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -public class VehicleListener extends EventListener { - - @EventHandler(ignoreCancelled = true) - public void onVehicleEnter(VehicleEnterEvent event) { - if (event.getEntered() instanceof Player) { - getBackend().logEnterExit((Player) event.getEntered()); - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @EventHandler(ignoreCancelled = true) - public void onVehicleExit(VehicleExitEvent event) { - if (event.getExited() instanceof Player) { - getBackend().logEnterExit((Player) event.getExited()); - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } - - @SuppressWarnings("deprecation") - @EventHandler(ignoreCancelled = true) - public void onVehicleDestroy(VehicleDestroyEvent event) { - if (VersionUtil.isBountifulUpdate()) { - if (event.getVehicle().getPassenger() != null) { - Entity entity = event.getVehicle().getPassenger(); - if (entity instanceof Player) { - getBackend().logEnterExit((Player) entity); - } - } - } else { - if (!event.getVehicle().getPassengers().isEmpty()) { - for (Entity entity : event.getVehicle().getPassengers()) { - if (entity instanceof Player) { - getBackend().logEnterExit((Player) entity); - } - } - } - } - - AntiCheatReloaded.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/AntiCheatManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/AntiCheatManager.java deleted file mode 100644 index 0ffac73..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/AntiCheatManager.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details.- - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.manage; - -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; - -import org.bukkit.plugin.RegisteredListener; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.Backend; -import com.rammelkast.anticheatreloaded.config.Configuration; - -/** - * The internal hub for all managers. - */ -public class AntiCheatManager { - private static AntiCheatReloaded plugin = null; - private static Configuration configuration; - private static UserManager userManager = null; - private static CheckManager checkManager = null; - private static LoggingManager loggingManager = null; - private static Backend backend = null; - private static Map eventchains = new ConcurrentHashMap(); - private static Map eventcache = new ConcurrentHashMap(); - - public AntiCheatManager(AntiCheatReloaded instance, Logger logger) { - plugin = instance; - configuration = new Configuration(plugin, this); - loggingManager = new LoggingManager(plugin, logger, configuration); - userManager = new UserManager(this); - checkManager = new CheckManager(this); - backend = new Backend(this); - } - - public void log(String message) { - loggingManager.log(message); - } - - public void debugLog(String message) { - loggingManager.debugLog(message); - } - - public void playerLog(String message) { - loggingManager.logToPlayers(message); - } - - public void addEvent(String e, RegisteredListener[] arr) { - if (!configuration.getConfig().eventChains.getValue()) - return; - if (!eventcache.containsKey(e) || eventcache.get(e) > 30000L) { - eventchains.put(e, arr); - eventcache.put(e, System.currentTimeMillis()); - } - } - - public String getEventChainReport() { - String gen = ""; - if (!configuration.getConfig().eventChains.getValue()) { - return "Event Chains is disabled by the configuration." + '\n'; - } - - if (eventchains.entrySet().size() == 0) { - return "No event chains found." + '\n'; - } - - for (Entry e : eventchains.entrySet()) { - String toadd = ""; - String ename = e.getKey(); - - toadd += ename + ":" + '\n'; - - RegisteredListener[] reg = e.getValue(); - for (RegisteredListener plug : reg) { - String pluginname = plug.getPlugin().getName(); - if (pluginname.equals("AntiCheat")) - pluginname = "self"; - - toadd += "- " + pluginname + '\n'; - } - - gen += toadd + '\n'; - } - - return gen; - } - - public AntiCheatReloaded getPlugin() { - return plugin; - } - - public Configuration getConfiguration() { - return configuration; - } - - public UserManager getUserManager() { - return userManager; - } - - public CheckManager getCheckManager() { - return checkManager; - } - - public Backend getBackend() { - return backend; - } - - public LoggingManager getLoggingManager() { - return loggingManager; - } - - public static void close() { - loggingManager.closeHandler(); - - if (configuration.getConfig().enterprise.getValue()) { - configuration.getEnterprise().database.shutdown(); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java deleted file mode 100644 index ecd5378..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/CheckManager.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.manage; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.util.VersionUtil; - -/** - *

- * The manager that AntiCheat will check with to see if it should watch certain checks and certain players. - */ - -public class CheckManager { - private AntiCheatManager manager = null; - private Configuration config; - private static List checkIgnoreList = new ArrayList(); - private static Map> exemptList = new HashMap>(); - - public CheckManager(AntiCheatManager manager) { - this.manager = manager; - this.config = manager.getConfiguration(); - this.loadCheckIgnoreList(this.config); - } - - public void loadCheckIgnoreList(Configuration configuration) { - checkIgnoreList.clear(); - for (CheckType type : CheckType.values()) { - if (!configuration.getChecks().isEnabled(type)) { - checkIgnoreList.add(type); - } - } - - if (!checkIgnoreList.isEmpty()) { - Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.DARK_GRAY + "> " + ChatColor.GRAY - + checkIgnoreList.size() + " check(s) have been disabled"); - } - } - - /** - * Turn a check on - * - * @param type The CheckType to enable - */ - public void activateCheck(CheckType type, String className) { - if (!isActive(type)) { - manager.getLoggingManager().logFineInfo("The " + type.toString() + " check was activated by " + className + "."); - checkIgnoreList.remove(type); - } - } - - /** - * Turn a check off - * - * @param type The CheckType to disable - */ - public void deactivateCheck(CheckType type, String className) { - if (isActive(type)) { - manager.getLoggingManager().logFineInfo("The " + type.toString() + " check was deactivated by " + className + "."); - checkIgnoreList.add(type); - } - } - - /** - * Determine whether a check is enabled - * - * @param type The CheckType to check - * @return true if the check is active - */ - public boolean isActive(CheckType type) { - return !checkIgnoreList.contains(type); - } - - /** - * Exempt a player from a check - * - * @param player The player - * @param type The check - */ - public void exemptPlayer(Player player, CheckType type, String className) { - if (!isExempt(player, type)) { - if (!exemptList.containsKey(player.getUniqueId())) { - exemptList.put(player.getUniqueId(), new ArrayList()); - } - manager.getLoggingManager().logFineInfo(player.getName() + " was exempted from the " + type.toString() + " check by " + className + "."); - exemptList.get(player.getUniqueId()).add(type); - } - } - - /** - * Unexempt a player from a check - * - * @param player The player - * @param type The check - */ - public void unexemptPlayer(Player player, CheckType type, String className) { - if (isExempt(player, type)) { - manager.getLoggingManager().logFineInfo(player.getName() + " was unexempted from the " + type.toString() + " check by " + className + "."); - exemptList.get(player.getUniqueId()).remove(type); - } - } - - /** - * Determine whether a player is exempt from a check - * - * @param player The player - * @param type The check - */ - public boolean isExempt(Player player, CheckType type) { - return exemptList.containsKey(player.getUniqueId()) ? exemptList.get(player.getUniqueId()).contains(type) : false; - } - - /** - * Determine whether a player is exempt from all checks from op status - * - * @param player The player - */ - public boolean isOpExempt(Player player) { - return (this.manager.getConfiguration().getConfig().exemptOp.getValue() && player.isOp()); - } - - /** - * Determine whether a player should be checked in their world - * - * @param player The player - * @return true if the player's world is enabled - */ - public boolean checkInWorld(Player player) { - return !config.getConfig().disabledWorlds.getValue().contains(player.getWorld().getName()); - } - - /** - * Run a quick version of the "willCheck" method, using the other non-check-specific methods beforehand - * - * @param player The player to check - * @param type The check being run - * @return true if the check should run - */ - public boolean willCheckQuick(Player player, CheckType type) { - return - isActive(type) - && !isExempt(player, type) - && !type.checkPermission(player); - } - - /** - * Determine whether a check should run on a player - * - * @param player The player to check - * @param type The check being run - * @return true if the check should run - */ - public boolean willCheck(Player player, CheckType type) { - boolean check = isActive(type) - && checkInWorld(player) - && !isExempt(player, type) - && !type.checkPermission(player) - && !isOpExempt(player); - if ((type == CheckType.FLIGHT || type == CheckType.SPEED) && VersionUtil.isFlying(player)) - return false; - return check; - } - - /** - * Determine whether a player is actually online; not an NPC - * - * @param player Player to check - * @return true if the player is a real person - */ - public boolean isOnline(Player player) { - // Check if the player is on the user list, e.g. is not an NPC - for (Player p : Bukkit.getOnlinePlayers()) { - if (p.getUniqueId().equals(player.getUniqueId())) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/LoggingManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/LoggingManager.java deleted file mode 100644 index ffb5c03..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/LoggingManager.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.manage; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.util.FileFormatter; -import com.rammelkast.anticheatreloaded.util.Permission; - -import java.io.File; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class LoggingManager { - - private final Logger fileLogger; - private static Handler fileHandler; - private static List logs = new CopyOnWriteArrayList(); - private final Configuration config; - - public LoggingManager(AntiCheatReloaded plugin, Logger logger, Configuration config) { - this.fileLogger = Logger.getLogger("com.rammelkast.anticheatreloaded.AntiCheatReloaded"); - this.config = config; - try { - File file = new File(plugin.getDataFolder(), "log"); - if (!file.exists()) { - file.mkdir(); - } - fileHandler = new FileHandler(plugin.getDataFolder() + "/log/anticheat.log", true); - fileHandler.setFormatter(new FileFormatter()); - } catch (Exception ex) { - logger.log(Level.SEVERE, null, ex); - } - fileLogger.setUseParentHandlers(false); - fileLogger.addHandler(fileHandler); - } - - public void log(String message) { - if (config.getConfig().logToConsole.getValue()) { - logToConsole(message); - } - if (config.getConfig().logToFile.getValue()) { - logToFile(message); - } - logToLogs(message); - } - - public void debugLog(String message) { - Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "ACR " + ChatColor.GRAY + message); - logToLogs(message); - } - - public void logToConsole(String message) { - Bukkit.getConsoleSender().sendMessage(message); - } - - public void logToFile(String message) { - fileLogger.info(ChatColor.stripColor(message)); - } - - public void logFineInfo(String message) { - logToFile(message); - logToLogs(message); - } - - public void logToPlayers(String message) { - if(config.getConfig().disableBroadcast.getValue()) return; - for(Player player : Bukkit.getOnlinePlayers()) { - if (Permission.SYSTEM_NOTICE.get(player)) { - player.sendMessage(message); - } - } - } - - private void logToLogs(String message) { // Yo dawg, you like logs? - logs.add(ChatColor.stripColor(message)); - } - - public List getLastLogs() { - List log = new CopyOnWriteArrayList(); - if (logs.size() < 30) { - return logs; - } - for (int i = logs.size() - 1; i >= 0; i--) { - log.add(logs.get(i)); - } - logs.clear(); - return log; - } - - public void closeHandler() { - fileHandler.close(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/manage/UserManager.java b/src/main/java/com/rammelkast/anticheatreloaded/manage/UserManager.java deleted file mode 100644 index c522cac..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/manage/UserManager.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.manage; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.BanList.Type; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.util.Group; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -public class UserManager { - private List users = new ArrayList(); - private AntiCheatManager manager; - private Configuration config; - /** - * Initialize the user manager - * - * @param manager The AntiCheat Manager - */ - public UserManager(AntiCheatManager manager) { - this.manager = manager; - this.config = manager.getConfiguration(); - } - - /** - * Get a user with the given UUID - * - * @param uuid UUID - * @return User with UUID - */ - public User getUser(UUID uuid) { - for (User user : users) { - if (user.getUUID().equals(uuid)) { - return user; - } - } - // Otherwise try to load them - User user = new User(uuid); - user.setIsWaitingOnLevelSync(true); - config.getLevels().loadLevelToUser(user); - return user; - } - - /** - * Get all users - * - * @return List of users - */ - public List getUsers() { - return users; - } - - /** - * Add a user to the list - * - * @param user User to add - */ - public void addUser(User user) { - users.add(user); - } - - /** - * Remove a user from the list - * - * @param user User to remove - */ - public void remove(User user) { - users.remove(user); - } - - /** - * Save a user's level - * - * @param user User to save - */ - public void saveLevel(User user) { - config.getLevels().saveLevelFromUser(user); - } - - /** - * Get users in group - * - * @param group Group to find users of - */ - public List getUsersInGroup(Group group) { - List list = new ArrayList(); - for (User u : users) { - if (u.getGroup() == group) { - list.add(u); - } - } - return list; - } - - /** - * Get a user's level, or 0 if the player isn't found - * - * @param uuid UUID of the player - * @return player level - */ - public int safeGetLevel(UUID uuid) { - User user = getUser(uuid); - if (user == null) { - return 0; - } else { - return user.getLevel(); - } - } - - /** - * Set a user's level - * - * @param uuid UUID of the player - * @param level Group to set - */ - public void safeSetLevel(UUID uuid, int level) { - User user = getUser(uuid); - if (user != null) { - user.setLevel(level); - } - } - - /** - * Reset a user - * - * @param uuid UUID of the user - */ - public void safeReset(UUID uuid) { - User user = getUser(uuid); - if (user != null) { - user.resetLevel(); - } - } - - /** - * Fire an alert - * - * @param user The user to alert - * @param group The user's group - * @param type The CheckType that triggered the alert - */ - public void alert(User user, Group group, CheckType type) { - execute(user, group.getActions(), type); - } - - /** - * Execute configuration actions for an alert - * - * @param user The user - * @param actions The list of actions to execute - * @param type The CheckType that triggered the alert - */ - public void execute(User user, List actions, CheckType type) { - execute(user, actions, type, config.getLang().KICK_REASON(), config.getLang().WARNING(), config.getLang().BAN_REASON()); - } - - /** - * Execute configuration actions for an alert - * - * @param user The user - * @param actions The list of actions to execute - * @param type The CheckType that triggered the alert - * @param kickReason The config's kick reason - * @param warning The config's warning format - * @param banReason The config's ban reason - */ - public void execute(final User user, final List actions, final CheckType type, final String kickReason, final List warning, final String banReason) { - // Execute synchronously for thread safety when called from AsyncPlayerChatEvent - Bukkit.getScheduler().scheduleSyncDelayedTask(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - if (user.getPlayer() == null) { - return; - } - final String name = user.getName(); - for (String event : actions) { - event = event.replaceAll("%player%", name).replaceAll("%world%", user.getPlayer().getWorld().getName()).replaceAll("%check%", type.name()); - - if (event.startsWith("COMMAND[")) { - for (String cmd : Utilities.getCommands(event)) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); - } - } else if (event.equalsIgnoreCase("KICK")) { - user.getPlayer().kickPlayer(ChatColor.translateAlternateColorCodes('&', kickReason)); - AntiCheatReloaded.getPlugin().onPlayerKicked(); - String msg = ChatColor.translateAlternateColorCodes('&', config.getLang().KICK_BROADCAST().replaceAll("%player%", name) + " (" + type.getName() + ")"); - if (!msg.equals("")) { - manager.log(msg); - manager.playerLog(msg); - } - } else if (event.equalsIgnoreCase("WARN")) { - List message = warning; - for (String string : message) { - if (!string.equals("")) { - user.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); - } - } - } else if (event.equalsIgnoreCase("BAN")) { - Bukkit.getBanList(Type.NAME).addBan(user.getPlayer().getName(), ChatColor.translateAlternateColorCodes('&', banReason), null, null); - user.getPlayer().kickPlayer(ChatColor.translateAlternateColorCodes('&', banReason)); - String msg = ChatColor.translateAlternateColorCodes('&', config.getLang().BAN_BROADCAST().replaceAll("%player%", name) + " (" + type.getName() + ")"); - if (!msg.equals("")) { - manager.log(msg); - manager.playerLog(msg); - } - } else if (event.equalsIgnoreCase("RESET")) { - user.resetLevel(); - } - } - } - }); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java b/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java deleted file mode 100644 index a85648d..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java +++ /dev/null @@ -1,766 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.metrics; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -import javax.net.ssl.HttpsURLConnection; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.plugin.ServicePriority; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; - -/** - * bStats collects some data for plugin authors. - *

- * Check out https://bStats.org/ to learn more about bStats! - */ -public class Metrics { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null - || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this - // little "trick" ... :D - final String defaultPackage = new String( - new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't' }); - final String examplePackage = new String( - new byte[] { 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e' }); - // We want to make sure nobody just copy & pastes the example and use the wrong - // package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) - || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final Plugin plugin; - - // The plugin id - private final int pluginId; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - * @param pluginId The id of the plugin. It can be found at - * What is my - * plugin id? - */ - public Metrics(Plugin plugin, int pluginId) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - this.pluginId = pluginId; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" - + "To honor their work, you should not disable it.\n" - + "This has nearly no effect on the server performance!\n" - + "Check out https://bStats.org/ to learn more :)") - .copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } - - // Load the data - enabled = config.getBoolean("enabled", true); - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - if (enabled) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { - } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to - // use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the - // stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other - // plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be - // blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("id", pluginId); // Append the id of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - JsonArray customCharts = new JsonArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JsonObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.add("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { // old bstats version compatibility - try { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } catch (ClassNotFoundException e) { - // minecraft version 1.14+ - if (logFailedRequests) { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); - } - } - } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException - | InvocationTargetException ignored) { - } - } - } catch (NoSuchFieldException ignored) { - } - } - - data.add("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(() -> { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - private JsonObject getRequestJsonObject() { - JsonObject chart = new JsonObject(); - chart.addProperty("chartId", chartId); - try { - JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.add("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JsonObject getChartData() throws Exception; - - } - - /** - * Represents a custom simple pie. - */ - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom drilldown pie. - */ - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObject value = new JsonObject(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - value.addProperty(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - values.add(entryValues.getKey(), value); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.addProperty("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.addProperty(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JsonArray categoryValues = new JsonArray(); - categoryValues.add(new JsonPrimitive(entry.getValue())); - values.add(entry.getKey(), categoryValues); - } - data.add("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObject getChartData() throws Exception { - JsonObject data = new JsonObject(); - JsonObject values = new JsonObject(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JsonArray categoryValues = new JsonArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(new JsonPrimitive(categoryValue)); - } - values.add(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.add("values", values); - return data; - } - } - -} \ No newline at end of file diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java deleted file mode 100644 index 1ad8d77..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Distance.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.Location; - -public class Distance { - private final double l1Y; - private final double l2Y; - - private final double XDiff; - private final double YDiff; - private final double ZDiff; - - private final Location from; - private final Location to; - - public Distance(Location from, Location to) { - l1Y = to.getY(); - l2Y = from.getY(); - - XDiff = Math.abs(to.getX() - from.getX()); - ZDiff = Math.abs(to.getZ() - from.getZ()); - YDiff = Math.abs(l1Y - l2Y); - - this.from = from; - this.to = to; - } - - public Distance() { - l1Y = 0; - l2Y = 0; - - XDiff = 0; - ZDiff = 0; - YDiff = 0; - - this.from = null; - this.to = null; - } - - public double fromY() { - return l2Y; - } - - public double toY() { - return l1Y; - } - - public double getXDifference() { - return XDiff; - } - - public double getZDifference() { - return ZDiff; - } - - public double getYDifference() { - return YDiff; - } - - public Location getFrom() { - return this.from; - } - - public Location getTo() { - return this.to; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java b/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java deleted file mode 100644 index 221e4ae..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/FileFormatter.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.logging.Formatter; -import java.util.logging.LogRecord; - -public class FileFormatter extends Formatter { - private static final DateFormat FORMAT = new SimpleDateFormat("h:mm:ss"); - private static final String LINE_SEP = System.getProperty("line.separator"); - - @Override - public String format(LogRecord record) { - StringBuilder output = new StringBuilder().append("[").append(record.getLevel()).append('|') - .append(FORMAT.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()) - .append(' ').append(LINE_SEP); - return output.toString(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java deleted file mode 100644 index 4a452d3..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Group.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.ChatColor; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Group { - - private String name; - private int level; - private ChatColor color = ChatColor.RED; - private List actions = new ArrayList(); - - public Group(String name, int level, String color, List actions) { - - this.name = name; - this.level = level; - this.actions = actions; - - ChatColor c = ChatColor.valueOf(color); - if (c == null) { - AntiCheatReloaded.getPlugin().getLogger() - .warning("Event '" + name + "' was initialized with the color '" + color + "' which is invalid."); - AntiCheatReloaded.getPlugin().getLogger().warning( - "This event will not run properly. See http://jd.bukkit.org/apidocs/org/bukkit/ChatColor.html#enum_constant_summary for a list of valid colors"); - } else { - this.color = c; - } - } - - public String getName() { - return name; - } - - public int getLevel() { - return level; - } - - public ChatColor getColor() { - return color; - } - - public List getActions() { - return actions; - } - - public static Group load(String string) { - try { - if (string.split(" : ").length == 4) { - String name = string.split(" : ")[0]; - int level = Integer.parseInt(string.split(" : ")[1]); - String color = string.split(" : ")[2]; - List actions = Arrays.asList(string.split(" : ")[3].split(",")); - return new Group(name, level, color, actions); - } else { - throw new Exception(); - } - } catch (Exception ex) { - AntiCheatReloaded.getPlugin().getLogger() - .warning("An event was initialized with an invalid string: '" + string + "'"); - AntiCheatReloaded.getPlugin().getLogger().warning( - "The proper format is: 'name : threshold : color : action' such as 'High : 50 : RED : KICK'"); - AntiCheatReloaded.getPlugin().getLogger().warning("This event will NOT run. (" + ex.getMessage() + ")"); - return null; - } - } - - @Override - public String toString() { - return name + " : " + level + " : " + color.name() + " : " + Utilities.listToCommaString(actions); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/MinecraftVersion.java b/src/main/java/com/rammelkast/anticheatreloaded/util/MinecraftVersion.java deleted file mode 100644 index 8df9d9c..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/MinecraftVersion.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2012 Kristian S. Stangeland - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA - */ - -package com.rammelkast.anticheatreloaded.util; - -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.Server; - -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.utility.SnapshotVersion; -import com.google.common.base.Objects; -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.Ordering; - -/** - * Determine the current Minecraft version. - * - * @author Kristian - */ -public class MinecraftVersion implements Comparable, Serializable { - private static final long serialVersionUID = 1L; - - /** - * Regular expression used to parse version strings. - */ - private static final Pattern VERSION_PATTERN = Pattern.compile(".*\\(.*MC.\\s*([a-zA-z0-9\\-.]+).*"); - - /** - * Version 1.16.2 - breaking change to the nether update - */ - public static final MinecraftVersion NETHER_UPDATE_2 = new MinecraftVersion("1.16.2"); - - /** - * Version 1.16.0 - the nether update - */ - public static final MinecraftVersion NETHER_UPDATE = new MinecraftVersion("1.16"); - - /** - * Version 1.15 - the bee update - */ - public static final MinecraftVersion BEE_UPDATE = new MinecraftVersion("1.15"); - - /** - * Version 1.14 - village and pillage update. - */ - public static final MinecraftVersion VILLAGE_UPDATE = new MinecraftVersion("1.14"); - - /** - * Version 1.13 - update aquatic. - */ - public static final MinecraftVersion AQUATIC_UPDATE = new MinecraftVersion("1.13"); - - /** - * Version 1.12 - the world of color update. - */ - public static final MinecraftVersion COLOR_UPDATE = new MinecraftVersion("1.12"); - - /** - * Version 1.11 - the exploration update. - */ - public static final MinecraftVersion EXPLORATION_UPDATE = new MinecraftVersion("1.11"); - - /** - * Version 1.10 - the frostburn update. - */ - public static final MinecraftVersion FROSTBURN_UPDATE = new MinecraftVersion("1.10"); - - /** - * Version 1.9 - the combat update. - */ - public static final MinecraftVersion COMBAT_UPDATE = new MinecraftVersion("1.9"); - - /** - * Version 1.8 - the "bountiful" update. - */ - public static final MinecraftVersion BOUNTIFUL_UPDATE = new MinecraftVersion("1.8"); - - /** - * Version 1.7.8 - the update that changed the skin format (and distribution - R.I.P. player disguise) - */ - public static final MinecraftVersion SKIN_UPDATE = new MinecraftVersion("1.7.8"); - - /** - * Version 1.7.2 - the update that changed the world. - */ - public static final MinecraftVersion WORLD_UPDATE = new MinecraftVersion("1.7.2"); - - /** - * Version 1.6.1 - the horse update. - */ - public static final MinecraftVersion HORSE_UPDATE = new MinecraftVersion("1.6.1"); - - /** - * Version 1.5.0 - the redstone update. - */ - public static final MinecraftVersion REDSTONE_UPDATE = new MinecraftVersion("1.5.0"); - - /** - * Version 1.4.2 - the scary update (Wither Boss). - */ - public static final MinecraftVersion SCARY_UPDATE = new MinecraftVersion("1.4.2"); - - private final int major; - private final int minor; - private final int build; - private Boolean atLeast; - - // The development stage - private final String development; - - // Snapshot? - private final SnapshotVersion snapshot; - - /** - * Determine the current Minecraft version. - * @param server - the Bukkit server that will be used to examine the MC version. - */ - public MinecraftVersion(Server server) { - this(extractVersion(server.getVersion())); - } - - /** - * Construct a version object from the format major.minor.build, or the snapshot format. - * @param versionOnly - the version in text form. - */ - public MinecraftVersion(String versionOnly) { - this(versionOnly, true); - } - - /** - * Construct a version format from the standard release version or the snapshot verison. - * @param versionOnly - the version. - * @param parseSnapshot - TRUE to parse the snapshot, FALSE otherwise. - */ - private MinecraftVersion(String versionOnly, boolean parseSnapshot) { - String[] section = versionOnly.split("-"); - SnapshotVersion snapshot = null; - int[] numbers = new int[3]; - - try { - numbers = parseVersion(section[0]); - - } catch (NumberFormatException cause) { - // Skip snapshot parsing - if (!parseSnapshot) - throw cause; - - try { - // Determine if the snapshot is newer than the current release version - snapshot = new SnapshotVersion(section[0]); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US); - - MinecraftVersion latest = new MinecraftVersion(ProtocolLibrary.MAXIMUM_MINECRAFT_VERSION, false); - boolean newer = snapshot.getSnapshotDate().compareTo( - format.parse(ProtocolLibrary.MINECRAFT_LAST_RELEASE_DATE)) > 0; - - numbers[0] = latest.getMajor(); - numbers[1] = latest.getMinor() + (newer ? 1 : -1); - numbers[2] = 0; - } catch (Exception e) { - throw new IllegalStateException("Cannot parse " + section[0], e); - } - } - - this.major = numbers[0]; - this.minor = numbers[1]; - this.build = numbers[2]; - this.development = section.length > 1 ? section[1] : (snapshot != null ? "snapshot" : null); - this.snapshot = snapshot; - } - - /** - * Construct a version object directly. - * @param major - major version number. - * @param minor - minor version number. - * @param build - build version number. - */ - public MinecraftVersion(int major, int minor, int build) { - this(major, minor, build, null); - } - - /** - * Construct a version object directly. - * @param major - major version number. - * @param minor - minor version number. - * @param build - build version number. - * @param development - development stage. - */ - public MinecraftVersion(int major, int minor, int build, String development) { - this.major = major; - this.minor = minor; - this.build = build; - this.development = development; - this.snapshot = null; - } - - private int[] parseVersion(String version) { - String[] elements = version.split("\\."); - int[] numbers = new int[3]; - - // Make sure it's even a valid version - if (elements.length < 1) - throw new IllegalStateException("Corrupt MC version: " + version); - - // The String 1 or 1.2 is interpreted as 1.0.0 and 1.2.0 respectively. - for (int i = 0; i < Math.min(numbers.length, elements.length); i++) - numbers[i] = Integer.parseInt(elements[i].trim()); - return numbers; - } - - /** - * Major version number - * @return Current major version number. - */ - public int getMajor() { - return major; - } - - /** - * Minor version number - * @return Current minor version number. - */ - public int getMinor() { - return minor; - } - - /** - * Build version number - * @return Current build version number. - */ - public int getBuild() { - return build; - } - - /** - * Retrieve the development stage. - * @return Development stage, or NULL if this is a release. - */ - public String getDevelopmentStage() { - return development; - } - - /** - * Retrieve the snapshot version, or NULL if this is a release. - * @return The snapshot version. - */ - public SnapshotVersion getSnapshot() { - return snapshot; - } - - /** - * Determine if this version is a snapshot. - * @return The snapshot version. - */ - public boolean isSnapshot() { - return snapshot != null; - } - - public boolean atOrAbove() { - if (atLeast == null) { - atLeast = MinecraftVersion.atOrAbove(this); - } - - return atLeast; - } - - /** - * Retrieve the version String (major.minor.build) only. - * @return A normal version string. - */ - public String getVersion() { - if (getDevelopmentStage() == null) - return String.format("%s.%s.%s", getMajor(), getMinor(), getBuild()); - else - return String.format("%s.%s.%s-%s%s", getMajor(), getMinor(), getBuild(), - getDevelopmentStage(), isSnapshot() ? snapshot : ""); - } - - @Override - public int compareTo(MinecraftVersion o) { - if (o == null) - return 1; - - return ComparisonChain.start(). - compare(getMajor(), o.getMajor()). - compare(getMinor(), o.getMinor()). - compare(getBuild(), o.getBuild()). - // No development String means it's a release - compare(getDevelopmentStage(), o.getDevelopmentStage(), Ordering.natural().nullsLast()). - compare(getSnapshot(), o.getSnapshot(), Ordering.natural().nullsFirst()). - result(); - } - - public boolean isAtLeast(MinecraftVersion other) { - if (other == null) - return false; - - return compareTo(other) >= 0; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (obj == this) - return true; - - if (obj instanceof MinecraftVersion) { - MinecraftVersion other = (MinecraftVersion) obj; - - return getMajor() == other.getMajor() && - getMinor() == other.getMinor() && - getBuild() == other.getBuild() && - Objects.equal(getDevelopmentStage(), other.getDevelopmentStage()); - } - - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(getMajor(), getMinor(), getBuild()); - } - - @Override - public String toString() { - // Convert to a String that we can parse back again - return String.format("(MC: %s)", getVersion()); - } - - /** - * Extract the Minecraft version from CraftBukkit itself. - * @param text - the server version in text form. - * @return The underlying MC version. - * @throws IllegalStateException If we could not parse the version string. - */ - public static String extractVersion(String text) { - Matcher version = VERSION_PATTERN.matcher(text); - - if (version.matches() && version.group(1) != null) { - return version.group(1); - } else { - throw new IllegalStateException("Cannot parse version String '" + text + "'"); - } - } - - /** - * Parse the given server version into a Minecraft version. - * @param serverVersion - the server version. - * @return The resulting Minecraft version. - */ - public static MinecraftVersion fromServerVersion(String serverVersion) { - return new MinecraftVersion(extractVersion(serverVersion)); - } - - private static MinecraftVersion currentVersion; - - public static void setCurrentVersion(MinecraftVersion version) { - currentVersion = version; - } - - public static MinecraftVersion getCurrentVersion() { - if (currentVersion == null) { - currentVersion = fromServerVersion(Bukkit.getVersion()); - } - - return currentVersion; - } - - public static boolean atOrAbove(MinecraftVersion version) { - return getCurrentVersion().isAtLeast(version); - } -} \ No newline at end of file diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/MovementManager.java b/src/main/java/com/rammelkast/anticheatreloaded/util/MovementManager.java deleted file mode 100644 index 6a900a6..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/MovementManager.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; - -public class MovementManager { - - // Ticks in air - public int airTicks = 0; - // Ticks on ground - public int groundTicks = 0; - // Ticks on ice - public int iceTicks = 0; - // Ticks on slime - public int slimeTicks = 0; - // Ticks in air before last grounded moment - public int airTicksBeforeGrounded = 0; - // Ticks influenced by ice - public int iceInfluenceTicks = 0; - // Ticks influenced by slime - public int slimeInfluenceTicks = 0; - // Y motion of the movement - public double motionY; - // Previous Y motion of the movement - public double lastMotionY; - // Horizontal distance of movement - public double distanceXZ; - // Horizontal distance on x-axis of movement - public double distanceX; - // Horizontal distance on z-axis of movement - public double distanceZ; - // Previous horizontal distance of movement - public double lastDistanceXZ; - // Previous horizontal distance on x-axis of movement - public double lastDistanceX; - // Previous horizontal distance on z-axis of movement - public double lastDistanceZ; - // If the player touched the ground again this tick - public boolean touchedGroundThisTick = false; - // Last recorded distance - public Distance lastDistance = new Distance(); - // Movement acceleration - public double acceleration; - // Is the block above solid - public boolean topSolid; - // Is the block below solid - public boolean bottomSolid; - // If the current movement is up a slab or stair - public boolean halfMovement; - // If the player is on the ground (determined clientside!) - public boolean onGround; - // Ticks counter for last halfMovement - public int halfMovementHistoryCounter = 0; - // Time of last teleport - public long lastTeleport; - // Elytra effect ticks - public int elytraEffectTicks; - // Used by Velocity check, represents the currently expected Y motion - public double velocityExpectedMotionY; - // Amount of ticks a player is sneaking - public int sneakingTicks; - // Ticks counter after being near a liquid - public int nearLiquidTicks; - // Ticks of player blocking - public int blockingTicks; - // If the player has a speed effect - public boolean hasSpeedEffect = false; - // If the player had speed effect previous tick - public boolean hadSpeedEffect = false; - // Time of last update - public long lastUpdate; - - @SuppressWarnings("deprecation") - public void handle(Player player, Location from, Location to, Distance distance) { - // TODO as of now, we "trust" the client to send the right thing - // This is checked for spoofing by "GroundFlight" - // Also seems to make NoFall cheats flag for speed lmao - this.onGround = player.isOnGround(); - - double x = distance.getXDifference(); - double z = distance.getZDifference(); - this.lastDistanceXZ = this.distanceXZ; - this.lastDistanceX = this.distanceX; - this.lastDistanceZ = this.distanceZ; - this.distanceXZ = Math.sqrt(x * x + z * z); - this.distanceX = x; - this.distanceZ = z; - - // Account for standing on boat - if (Utilities.couldBeOnBoat(player, 0.25, true) && !Utilities.isSubmersed(player)) - this.onGround = true; - - // Handle 1.9+ potion effects - if (MinecraftVersion.atOrAbove(MinecraftVersion.COMBAT_UPDATE)) { - for (PotionEffect effect : player.getActivePotionEffects()) { - if (!VersionUtil.isLevitationEffect(effect)) - return; - AntiCheatReloaded.getManager().getBackend().logLevitating(player, 1); - } - } - - this.touchedGroundThisTick = false; - this.halfMovement = false; - if (!this.onGround) { - this.groundTicks = 0; - this.airTicks++; - } else { - if (this.airTicks > 0) - this.touchedGroundThisTick = true; - this.airTicksBeforeGrounded = this.airTicks; - this.airTicks = 0; - this.groundTicks++; - } - - if (Utilities.couldBeOnIce(to)) { - this.iceTicks++; - this.iceInfluenceTicks = 60; - } else { - this.iceTicks = 0; - if (this.iceInfluenceTicks > 0) - this.iceInfluenceTicks--; - } - - if (Utilities.couldBeOnSlime(to)) { - this.slimeTicks++; - this.slimeInfluenceTicks = 40; - } else { - this.slimeTicks = 0; - if (this.slimeInfluenceTicks > 0) - this.slimeInfluenceTicks--; - } - - if (VersionUtil.isGliding(player)) { - this.elytraEffectTicks = 30; - } else { - if (this.elytraEffectTicks > 0) - this.elytraEffectTicks--; - } - - if (player.isSneaking()) - this.sneakingTicks++; - else - this.sneakingTicks = 0; - - if (player.isBlocking()) - this.blockingTicks++; - else - this.blockingTicks = 0; - - if (Utilities.isNearWater(player)) - this.nearLiquidTicks = 8; - else { - if (this.nearLiquidTicks > 0) - this.nearLiquidTicks--; - else - this.nearLiquidTicks = 0; - } - - this.hadSpeedEffect = this.hasSpeedEffect; - this.hasSpeedEffect = player.hasPotionEffect(PotionEffectType.SPEED); - - double lastDistanceSq = Math.sqrt(this.lastDistance.getXDifference() * this.lastDistance.getXDifference() - + this.lastDistance.getZDifference() * this.lastDistance.getZDifference()); - double currentDistanceSq = Math.sqrt(distance.getXDifference() * distance.getXDifference() - + distance.getZDifference() * distance.getZDifference()); - this.acceleration = currentDistanceSq - lastDistanceSq; - - this.lastMotionY = this.motionY; - this.motionY = to.getY() - from.getY(); - - Location top = to.clone().add(0, 2, 0); - this.topSolid = top.getBlock().getType().isSolid(); - Location bottom = to.clone().add(0, -1, 0); - this.bottomSolid = bottom.getBlock().getType().isSolid(); - - if ((this.motionY > 0.42D && this.motionY <= 0.5625D) - && (Utilities.couldBeOnHalfblock(to) || Utilities.isNearBed(to))) { - this.halfMovement = true; - this.halfMovementHistoryCounter = 30; - } else { - if (this.halfMovementHistoryCounter > 0) - this.halfMovementHistoryCounter--; - } - - this.lastUpdate = System.currentTimeMillis(); - // Update "good location" - AntiCheatReloaded.getManager().getUserManager().getUser(player.getUniqueId()).setGoodLocation(from); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/PacketListener.java b/src/main/java/com/rammelkast/anticheatreloaded/util/PacketListener.java deleted file mode 100644 index 03020dd..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/PacketListener.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.entity.Player; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.injector.server.TemporaryPlayer; -import com.comphenix.protocol.wrappers.EnumWrappers.PlayerDigType; -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.movement.NoSlowCheck; -import com.rammelkast.anticheatreloaded.check.packet.BadPacketsCheck; -import com.rammelkast.anticheatreloaded.check.packet.MorePacketsCheck; - -public class PacketListener { - - public static void listenMovementPackets() { - AntiCheatReloaded.getProtocolManager() - .addPacketListener(new PacketAdapter(AntiCheatReloaded.getPlugin(), ListenerPriority.LOWEST, - new PacketType[] { PacketType.Play.Client.POSITION, PacketType.Play.Client.POSITION_LOOK, - PacketType.Play.Server.POSITION }) { - @Override - public void onPacketReceiving(PacketEvent event) { - Player player = event.getPlayer(); - if (player == null || !player.isOnline()) - return; - - // Run MorePackets check - MorePacketsCheck.runCheck(player, event); - - if (!event.isCancelled()) { - // Run BadPackets check - BadPacketsCheck.runCheck(player, event); - } - } - - @Override - public void onPacketSending(PacketEvent event) { - Player player = event.getPlayer(); - // Check if we have an actual player object - if (player instanceof TemporaryPlayer) - return; - // Compensate for teleport - MorePacketsCheck.compensate(player); - } - }); - } - - public static void listenKeepAlivePackets() { - AntiCheatReloaded.getProtocolManager() - .addPacketListener(new PacketAdapter(AntiCheatReloaded.getPlugin(), ListenerPriority.LOWEST, - new PacketType[] { PacketType.Play.Client.KEEP_ALIVE, PacketType.Play.Server.KEEP_ALIVE }) { - @Override - public void onPacketSending(PacketEvent event) { - User user = AntiCheatReloaded.getManager().getUserManager() - .getUser(event.getPlayer().getUniqueId()); - user.onServerPing(); - } - - @Override - public void onPacketReceiving(PacketEvent event) { - User user = AntiCheatReloaded.getManager().getUserManager() - .getUser(event.getPlayer().getUniqueId()); - user.onClientPong(); - } - }); - } - - public static void listenUseItemPackets() { - AntiCheatReloaded.getProtocolManager().addPacketListener(new PacketAdapter(AntiCheatReloaded.getPlugin(), - ListenerPriority.LOWEST, new PacketType[] { PacketType.Play.Client.BLOCK_DIG }) { - @Override - public void onPacketReceiving(PacketEvent event) { - if (event.getPacket().getPlayerDigTypes().read(0) == PlayerDigType.RELEASE_USE_ITEM) - NoSlowCheck.runCheck(event.getPlayer(), event); - } - }); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java deleted file mode 100644 index 8f76bdb..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Permission.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.command.CommandSender; - -public enum Permission { - /* Check Nodes */ - CHECK_FLIGHT, CHECK_ELYTRAFLY, CHECK_WATERWALK, CHECK_FASTPLACE, CHECK_CHATSPAM, CHECK_COMMANDSPAM, CHECK_SPRINT, - CHECK_SNEAK, CHECK_SPEED, CHECK_VCLIP, CHECK_SPIDER, CHECK_NOFALL, CHECK_FASTBOW, CHECK_FASTEAT, CHECK_FASTHEAL, - CHECK_KILLAURA, CHECK_UNICODE, CHECK_FASTPROJECTILE, CHECK_ITEMSPAM, CHECK_FASTINVENTORY, - CHECK_MOREPACKETS, CHECK_BADPACKETS, CHECK_VELOCITY, CHECK_CRITICALS, CHECK_ILLEGALINTERACT, CHECK_FASTLADDER, - CHECK_AIMBOT, CHECK_STRAFE, CHECK_NOSLOW, CHECK_BOATFLY, - - /* System Nodes */ - SYSTEM_LOG, SYSTEM_RESET, SYSTEM_HELP, SYSTEM_VERSION, SYSTEM_REPORT, SYSTEM_NOTICE, SYSTEM_CHECK, SYSTEM_RELOAD, - SYSTEM_MUTE; - - private static final String PERMISSION_ALL = "anticheat.*"; - private static final String PERMISSION_SPAM = "anticheat.check.spam"; - - public static boolean getCommandExempt(CommandSender cs, String commandLabel) { - // Check permission, base, and all will have already been checked - return cs.hasPermission(CHECK_COMMANDSPAM.toString() + commandLabel); - } - - public boolean get(CommandSender cs) { - if ((this == CHECK_CHATSPAM || this == CHECK_COMMANDSPAM) && cs.hasPermission(PERMISSION_SPAM)) - return true; - return cs.hasPermission(toString()) || cs.hasPermission(getBase()) || cs.hasPermission(PERMISSION_ALL); - } - - public String getBase() { - return "anticheat." + this.name().toLowerCase().split("_")[0] + ".*"; - } - - public String whichPermission(CommandSender cs) { - for (String s : new String[] { PERMISSION_ALL, getBase(), toString() }) { - if (cs.hasPermission(s)) { - return s; - } - } - return null; - } - - @Override - public String toString() { - return "anticheat." + this.name().toLowerCase().replace("_", "."); - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java b/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java deleted file mode 100644 index 46ab32d..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/ToolHardness.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import org.bukkit.Material; - -public enum ToolHardness { - - // NOTHING(null, 1.5) - WOOD(0.75D), STONE(0.40D), IRON(0.25D), DIAMOND(0.20D), SHEARS(0.55D), GOLD(0.15D); - - double hardness; - - ToolHardness(double hard) { - hardness = hard; - } - - public static double getToolHardness(Material tool) { - for (ToolHardness e : ToolHardness.values()) { - if (tool.name().contains(e.name())) { - return e.hardness; - } - } - - return 1.50D; - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/UpdateManager.java b/src/main/java/com/rammelkast/anticheatreloaded/util/UpdateManager.java deleted file mode 100644 index 2c252e4..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/UpdateManager.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.charset.Charset; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; - -public class UpdateManager { - - public static final int RESOURCE_ID = 23799; - public static final String SPIGOT_VERSION_URL = "https://api.spigotmc.org/legacy/update.php?resource=" - + RESOURCE_ID; - - private String latestVersion; - private boolean isLatest; - private boolean isAhead; - - public UpdateManager() { - this.update(); - } - - public void update() { - this.latestVersion = this.getOnlineData(SPIGOT_VERSION_URL); - if (this.latestVersion == null) { - this.isLatest = true; - this.isAhead = false; - return; - } - - int splitCompare = 0; - try { - VersionSplit currentSplit = new VersionSplit(AntiCheatReloaded.getVersion()); - VersionSplit newSplit = new VersionSplit(this.latestVersion); - splitCompare = currentSplit.compareTo(newSplit); - } catch (Exception e) {} - this.isLatest = splitCompare >= 0; - this.isAhead = splitCompare > 0; - } - - private String getOnlineData(String url) { - String data = null; - InputStream stream = null; - try { - stream = new URL(url).openStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8"))); - StringBuilder builder = new StringBuilder(); - int readChar; - while ((readChar = reader.read()) != -1) { - builder.append((char) readChar); - } - data = builder.toString(); - reader.close(); - } catch (IOException exception) {} - finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - } - } - } - return data; - } - - public boolean isLatest() { - return this.isLatest; - } - - public boolean isAhead() { - return this.isAhead; - } - - public String getCurrentVersion() { - return AntiCheatReloaded.getVersion(); - } - - public String getLatestVersion() { - return this.latestVersion; - } - - public class VersionSplit implements Comparable { - private final int major, minor, build; - - public VersionSplit(String version) throws Exception { - if (version.endsWith("-ALPHA")) { - version = version.substring(0, version.length() - 6); - } else if (version.endsWith("-PRE")) { - version = version.substring(0, version.length() - 4); - } - - String[] versionSplit = version.split("\\."); - if (versionSplit.length != 3) { - // Illegal version - throw new Exception("Version " + version + " is illegal!"); - } - - try { - int major = Integer.parseInt(versionSplit[0]); - int minor = Integer.parseInt(versionSplit[1]); - int build = Integer.parseInt(versionSplit[2]); - if (major <= 0) { - throw new Exception("Illegal version!"); - } - this.major = major; - this.minor = minor; - this.build = build; - } catch (Exception e) { - throw new Exception("Illegal version!"); - } - } - - @Override - public int compareTo(VersionSplit other) { - if (other.major == this.major) { - if (other.minor == this.minor) { - if (other.build == this.build) { - return 0; - } - if (other.build > this.build) { - return -1; - } - return 1; - } - if (other.minor > this.minor) { - return -1; - } - return 1; - } - if (other.major > this.major) { - return -1; - } - return 1; - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getBuild() { - return build; - } - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/User.java b/src/main/java/com/rammelkast/anticheatreloaded/util/User.java deleted file mode 100644 index 8b8dee2..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/User.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.config.Configuration; -import com.rammelkast.anticheatreloaded.util.rule.Rule; - -public class User { - private final UUID uuid; - private final String name; - private final int id; - private int level = 0; - private Location goodLocation; - private List inventorySnapshot = null; - private Configuration config = AntiCheatReloaded.getManager().getConfiguration(); - private int toX, toY, toZ; - private String[] messages = new String[2]; - private Long[] messageTimes = new Long[2]; - private String[] commands = new String[2]; - private Long[] commandTimes = new Long[2]; - - private boolean isWaitingOnLevelSync; - private Timestamp levelSyncTimestamp; - - private long lastServerPing, lastClientPong; - private int ping = -1; - private int lastPing = -1; - - private MovementManager movementManager; - - /** - * Initialize an AntiCheat user - * - * @param uuid Player's UUID - */ - public User(UUID uuid) { - this.uuid = uuid; - this.name = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getName() : ""; - this.id = getPlayer() != null && getPlayer().isOnline() ? getPlayer().getEntityId() : -1; - this.movementManager = new MovementManager(); - this.ping = getPlayer() != null && getPlayer().isOnline() ? VersionUtil.getPlayerPing(getPlayer()) : -1; - } - - /** - * Get the player's UUID - * - * @return Player UUID - */ - public UUID getUUID() { - return uuid; - } - - /** - * Get the player's name - * - * @return Player name - */ - public String getName() { - return name; - } - - /** - * Get the player's entity ID - * - * @return Entity id - */ - public int getId() { - return id; - } - - /** - * Get the Bukkit player - * - * @return Player - */ - public Player getPlayer() { - return Bukkit.getPlayer(uuid); - } - - /** - * Get the user's level value - * - * @return level - */ - public int getLevel() { - return level; - } - - /** - * Get the user's group - * - * @return group - */ - public Group getGroup() { - List groups = config.getGroups().getGroups(); - for (int i = 0; i < groups.size(); i++) { - if (i == 0 && level < groups.get(i).getLevel()) - break; - else if (i == groups.size() - 1) - return groups.get(i); - else if (level >= groups.get(i).getLevel() && level < groups.get(i + 1).getLevel()) - return groups.get(i); - } - return null; - } - - /** - * Increase the player's level (from failing a check) - * - * @param type The check failed - * @return true if the level was increased - */ - public boolean increaseLevel(CheckType type) { - if (getPlayer() != null && getPlayer().isOnline()) { - if (silentMode() && type.getUses(uuid) % 4 != 0) { - // Prevent silent mode from increasing the level way too fast - return false; - } else { - if (level < config.getGroups().getHighestLevel()) { - level++; - - // Check levels - for (Group l : getLevels()) { - if (l.getLevel() == level) { - AntiCheatReloaded.getManager().getUserManager().alert(this, l, type); - if (l.getLevel() == config.getGroups().getHighestLevel()) { - level = l.getLevel() - 10; - } - } - } - - // Execute rules - for (Rule rule : config.getRules().getRules()) { - rule.check(this, type); - } - return true; - } - return false; - } - } else { - return false; - } - } - - /** - * Decrease the player's level by one value - */ - public void decreaseLevel() { - level = level != 0 ? level - 1 : 0; - } - - /** - * Set the users level to a specific value. Must be 0 < level < config-defined - * highest level - * - * @param level level to set - * @return true if the level was valid and set properly - */ - public boolean setLevel(int level) { - isWaitingOnLevelSync = false; - if (level >= 0) { - if (level <= config.getGroups().getHighestLevel()) { - this.level = level; - return true; - } else { - this.level = config.getGroups().getHighestLevel(); - return false; - } - } else { - return false; - } - } - - /** - * Reset the user's level to zero and clear all check failures - */ - public void resetLevel() { - level = 0; - for (CheckType type : CheckType.values()) { - type.clearUse(uuid); - } - } - - /** - * Get the last known valid location of the player for use in resetting - * - * @param location default value to be returned if no known good location exists - * @return last known valid location - */ - public Location getGoodLocation(Location location) { - if (goodLocation == null || !location.getWorld().equals(goodLocation.getWorld()) - || location.distance(goodLocation) > config.getConfig().maxSetbackDistance.getValue()) { - return location; - } - - Location moveTo = goodLocation; - if (location != null) { - moveTo.setPitch(location.getPitch()); - moveTo.setYaw(location.getYaw()); - } - return moveTo; - } - - /** - * Set the last known valid location of the player - * - * @param location location to be set - * @return true if the location was valid and set properly - */ - public boolean setGoodLocation(Location location) { - if (Utilities.cantStandAtExp(location)) { - return false; - } - - goodLocation = location; - return true; - } - - /** - * Store a copy of the player's inventory, for use in resetting - * - * @param is ItemStack list to store - */ - public void setInventorySnapshot(ItemStack[] is) { - inventorySnapshot = new ArrayList(); - for (int i = 0; i < is.length; i++) { - if (is[i] != null) { - inventorySnapshot.add(is[i].clone()); - } - } - } - - /** - * Remove the current inventory snapshot - */ - public void removeInventorySnapshot() { - inventorySnapshot = null; - } - - /** - * Restore the player's inventory with the current inventory snapshot - * - * @param inventory Player's inventory - */ - public void restoreInventory(Inventory inventory) { - if (inventorySnapshot != null) { - inventory.clear(); - for (ItemStack is : inventorySnapshot) { - if (is != null) { - inventory.addItem(is); - } - } - } - } - - /** - * Set the player's to location - * - * @param x X value - * @param y Y value - * @param z Z value - */ - public void setTo(double x, double y, double z) { - toX = (int) x; - toY = (int) y; - toZ = (int) z; - } - - /** - * Check if a given to value is the same as the stored value - * - * @param x X value - * @param y Y value - * @param z Z value - * @return true if coordinates are all equal - */ - public boolean checkTo(double x, double y, double z) { - return (int) x == toX && (int) y == toY && (int) z == toZ; - } - - /** - * Log a player's chat message - * - * @param message Message to log - */ - public void addMessage(String message) { - addToSpamLog(message, messages, messageTimes); - } - - /** - * Log a player's command - * - * @param command Command to log - */ - public void addCommand(String command) { - addToSpamLog(command, commands, commandTimes); - } - - private void addToSpamLog(String string, String[] messages, Long[] times) { - messages[1] = messages[0]; - messages[0] = string; - - times[1] = times[0]; - times[0] = System.currentTimeMillis(); - } - - /** - * Get a stored chat message - * - * @param index Index of the chat in storage - * @return the message - */ - public String getMessage(int index) { - return messages[index]; - } - - /** - * Get a stored command - * - * @param index Index of the command in storage - * @return the command - */ - public String getCommand(int index) { - return commands[index]; - } - - /** - * Get the time a message in storage was sent - * - * @param index Index of the chat in storage - * @return time the message was sent - */ - public Long getMessageTime(int index) { - return messageTimes[index]; - } - - /** - * Get the time a command in storage was sent - * - * @param index Index of the command in storage - * @return time the command was sent - */ - public Long getCommandTime(int index) { - return commandTimes[index]; - } - - /** - * Clear all stored messages - */ - public void clearMessages() { - messages = new String[2]; - messageTimes = new Long[2]; - } - - /** - * Clear all stored commands - */ - public void clearCommands() { - commands = new String[2]; - commandTimes = new Long[2]; - } - - /** - * Get the time the very last stored message was sent - * - * @return the last message's time - */ - public Long getLastMessageTime() { - return getMessageTime(0) == null ? -1 : getMessageTime(0); - } - - /** - * Get the time the very last stored command was sent - * - * @return the last command's time - */ - public Long getLastCommandTime() { - return getCommandTime(0) == null ? -1 : getCommandTime(0); - } - - private List getLevels() { - return config.getGroups().getGroups(); - } - - private boolean silentMode() { - return config.getConfig().silentMode.getValue(); - } - - public void setIsWaitingOnLevelSync(boolean b) { - this.isWaitingOnLevelSync = b; - } - - public boolean isWaitingOnLevelSync() { - return isWaitingOnLevelSync; - } - - public void setLevelSyncTimestamp(Timestamp timestamp) { - levelSyncTimestamp = timestamp; - } - - public Timestamp getLevelSyncTimestamp() { - return levelSyncTimestamp; - } - - public void onServerPing() { - this.lastServerPing = System.currentTimeMillis(); - } - - public void onClientPong() { - this.lastClientPong = System.currentTimeMillis(); - this.lastPing = this.ping; - this.ping = (int) (this.lastClientPong - this.lastServerPing); - } - - public int getPing() { - int ping = this.ping; - if (ping < 0) { - return VersionUtil.getPlayerPing(this.getPlayer()); - } - return ping; - } - - public int getLastPing() { - int lastPing = this.lastPing; - if (lastPing < 0) { - return this.getPing(); - } - return lastPing; - } - - public boolean isLagging() { - return Math.abs(this.ping - this.lastPing) > config.getMagic().LAG_DETERMINATION() - && this.ping > config.getMagic().LAG_DETERMINATION(); - } - - public MovementManager getMovementManager() { - return this.movementManager; - } - - @Override - public String toString() { - return "User {name = " + getName() + ", level = " + level + "}"; - } - -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java b/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java deleted file mode 100644 index d0090f7..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/Utilities.java +++ /dev/null @@ -1,1030 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Boat; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.BoundingBox; -import org.bukkit.util.NumberConversions; - -public final class Utilities { - private static final List INSTANT_BREAK = new ArrayList(); - private static final List FOOD = new ArrayList(); - private static final List CLIMBABLE = new ArrayList(); - private static final Map COMBO = new HashMap(); - - public static final double JUMP_MOTION_Y = 0.41999998688697815; - - /** - * Check if only the block beneath them is standable (includes water + lava) - * - * @param block the block to check (under) - * @return true if they cannot stand there - */ - public static boolean cantStandAtSingle(Block block) { - Block otherBlock = block.getLocation().add(0, -0.5, 0).getBlock(); - boolean center = otherBlock.getType() == Material.AIR; - return center; - } - - /** - * Determine whether a player cannot stand on or around the given block - * - * @param block the block to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAt(Block block) { - return !canStand(block) && cantStandClose(block) && cantStandFar(block); - } - - /** - * Determine whether a player should be unable to stand at a given location - * - * @param location the location to check - * @return true if the player should be unable to stand here - */ - public static boolean cantStandAtExp(Location location) { - return cantStandAt(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, - location.getBlockZ()).getBlock()); - } - - /** - * Determine whether cannot stand on the block's immediately surroundings - * (North, East, South, West) - * - * @param block the block to check - * @return true if a player cannot stand in the immediate vicinity - */ - public static boolean cantStandClose(Block block) { - return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) - && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST)); - } - - /** - * Determine whether cannot stand on the block's outer surroundings - * - * @param block the block to check - * @return true if a player cannot stand in areas further away from the block - */ - public static boolean cantStandFar(Block block) { - return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) - && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) - && !canStand(block.getRelative(BlockFace.SOUTH_EAST)); - } - - /** - * Determine whether a player can stand on the given block - * - * @param block the block to check - * @return true if the player can stand here - */ - public static boolean canStand(Block block) { - return !(block.isLiquid() || block.getType() == Material.AIR); - } - - public static boolean isNotNearSlime(Block block) { - return !isSlime(block.getRelative(BlockFace.NORTH)) && !isSlime(block.getRelative(BlockFace.EAST)) - && !isSlime(block.getRelative(BlockFace.SOUTH)) && !isSlime(block.getRelative(BlockFace.WEST)) - && !isSlime(block.getRelative(BlockFace.DOWN)); - } - - public static boolean couldBeOnBoat(Player player) { - return couldBeOnBoat(player, 0.35, false); - } - - public static boolean couldBeOnBoat(Player player, double range, boolean checkY) { - for (Entity entity : player.getNearbyEntities(range, range, range)) { - if (entity instanceof Boat) { - if (((Boat) entity).getLocation().getY() < player.getLocation().getY() + 0.25) { - return true; - } else if (!checkY) { - return true; - } - } - } - return false; - } - - /** - * Determine whether a player could be standing on ice - * - * @param location the location to check - * @return true if the player could be standing on ice - */ - public static boolean couldBeOnIce(Location location) { - return isNearIce(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, - location.getBlockZ())) - || isNearIce(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.26D, - location.getBlockZ())); - } - - /** - * Determine whether a block is a type of ice - * - * @param block block to check - * @return true if block is a type of ice - */ - public static boolean isIce(Block block) { - Material type = block.getType(); - return type.name().endsWith("ICE"); - } - - public static boolean isNearIce(Location location) { - return isIce(location.getBlock()) || isIce(location.getBlock().getRelative(BlockFace.NORTH)) - || isIce(location.getBlock().getRelative(BlockFace.SOUTH)) - || isIce(location.getBlock().getRelative(BlockFace.EAST)) - || isIce(location.getBlock().getRelative(BlockFace.WEST)) - || isIce(location.getBlock().getRelative(BlockFace.NORTH_EAST)) - || isIce(location.getBlock().getRelative(BlockFace.NORTH_WEST)) - || isIce(location.getBlock().getRelative(BlockFace.SOUTH_EAST)) - || isIce(location.getBlock().getRelative(BlockFace.SOUTH_WEST)); - } - - /** - * Determine whether a block is a shulker box - * - * @param block block to check - * @return true if block is a shulker box - */ - public static boolean isShulkerBox(Block block) { - Material type = block.getType(); - return type.name().endsWith("SHULKER_BOX"); - } - - public static boolean isNearShulkerBox(Location location) { - // Shulkers are 1.12+ - if (MinecraftVersion.getCurrentVersion().isAtLeast(MinecraftVersion.COLOR_UPDATE)) { - return false; - } - return isShulkerBox(location.getBlock()) || isShulkerBox(location.getBlock().getRelative(BlockFace.NORTH)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.SOUTH)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.EAST)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.WEST)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.NORTH_EAST)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.NORTH_WEST)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.SOUTH_EAST)) - || isShulkerBox(location.getBlock().getRelative(BlockFace.SOUTH_WEST)); - } - - /** - * Determine whether a player could be standing on a halfblock - * - * @param location the location to check - * @return true if the player could be standing on a halfblock - */ - public static boolean couldBeOnHalfblock(Location location) { - return isNearHalfblock( - new Location(location.getWorld(), location.getX(), location.getY() - 0.01D, location.getBlockZ())) - || isNearHalfblock(new Location(location.getWorld(), location.getX(), location.getY() - 0.51D, - location.getBlockZ())); - } - - public static boolean isNearHalfblock(Location location) { - return isHalfblock(location.getBlock()) || isHalfblock(location.getBlock().getRelative(BlockFace.NORTH)) - || isHalfblock(location.getBlock().getRelative(BlockFace.SOUTH)) - || isHalfblock(location.getBlock().getRelative(BlockFace.EAST)) - || isHalfblock(location.getBlock().getRelative(BlockFace.WEST)) - || isHalfblock(location.getBlock().getRelative(BlockFace.NORTH_EAST)) - || isHalfblock(location.getBlock().getRelative(BlockFace.NORTH_WEST)) - || isHalfblock(location.getBlock().getRelative(BlockFace.SOUTH_EAST)) - || isHalfblock(location.getBlock().getRelative(BlockFace.SOUTH_WEST)); - } - - public static boolean isHalfblock(Block block) { - // getBoundingBox() is only available on 1.14+ - if (MinecraftVersion.getCurrentVersion().isAtLeast(MinecraftVersion.VILLAGE_UPDATE)) { - BoundingBox box = block.getBoundingBox(); - double height = box.getMaxY() - box.getMinY(); - if (height > 0.42 && height <= 0.6 && block.getType().isSolid()) - return true; - } - return isSlab(block) || isStair(block) || isWall(block) || block.getType() == Material.SNOW - || block.getType().name().endsWith("HEAD"); - } - - /** - * Determine whether a player could be standing on slime - * - * @param location the location to check - * @return true if the player could be standing on slime - */ - public static boolean couldBeOnSlime(Location location) { - return isNearSlime(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.01D, - location.getBlockZ())) - || isNearSlime(new Location(location.getWorld(), fixXAxis(location.getX()), location.getY() - 0.51D, - location.getBlockZ())); - } - - /** - * Determine whether a block is a type of slime - * - * @param block block to check - * @return true if block is a type of slime - */ - public static boolean isSlime(Block block) { - Material type = block.getType(); - return type.equals(XMaterial.SLIME_BLOCK.parseMaterial()); - } - - public static boolean isNearSlime(Location location) { - return isSlime(location.getBlock()) || isSlime(location.getBlock().getRelative(BlockFace.NORTH)) - || isSlime(location.getBlock().getRelative(BlockFace.SOUTH)) - || isSlime(location.getBlock().getRelative(BlockFace.EAST)) - || isSlime(location.getBlock().getRelative(BlockFace.WEST)) - || isSlime(location.getBlock().getRelative(BlockFace.NORTH_EAST)) - || isSlime(location.getBlock().getRelative(BlockFace.NORTH_WEST)) - || isSlime(location.getBlock().getRelative(BlockFace.SOUTH_EAST)) - || isSlime(location.getBlock().getRelative(BlockFace.SOUTH_WEST)); - } - - /** - * Determine whether a player is fully submerged in water - * - * @param player the player's location - * @return true if the player is fully in the water - */ - public static boolean isFullyInWater(Location player) { - double touchedX = fixXAxis(player.getX()); - - // Yes, this doesn't make sense, but it's supposed to fix some false positives - // in water walk. - // Think of it as 2 negatives = a positive :) - if (!(new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() - && !(new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()) - .getBlock()).isLiquid()) { - return true; - } - - return (new Location(player.getWorld(), touchedX, player.getY(), player.getBlockZ()).getBlock()).isLiquid() - && (new Location(player.getWorld(), touchedX, Math.round(player.getY()), player.getBlockZ()).getBlock()) - .isLiquid(); - } - - /** - * Fixes a player's X position to determine the block they are on, even if - * they're on the edge - * - * @param x player's x position - * @return fixed x position - */ - public static double fixXAxis(double x) { - /* For Z axis, just use Math.round(xaxis); */ - double touchedX = x; - double rem = touchedX - Math.round(touchedX) + 0.01D; - if (rem < 0.30D) { - touchedX = NumberConversions.floor(x) - 1; - } - return touchedX; - } - - /** - * Determine if the player is hovering over water with the given limit - * - * @param player the player's location - * @param blocks max blocks to check - * @return true if the player is hovering over water - */ - public static boolean isHoveringOverWater(Location player, int blocks) { - for (int i = player.getBlockY(); i > player.getBlockY() - blocks; i--) { - Block newloc = (new Location(player.getWorld(), player.getBlockX(), i, player.getBlockZ())).getBlock(); - if (newloc.getType() != Material.AIR) { - return newloc.isLiquid(); - } - } - - return false; - } - - /** - * Determine if the player is hovering over water with a hard limit of 25 blocks - * - * @param player the player's location - * @return true if the player is hovering over water - */ - public static boolean isHoveringOverWater(Location player) { - return isHoveringOverWater(player, 25); - } - - /** - * Determine whether a material will break instantly when hit - * - * @param m the material to check - * @return true if the material is instant break - */ - public static boolean isInstantBreak(Material m) { - return INSTANT_BREAK.contains(m); - } - - /** - * Determine whether a material is edible - * - * @param m the material to check - * @return true if the material is food - */ - public static boolean isFood(Material m) { - return FOOD.contains(m); - } - - /** - * Determine whether a block is a slab - * - * @param block block to check - * @return true if slab - */ - public static boolean isSlab(Block block) { - Material type = block.getType(); - return type.name().endsWith("SLAB"); - } - - /** - * Determine whether a block is a bed - * - * @param block block to bed - * @return true if bed - */ - public static boolean isBed(Block block) { - Material type = block.getType(); - return type.name().endsWith("BED"); - } - - public static boolean isNearBed(Location location) { - return isBed(location.getBlock()) || isBed(location.getBlock().getRelative(BlockFace.NORTH)) - || isBed(location.getBlock().getRelative(BlockFace.SOUTH)) - || isBed(location.getBlock().getRelative(BlockFace.EAST)) - || isBed(location.getBlock().getRelative(BlockFace.WEST)) - || isBed(location.getBlock().getRelative(BlockFace.NORTH_EAST)) - || isBed(location.getBlock().getRelative(BlockFace.NORTH_WEST)) - || isBed(location.getBlock().getRelative(BlockFace.SOUTH_EAST)) - || isBed(location.getBlock().getRelative(BlockFace.SOUTH_WEST)); - } - - /** - * Determine whether a block is a stair - * - * @param block block to check - * @return true if stair - */ - public static boolean isStair(Block block) { - Material type = block.getType(); - return type.name().endsWith("STAIRS"); - } - - /** - * Determine whether a block is a wall - * - * @param block block to check - * @return true if wall - */ - public static boolean isWall(Block block) { - Material type = block.getType(); - return type.name().endsWith("WALL") || type.name().endsWith("FENCE"); - } - - /** - * Determine whether a player is sprinting or flying - * - * @param player player to check - * @return true if sprinting or flying - */ - public static boolean sprintFly(Player player) { - return player.isSprinting() || player.isFlying(); - } - - /** - * Determine whether a player is standing on a lily pad - * - * @param player player to check - * @return true if on lily pad - */ - public static boolean isOnLilyPad(Player player) { - Block block = player.getLocation().getBlock(); - return block.getType() == XMaterial.LILY_PAD.parseMaterial() - || block.getRelative(BlockFace.NORTH).getType() == XMaterial.LILY_PAD.parseMaterial() - || block.getRelative(BlockFace.SOUTH).getType() == XMaterial.LILY_PAD.parseMaterial() - || block.getRelative(BlockFace.EAST).getType() == XMaterial.LILY_PAD.parseMaterial() - || block.getRelative(BlockFace.WEST).getType() == XMaterial.LILY_PAD.parseMaterial(); - } - - /** - * Determine whether a player is fully submersed in liquid - * - * @param player player to check - * @return true if submersed - */ - public static boolean isSubmersed(Player player) { - return player.getLocation().getBlock().isLiquid() - && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); - } - - /** - * Determine whether a player is in water - * - * @param player player to check - * @return true if in water - */ - public static boolean isInWater(Player player) { - return player.getLocation().getBlock().isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid() - || (MinecraftVersion.getCurrentVersion().isAtLeast(MinecraftVersion.AQUATIC_UPDATE) - && (player.getLocation().getBlock().getType() == XMaterial.KELP_PLANT.parseMaterial() - || player.getLocation().getBlock().getRelative(BlockFace.UP) - .getType() == XMaterial.KELP_PLANT.parseMaterial() - || player.getLocation().getBlock().getRelative(BlockFace.DOWN) - .getType() == XMaterial.KELP_PLANT.parseMaterial()) - && isNearWater(player)); - } - - /** - * Determine whether a player is near a liquid block - * - * @param player player to check - * @return true if near liquid block - */ - public static boolean isNearWater(Player player) { - return player.getLocation().getBlock().isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.NORTH).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.SOUTH).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.EAST).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.WEST).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.NORTH_EAST).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.NORTH_WEST).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.SOUTH_EAST).isLiquid() - || player.getLocation().getBlock().getRelative(BlockFace.SOUTH_WEST).isLiquid(); - } - - /** - * Determine whether a player is surrounded by liquid blocks - * - * @param player player to check - * @return true if surrounded by liquid blocks - */ - public static boolean isSurroundedByWater(Player player) { - Location location = player.getLocation().clone().subtract(0, 0.1, 0); - return location.getBlock().isLiquid() && location.getBlock().getRelative(BlockFace.NORTH).isLiquid() - && location.getBlock().getRelative(BlockFace.SOUTH).isLiquid() - && location.getBlock().getRelative(BlockFace.EAST).isLiquid() - && location.getBlock().getRelative(BlockFace.WEST).isLiquid() - && location.getBlock().getRelative(BlockFace.NORTH_EAST).isLiquid() - && location.getBlock().getRelative(BlockFace.NORTH_WEST).isLiquid() - && location.getBlock().getRelative(BlockFace.SOUTH_EAST).isLiquid() - && location.getBlock().getRelative(BlockFace.SOUTH_WEST).isLiquid(); - } - - /** - * Determine whether a player is near a web - * - * @param player player to check - * @return true if near a web - */ - public static boolean isNearWeb(Player player) { - return isWeb(player.getLocation().getBlock()) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.DOWN)) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.UP)) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.NORTH)) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.SOUTH)) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.EAST)) - || isWeb(player.getLocation().getBlock().getRelative(BlockFace.WEST)); - } - - /** - * Determine whether a block is a web - * - * @param block block to check - * @return true if web - */ - public static boolean isWeb(Block block) { - return block.getType() == XMaterial.COBWEB.parseMaterial(); - } - - /** - * Determine whether a player is in a web - * - * @param player player to check - * @return true if in web - */ - public static boolean isInWeb(Player player) { - return player.getLocation().getBlock().getType() == XMaterial.COBWEB.parseMaterial() - || player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() == XMaterial.COBWEB - .parseMaterial() - || player.getLocation().getBlock().getRelative(BlockFace.UP).getType() == XMaterial.COBWEB - .parseMaterial(); - } - - /** - * Determine whether a player is near a climbable block - * - * @param player player to check - * @return true if near climbable block - */ - public static boolean isNearClimbable(Player player) { - return isClimbableBlock(player.getLocation().getBlock()) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.DOWN)) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.UP)) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.NORTH)) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.SOUTH)) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.EAST)) - || isClimbableBlock(player.getLocation().getBlock().getRelative(BlockFace.WEST)); - } - - /** - * Determine whether a location is near a climbable block - * - * @param location location to check - * @return true if near climbable block - */ - public static boolean isNearClimbable(Location location) { - return isClimbableBlock(location.getBlock()) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.DOWN)) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.UP)) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.NORTH)) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.SOUTH)) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.EAST)) - || isClimbableBlock(location.getBlock().getRelative(BlockFace.WEST)); - } - - /** - * Determine whether a block is climbable - * - * @param block block to check - * @return true if climbable - */ - public static boolean isClimbableBlock(Block block) { - return CLIMBABLE.contains(block.getType()); - } - - /** - * Determine whether a player is on a vine (can be free hanging) - * - * @param player to check - * @return true if on vine - */ - public static boolean isOnVine(Player player) { - return player.getLocation().getBlock().getType() == XMaterial.VINE.parseMaterial(); - } - - /** - * Determine whether a String can be cast to an Integer - * - * @param string text to check - * @return true if int - */ - public static boolean isInt(String string) { - try { - Integer.parseInt(string); - return true; - } catch (Exception ex) { - return false; - } - } - - /** - * Determine whether a String can be cast to a Double - * - * @param string text to check - * @return true if double - */ - public static boolean isDouble(String string) { - try { - Double.parseDouble(string); - return true; - } catch (Exception ex) { - return false; - } - } - - /** - * Determine if a block ISN'T one of the specified types - * - * @param block block to check - * @param materials array of possible materials - * @return true if the block isn't any of the materials - */ - public static boolean blockIsnt(Block block, Material[] materials) { - Material type = block.getType(); - for (Material m : materials) { - if (m == type) { - return false; - } - } - return true; - } - - /** - * Determine if a block ISN'T one of the specified types - * - * @param block block to check - * @param endTypes array of possible name endings - * @return true if the block isn't any of the materials - */ - public static boolean blockIsnt(Block block, String[] endTypes) { - Material type = block.getType(); - for (String s : endTypes) { - if (type.name().endsWith(s)) { - return false; - } - } - return true; - } - - /** - * Parse a COMMAND[] input to a set of commands to execute - * - * @param command input string - * @return parsed commands - */ - public static String[] getCommands(String command) { - return command.replaceAll("COMMAND\\[", "").replaceAll("]", "").split(";"); - } - - /** - * Remove all whitespace from the given string to ready it for parsing - * - * @param string the string to parse - * @return string with whitespace removed - */ - public static String removeWhitespace(String string) { - return string.replaceAll(" ", ""); - } - - /** - * Determine if a player has the given enchantment on their armor - * - * @param player player to check - * @param e enchantment to check - * @return true if the armor has this enchantment - */ - public static boolean hasArmorEnchantment(Player player, Enchantment e) { - for (ItemStack is : player.getInventory().getArmorContents()) { - if (is != null && is.containsEnchantment(e)) { - return true; - } - } - return false; - } - - /** - * Create a list with the given string for execution - * - * @param string the string to parse - * @return ArrayList with string - */ - public static ArrayList stringToList(final String string) { - return new ArrayList() { - private static final long serialVersionUID = 364115444874638230L; - { - add(string); - } - }; - } - - /** - * Create a comma-delimited string from a list - * - * @param list the list to parse - * @return the list in a string format - */ - public static String listToCommaString(List list) { - StringBuilder b = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - b.append(list.get(i)); - if (i < list.size() - 1) { - b.append(","); - } - } - return b.toString(); - } - - /** - * Parse a string in the format of "XdXhXmXs" to seconds - * - * @param string The string to parse - * @return seconds - */ - public static long lifeToSeconds(String string) { - if (string.equals("0") || string.equals("")) - return 0; - String[] lifeMatch = new String[] { "d", "h", "m", "s" }; - int[] lifeInterval = new int[] { 86400, 3600, 60, 1 }; - long seconds = 0L; - - for (int i = 0; i < lifeMatch.length; i++) { - Matcher matcher = Pattern.compile("([0-9]*)" + lifeMatch[i]).matcher(string); - while (matcher.find()) { - seconds += Integer.parseInt(matcher.group(1)) * lifeInterval[i]; - } - - } - return seconds; - } - - /** - * Rounds a float value to a scale - * - * @param value Value to round - * @param scale Scale - * @return rounded value - */ - public static float roundFloat(float value, int scale) { - return new BigDecimal(value).setScale(scale, RoundingMode.HALF_UP).floatValue(); - } - - /** - * Rounds a double value to a scale - * - * @param value Value to round - * @param scale Scale - * @return rounded value - */ - public static double roundDouble(double value, int scale) { - return new BigDecimal(value).setScale(scale, RoundingMode.HALF_UP).doubleValue(); - } - - public static int floor(double value) { - int rounded = (int) value; - return value < rounded ? rounded - 1 : rounded; - } - - public static boolean isHoneyBlock(Block block) { - if (MinecraftVersion.getCurrentVersion().isAtLeast(MinecraftVersion.BEE_UPDATE)) { - return false; - } - return block.getType() == XMaterial.HONEY_BLOCK.parseMaterial(); - } - - static { - // Start 1.8.8 - if (VersionUtil.isBountifulUpdate()) { - // Start instant break materials - INSTANT_BREAK.add(XMaterial.COMPARATOR.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REPEATER.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TORCH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REDSTONE_TORCH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REDSTONE_WIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TRIPWIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TRIPWIRE_HOOK.parseMaterial()); - INSTANT_BREAK.add(XMaterial.FIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.FLOWER_POT.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TNT.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SLIME_BLOCK.parseMaterial()); - INSTANT_BREAK.add(XMaterial.CARROT.parseMaterial()); - INSTANT_BREAK.add(XMaterial.DEAD_BUSH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.GRASS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TALL_GRASS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.LILY_PAD.parseMaterial()); - INSTANT_BREAK.add(XMaterial.MELON_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.MELON_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.BROWN_MUSHROOM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.RED_MUSHROOM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.NETHER_WART.parseMaterial()); - INSTANT_BREAK.add(XMaterial.POTATO.parseMaterial()); - INSTANT_BREAK.add(XMaterial.PUMPKIN_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.PUMPKIN_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.OAK_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SUGAR_CANE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.WHEAT.parseMaterial()); - // End instant break materials - - // Start food - FOOD.add(XMaterial.APPLE.parseMaterial()); - FOOD.add(XMaterial.BAKED_POTATO.parseMaterial()); - FOOD.add(XMaterial.BREAD.parseMaterial()); - FOOD.add(XMaterial.CAKE.parseMaterial()); - FOOD.add(XMaterial.CARROT.parseMaterial()); - FOOD.add(XMaterial.COOKED_CHICKEN.parseMaterial()); - FOOD.add(XMaterial.COOKED_COD.parseMaterial()); - FOOD.add(XMaterial.COD.parseMaterial()); - FOOD.add(XMaterial.COOKED_MUTTON.parseMaterial()); - FOOD.add(XMaterial.COOKED_PORKCHOP.parseMaterial()); - FOOD.add(XMaterial.COOKED_RABBIT.parseMaterial()); - FOOD.add(XMaterial.COOKIE.parseMaterial()); - FOOD.add(XMaterial.GOLDEN_APPLE.parseMaterial()); - FOOD.add(XMaterial.GOLDEN_CARROT.parseMaterial()); - FOOD.add(XMaterial.GLISTERING_MELON_SLICE.parseMaterial()); - FOOD.add(XMaterial.MUSHROOM_STEM.parseMaterial()); - FOOD.add(XMaterial.POISONOUS_POTATO.parseMaterial()); - FOOD.add(XMaterial.POTATO.parseMaterial()); - FOOD.add(XMaterial.PUMPKIN_PIE.parseMaterial()); - FOOD.add(XMaterial.RABBIT_STEW.parseMaterial()); - FOOD.add(XMaterial.COOKED_BEEF.parseMaterial()); - FOOD.add(XMaterial.BEEF.parseMaterial()); - FOOD.add(XMaterial.COOKED_CHICKEN.parseMaterial()); - FOOD.add(XMaterial.CHICKEN.parseMaterial()); - FOOD.add(XMaterial.MUTTON.parseMaterial()); - FOOD.add(XMaterial.PORKCHOP.parseMaterial()); - FOOD.add(XMaterial.RABBIT.parseMaterial()); - FOOD.add(XMaterial.COOKED_RABBIT.parseMaterial()); - FOOD.add(XMaterial.ROTTEN_FLESH.parseMaterial()); - FOOD.add(XMaterial.SPIDER_EYE.parseMaterial()); - - // Start combos - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.WHITE_WOOL.parseMaterial()); - - COMBO.put(XMaterial.IRON_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.DIAMOND_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.STONE_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.WOODEN_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - // End combos - - // Start climbable - CLIMBABLE.add(XMaterial.VINE.parseMaterial()); - CLIMBABLE.add(XMaterial.LADDER.parseMaterial()); - CLIMBABLE.add(XMaterial.WATER.parseMaterial()); - // End climbable - } - // End 1.8.8 - // Start other version - else { - MinecraftVersion currentVersion = MinecraftVersion.getCurrentVersion(); - - // Start instant break materials - INSTANT_BREAK.add(XMaterial.COMPARATOR.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REPEATER.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TORCH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REDSTONE_TORCH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.REDSTONE_WIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TRIPWIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TRIPWIRE_HOOK.parseMaterial()); - INSTANT_BREAK.add(XMaterial.FIRE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.FLOWER_POT.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_CHISELED_STONE_BRICKS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_COBBLESTONE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_CRACKED_STONE_BRICKS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_MOSSY_STONE_BRICKS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_STONE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.INFESTED_STONE_BRICKS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TNT.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SLIME_BLOCK.parseMaterial()); - INSTANT_BREAK.add(XMaterial.CARROTS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.DEAD_BUSH.parseMaterial()); - INSTANT_BREAK.add(XMaterial.FERN.parseMaterial()); - INSTANT_BREAK.add(XMaterial.LARGE_FERN.parseMaterial()); - INSTANT_BREAK.add(XMaterial.CHORUS_FLOWER.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SUNFLOWER.parseMaterial()); - INSTANT_BREAK.add(XMaterial.LILY_PAD.parseMaterial()); - INSTANT_BREAK.add(XMaterial.MELON_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.ATTACHED_MELON_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.BROWN_MUSHROOM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.RED_MUSHROOM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.NETHER_WART.parseMaterial()); - INSTANT_BREAK.add(XMaterial.POTATOES.parseMaterial()); - INSTANT_BREAK.add(XMaterial.PUMPKIN_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.ATTACHED_PUMPKIN_STEM.parseMaterial()); - INSTANT_BREAK.add(XMaterial.ACACIA_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.BIRCH_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.DARK_OAK_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.JUNGLE_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.OAK_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SPRUCE_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.SUGAR_CANE.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TALL_GRASS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.TALL_SEAGRASS.parseMaterial()); - INSTANT_BREAK.add(XMaterial.WHEAT.parseMaterial()); - // Start 1.14 objects - if (currentVersion.isAtLeast(MinecraftVersion.VILLAGE_UPDATE)) { - INSTANT_BREAK.add(XMaterial.BAMBOO_SAPLING.parseMaterial()); - INSTANT_BREAK.add(XMaterial.CORNFLOWER.parseMaterial()); - } - // End 1.14 objects - // Start 1.15 objects - if (currentVersion.isAtLeast(MinecraftVersion.BEE_UPDATE)) { - INSTANT_BREAK.add(XMaterial.HONEY_BLOCK.parseMaterial()); - } - // End 1.15 objects - // End instant break materials - - // Start food - FOOD.add(XMaterial.APPLE.parseMaterial()); - FOOD.add(XMaterial.BAKED_POTATO.parseMaterial()); - FOOD.add(XMaterial.BEETROOT.parseMaterial()); - FOOD.add(XMaterial.BEETROOT_SOUP.parseMaterial()); - FOOD.add(XMaterial.BREAD.parseMaterial()); - FOOD.add(XMaterial.CAKE.parseMaterial()); - FOOD.add(XMaterial.CARROT.parseMaterial()); - FOOD.add(XMaterial.CHORUS_FRUIT.parseMaterial()); - FOOD.add(XMaterial.COOKED_BEEF.parseMaterial()); - FOOD.add(XMaterial.COOKED_CHICKEN.parseMaterial()); - FOOD.add(XMaterial.COOKED_COD.parseMaterial()); - FOOD.add(XMaterial.COOKED_MUTTON.parseMaterial()); - FOOD.add(XMaterial.COOKED_PORKCHOP.parseMaterial()); - FOOD.add(XMaterial.COOKED_RABBIT.parseMaterial()); - FOOD.add(XMaterial.COOKED_SALMON.parseMaterial()); - FOOD.add(XMaterial.COOKIE.parseMaterial()); - FOOD.add(XMaterial.DRIED_KELP.parseMaterial()); - FOOD.add(XMaterial.ENCHANTED_GOLDEN_APPLE.parseMaterial()); - FOOD.add(XMaterial.GOLDEN_APPLE.parseMaterial()); - FOOD.add(XMaterial.GOLDEN_CARROT.parseMaterial()); - FOOD.add(XMaterial.MELON_SLICE.parseMaterial()); - FOOD.add(XMaterial.MUSHROOM_STEW.parseMaterial()); - FOOD.add(XMaterial.POISONOUS_POTATO.parseMaterial()); - FOOD.add(XMaterial.POTATO.parseMaterial()); - FOOD.add(XMaterial.PUFFERFISH.parseMaterial()); - FOOD.add(XMaterial.PUMPKIN_PIE.parseMaterial()); - FOOD.add(XMaterial.RABBIT_STEW.parseMaterial()); - FOOD.add(XMaterial.BEEF.parseMaterial()); - FOOD.add(XMaterial.CHICKEN.parseMaterial()); - FOOD.add(XMaterial.COD.parseMaterial()); - FOOD.add(XMaterial.MUTTON.parseMaterial()); - FOOD.add(XMaterial.PORKCHOP.parseMaterial()); - FOOD.add(XMaterial.RABBIT.parseMaterial()); - FOOD.add(XMaterial.SALMON.parseMaterial()); - FOOD.add(XMaterial.ROTTEN_FLESH.parseMaterial()); - FOOD.add(XMaterial.SPIDER_EYE.parseMaterial()); - FOOD.add(XMaterial.TROPICAL_FISH.parseMaterial()); - // Start 1.14 objects - if (currentVersion.isAtLeast(MinecraftVersion.VILLAGE_UPDATE)) { - FOOD.add(XMaterial.SUSPICIOUS_STEW.parseMaterial()); - FOOD.add(XMaterial.SWEET_BERRIES.parseMaterial()); - } - // End 1.14 objects - // Start 1.15 objects - if (currentVersion.isAtLeast(MinecraftVersion.BEE_UPDATE)) { - FOOD.add(XMaterial.HONEY_BOTTLE.parseMaterial()); - } - // End 1.15 objects - // End food - - // Start combos - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.BLACK_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.BLUE_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.BROWN_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.CYAN_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.GRAY_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.GREEN_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.LIGHT_BLUE_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.LIGHT_GRAY_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.LIME_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.MAGENTA_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.MAGENTA_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.ORANGE_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.PINK_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.PURPLE_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.RED_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.WHITE_WOOL.parseMaterial()); - COMBO.put(XMaterial.SHEARS.parseMaterial(), XMaterial.YELLOW_WOOL.parseMaterial()); - - COMBO.put(XMaterial.IRON_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.DIAMOND_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.STONE_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - COMBO.put(XMaterial.WOODEN_SWORD.parseMaterial(), XMaterial.COBWEB.parseMaterial()); - // End combos - - // Start climbable - CLIMBABLE.add(XMaterial.VINE.parseMaterial()); - CLIMBABLE.add(XMaterial.LADDER.parseMaterial()); - CLIMBABLE.add(XMaterial.WATER.parseMaterial()); - // Start 1.14 objects - if (currentVersion.isAtLeast(MinecraftVersion.VILLAGE_UPDATE)) { - CLIMBABLE.add(XMaterial.SCAFFOLDING.parseMaterial()); - CLIMBABLE.add(XMaterial.SWEET_BERRY_BUSH.parseMaterial()); - } - // End 1.14 objects - - // Start 1.16 objects - if (currentVersion.isAtLeast(MinecraftVersion.NETHER_UPDATE)) { - CLIMBABLE.add(XMaterial.TWISTING_VINES.parseMaterial()); - CLIMBABLE.add(XMaterial.TWISTING_VINES_PLANT.parseMaterial()); - CLIMBABLE.add(XMaterial.WEEPING_VINES.parseMaterial()); - CLIMBABLE.add(XMaterial.WEEPING_VINES_PLANT.parseMaterial()); - } - // End 1.16 objects - // End climbable - } - // End other versions - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/VersionUtil.java b/src/main/java/com/rammelkast/anticheatreloaded/util/VersionUtil.java deleted file mode 100644 index 495b276..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/VersionUtil.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.rammelkast.anticheatreloaded.util; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; - -public class VersionUtil { - - private static final List SUPPORTED_VERSIONS; - private static final MinecraftVersion CURRENT_VERSION; - - public static String getVersion() { - return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - } - - public static boolean isSupported() { - for (String versionId : SUPPORTED_VERSIONS) { - if (getVersion().startsWith(versionId)) { - return true; - } - } - return false; - } - - public static boolean isOfVersion(String versionId) { - if (getVersion().startsWith(versionId)) { - return true; - } - return false; - } - - /** - * @return the if server is running Bountiful Update (1.8) - */ - public static boolean isBountifulUpdate() { - return isOfVersion("v1_8"); - } - - public static boolean isFlying(Player player) { - if (isBountifulUpdate()) { - return player.isFlying(); - } - return player.isFlying() || player.isGliding() || player.hasPotionEffect(PotionEffectType.LEVITATION) - || AntiCheatReloaded.getManager().getBackend().justLevitated(player); - } - - public static boolean isRiptiding(Player player) { - if (!CURRENT_VERSION.isAtLeast(MinecraftVersion.AQUATIC_UPDATE)) { - return false; - } - return player.isRiptiding(); - } - - public static boolean isSlowFalling(Player player) { - if (!CURRENT_VERSION.isAtLeast(MinecraftVersion.AQUATIC_UPDATE)) { - return false; - } - return player.hasPotionEffect(PotionEffectType.SLOW_FALLING); - } - - public static boolean isFrostWalk(Player player) { - if (player.getInventory().getBoots() == null || isBountifulUpdate()) { - return false; - } - return player.getInventory().getBoots().containsEnchantment(Enchantment.FROST_WALKER); - } - - @SuppressWarnings("deprecation") - public static ItemStack getItemInHand(Player player) { - if (isBountifulUpdate()) { - return player.getItemInHand(); - } - return player.getInventory().getItemInMainHand(); - } - - public static int getPlayerPing(Player player) { - try { - Object entityPlayer = player.getClass().getMethod("getHandle").invoke(player); - int ping = (int) entityPlayer.getClass().getField("ping").get(entityPlayer); - return ping; - } catch (Exception e) { - return -1; - } - } - - public static Block getTargetBlock(Player player, int distance) { - if (!CURRENT_VERSION.isAtLeast(MinecraftVersion.AQUATIC_UPDATE)) { - return player.getTargetBlock((Set) null, distance); - } - return player.getTargetBlockExact(distance); - } - - public static boolean isGliding(Player player) { - if (isBountifulUpdate()) { - return false; - } - return player.isGliding(); - } - - public static boolean isLevitationEffect(PotionEffect effect) { - if (isBountifulUpdate()) { - return false; - } - return effect.getType().equals(PotionEffectType.LEVITATION); - } - - public static int getPotionLevel(Player player, PotionEffectType type) { - if (isBountifulUpdate()) { - for (PotionEffect effect : player.getActivePotionEffects()) { - if (effect.getType().equals(type)) - return effect.getAmplifier() + 1; - } - return 0; - } - - if (player.hasPotionEffect(type)) - return player.getPotionEffect(type).getAmplifier() + 1; - return 0; - } - - public static boolean isSwimming(Player player) { - if (!CURRENT_VERSION.isAtLeast(MinecraftVersion.AQUATIC_UPDATE)) { - return false; - } - return player.isSwimming(); - } - - static { - SUPPORTED_VERSIONS = Arrays.asList(new String[] { "v1_16", "v1_15", "v1_14", "v1_13", "v1_12", "v1_8_R3" }); - CURRENT_VERSION = MinecraftVersion.getCurrentVersion(); - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/XMaterial.java b/src/main/java/com/rammelkast/anticheatreloaded/util/XMaterial.java deleted file mode 100644 index 57dfea5..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/XMaterial.java +++ /dev/null @@ -1,2166 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2018 Hex_27 - * Copyright (c) 2020 Crypto Morin - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE - * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -package com.rammelkast.anticheatreloaded.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.apache.commons.lang.WordUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import com.google.common.base.Enums; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; - -/** - * XMaterial - Data Values/Pre-flattening
- * 1.13 and above as priority. - *

- * This class is mainly designed to support ItemStacks. If you want to use it on blocks, you'll have to use - * XBlock - *

- * Pre-flattening: https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening - * Materials: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html - * Materials (1.12): https://helpch.at/docs/1.12.2/index.html?org/bukkit/Material.html - * Material IDs: https://minecraft-ids.grahamedgecombe.com/ - * Material Source Code: https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse/src/main/java/org/bukkit/Material.java - * XMaterial v1: https://www.spigotmc.org/threads/329630/ - *

- * This class will throw a "unsupported material" error if someone tries to use an item with an invalid data value which can only happen in 1.12 servers and below. - * To get an invalid item, (aka Missing Texture Block) you can use the command - * /give @p minecraft:dirt 1 10 where 1 is the item amount, and 10 is the data value. The material {@link #DIRT} with a data value of {@code 10} doesn't exist. - * - * @author Crypto Morin - * @version 6.0.2 - * @see Material - * @see ItemStack - */ -public enum XMaterial { - ACACIA_BOAT("BOAT_ACACIA"), - ACACIA_BUTTON("WOOD_BUTTON"), - ACACIA_DOOR("ACACIA_DOOR_ITEM", "ACACIA_DOOR"), - ACACIA_FENCE, - ACACIA_FENCE_GATE, - ACACIA_LEAVES("LEAVES_2"), - ACACIA_LOG("LOG_2"), - ACACIA_PLANKS(4, "WOOD"), - ACACIA_PRESSURE_PLATE("WOOD_PLATE"), - ACACIA_SAPLING(4, "SAPLING"), - ACACIA_SIGN("SIGN_POST", "SIGN"), - ACACIA_SLAB(4, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - ACACIA_STAIRS, - ACACIA_TRAPDOOR("TRAP_DOOR"), - ACACIA_WALL_SIGN("WALL_SIGN"), - ACACIA_WOOD("LOG_2"), - ACTIVATOR_RAIL, - /** - * https://minecraft.gamepedia.com/Air - * {@link Material#isAir()} - * - * @see #VOID_AIR - * @see #CAVE_AIR - */ - AIR, - ALLIUM(2, "RED_ROSE"), - ANCIENT_DEBRIS("1.16"), - ANDESITE(5, "STONE"), - ANDESITE_SLAB, - ANDESITE_STAIRS, - ANDESITE_WALL, - ANVIL, - APPLE, - ARMOR_STAND, - ARROW, - ATTACHED_MELON_STEM(7, "MELON_STEM"), - ATTACHED_PUMPKIN_STEM(7, "PUMPKIN_STEM"), - AZURE_BLUET(3, "RED_ROSE"), - BAKED_POTATO, - BAMBOO("1.14", "SUGAR_CANE", ""), - BAMBOO_SAPLING("1.14"), - BARREL("1.14", "CHEST", ""), - BARRIER, - BASALT("1.16"), - BAT_SPAWN_EGG(65, "MONSTER_EGG"), - BEACON, - BEDROCK, - BEEF("RAW_BEEF"), - BEEHIVE("1.15"), - /** - * Beetroot is a known material in pre-1.13 - * Use XBlock when comparing block types. - */ - BEETROOT("BEETROOT_BLOCK"), - BEETROOTS("BEETROOT"), - BEETROOT_SEEDS, - BEETROOT_SOUP, - BEE_NEST("1.15"), - BEE_SPAWN_EGG("1.15"), - BELL("1.14"), - BIRCH_BOAT("BOAT_BIRCH"), - BIRCH_BUTTON("WOOD_BUTTON"), - BIRCH_DOOR("BIRCH_DOOR_ITEM", "BIRCH_DOOR"), - BIRCH_FENCE, - BIRCH_FENCE_GATE, - BIRCH_LEAVES(2, "LEAVES"), - BIRCH_LOG(2, "LOG"), - BIRCH_PLANKS(2, "WOOD"), - BIRCH_PRESSURE_PLATE("WOOD_PLATE"), - BIRCH_SAPLING(2, "SAPLING"), - BIRCH_SIGN("SIGN_POST", "SIGN"), - BIRCH_SLAB(2, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - BIRCH_STAIRS("BIRCH_WOOD_STAIRS"), - BIRCH_TRAPDOOR("TRAP_DOOR"), - BIRCH_WALL_SIGN("WALL_SIGN"), - BIRCH_WOOD(2, "LOG"), - BLACKSTONE("1.16"), - BLACKSTONE_SLAB("1.16"), - BLACKSTONE_STAIRS("1.16"), - BLACKSTONE_WALL("1.16"), - BLACK_BANNER("STANDING_BANNER", "BANNER"), - BLACK_BED(15, "BED_BLOCK", "BED"), - BLACK_CARPET(15, "CARPET"), - BLACK_CONCRETE(15, "CONCRETE"), - BLACK_CONCRETE_POWDER(15, "CONCRETE_POWDER"), - BLACK_DYE("1.14", "INK_SACK", "INK_SAC"), - BLACK_GLAZED_TERRACOTTA(15, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLACK_TERRACOTTA"), - BLACK_SHULKER_BOX, - BLACK_STAINED_GLASS(15, "STAINED_GLASS"), - BLACK_STAINED_GLASS_PANE(15, "STAINED_GLASS_PANE"), - BLACK_TERRACOTTA(15, "HARD_CLAY", "STAINED_CLAY"), - BLACK_WALL_BANNER("WALL_BANNER"), - BLACK_WOOL(15, "WOOL"), - BLAST_FURNACE("1.14", "FURNACE", ""), - BLAZE_POWDER, - BLAZE_ROD, - BLAZE_SPAWN_EGG(61, "MONSTER_EGG"), - BLUE_BANNER(4, "STANDING_BANNER", "BANNER"), - BLUE_BED(11, "BED_BLOCK", "BED"), - BLUE_CARPET(11, "CARPET"), - BLUE_CONCRETE(11, "CONCRETE"), - BLUE_CONCRETE_POWDER(11, "CONCRETE_POWDER"), - BLUE_DYE(4, "INK_SACK", "LAPIS_LAZULI"), - BLUE_GLAZED_TERRACOTTA(11, "1.12", "HARD_CLAY", "STAINED_CLAY", "BLUE_TERRACOTTA"), - BLUE_ICE("1.13", "PACKED_ICE", ""), - BLUE_ORCHID(1, "RED_ROSE"), - BLUE_SHULKER_BOX, - BLUE_STAINED_GLASS(11, "STAINED_GLASS"), - BLUE_STAINED_GLASS_PANE(11, "THIN_GLASS", "STAINED_GLASS_PANE"), - BLUE_TERRACOTTA(11, "HARD_CLAY", "STAINED_CLAY"), - BLUE_WALL_BANNER(4, "WALL_BANNER"), - BLUE_WOOL(11, "WOOL"), - BONE, - BONE_BLOCK, - BONE_MEAL(15, "INK_SACK"), - BOOK, - BOOKSHELF, - BOW, - BOWL, - BRAIN_CORAL("1.13"), - BRAIN_CORAL_BLOCK("1.13"), - BRAIN_CORAL_FAN("1.13"), - BRAIN_CORAL_WALL_FAN, - BREAD, - BREWING_STAND("BREWING_STAND_ITEM"), - BRICK("CLAY_BRICK"), - BRICKS("BRICK"), - BRICK_SLAB(4, "STEP"), - BRICK_STAIRS, - BRICK_WALL, - BROWN_BANNER(3, "STANDING_BANNER", "BANNER"), - BROWN_BED(12, "BED_BLOCK", "BED"), - BROWN_CARPET(12, "CARPET"), - BROWN_CONCRETE(12, "CONCRETE"), - BROWN_CONCRETE_POWDER(12, "CONCRETE_POWDER"), - BROWN_DYE(3, "INK_SACK", "COCOA", "COCOA_BEANS"), - BROWN_GLAZED_TERRACOTTA(12, "1.12", "HARD_CLAY", "STAINED_CLAY", "BROWN_TERRACOTTA"), - BROWN_MUSHROOM, - BROWN_MUSHROOM_BLOCK("BROWN_MUSHROOM", "HUGE_MUSHROOM_1"), - BROWN_SHULKER_BOX, - BROWN_STAINED_GLASS(12, "STAINED_GLASS"), - BROWN_STAINED_GLASS_PANE(12, "THIN_GLASS", "STAINED_GLASS_PANE"), - BROWN_TERRACOTTA(12, "STAINED_CLAY"), - BROWN_WALL_BANNER(3, "WALL_BANNER"), - BROWN_WOOL(12, "WOOL"), - BUBBLE_COLUMN("1.13"), - BUBBLE_CORAL("1.13"), - BUBBLE_CORAL_BLOCK("1.13"), - BUBBLE_CORAL_FAN("1.13"), - BUBBLE_CORAL_WALL_FAN, - BUCKET, - CACTUS, - CAKE("CAKE_BLOCK"), - CAMPFIRE("1.14"), - CARROT("CARROT_ITEM"), - CARROTS("CARROT"), - CARROT_ON_A_STICK("CARROT_STICK"), - CARTOGRAPHY_TABLE("1.14", "CRAFTING_TABLE", ""), - CARVED_PUMPKIN(1, "1.13", "PUMPKIN", ""), - CAT_SPAWN_EGG, - CAULDRON("CAULDRON_ITEM"), - /** - * 1.13 tag is not added because it's the same thing as {@link #AIR} - * - * @see #VOID_AIR - */ - CAVE_AIR("AIR"), - CAVE_SPIDER_SPAWN_EGG(59, "MONSTER_EGG"), - CHAIN("1.16"), - CHAINMAIL_BOOTS, - CHAINMAIL_CHESTPLATE, - CHAINMAIL_HELMET, - CHAINMAIL_LEGGINGS, - CHAIN_COMMAND_BLOCK("COMMAND", "COMMAND_CHAIN"), - CHARCOAL(1, "COAL"), - CHEST("LOCKED_CHEST"), - CHEST_MINECART("STORAGE_MINECART"), - CHICKEN("RAW_CHICKEN"), - CHICKEN_SPAWN_EGG(93, "MONSTER_EGG"), - CHIPPED_ANVIL(1, "ANVIL"), - CHISELED_NETHER_BRICKS(1, "NETHER_BRICKS"), - CHISELED_POLISHED_BLACKSTONE("1.16", "POLISHED_BLACKSTONE"), - CHISELED_QUARTZ_BLOCK(1, "QUARTZ_BLOCK"), - CHISELED_RED_SANDSTONE(1, "RED_SANDSTONE"), - CHISELED_SANDSTONE(1, "SANDSTONE"), - CHISELED_STONE_BRICKS(3, "SMOOTH_BRICK"), - CHORUS_FLOWER("1.9"), - CHORUS_FRUIT("1.9"), - CHORUS_PLANT("1.9"), - CLAY, - CLAY_BALL, - CLOCK("WATCH"), - COAL, - COAL_BLOCK, - COAL_ORE, - COARSE_DIRT(1, "DIRT"), - COBBLESTONE, - COBBLESTONE_SLAB(3, "STEP"), - COBBLESTONE_STAIRS, - COBBLESTONE_WALL("COBBLE_WALL"), - COBWEB("WEB"), - COCOA("1.15"), - COCOA_BEANS(3, "INK_SACK", "COCOA"), - COD("RAW_FISH"), - COD_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), - COD_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - COMMAND_BLOCK("COMMAND"), - COMMAND_BLOCK_MINECART("COMMAND_MINECART"), - /** - * Unlike redstone torch and redstone lamp... neither REDTONE_COMPARATOR_OFF nor REDSTONE_COMPARATOR_ON - * are items. REDSTONE_COMPARATOR is. - * - * @see #REDSTONE_TORCH - * @see #REDSTONE_LAMP - */ - COMPARATOR("REDSTONE_COMPARATOR_OFF", "REDSTONE_COMPARATOR_ON", "REDSTONE_COMPARATOR"), - COMPASS, - COMPOSTER("1.14", "CAULDRON", ""), - CONDUIT("1.13", "BEACON"), - COOKED_BEEF, - COOKED_CHICKEN, - COOKED_COD("COOKED_FISH"), - COOKED_MUTTON, - COOKED_PORKCHOP("PORK", "GRILLED_PORK"), - COOKED_RABBIT, - COOKED_SALMON(1, "COOKED_FISH"), - COOKIE, - CORNFLOWER(4, "1.14", "BLUE_DYE", ""), - COW_SPAWN_EGG(92, "MONSTER_EGG"), - CRACKED_NETHER_BRICKS(2, "NETHER_BRICKS"), - CRACKED_POLISHED_BLACKSTONE_BRICKS("1.16", "POLISHED_BLACKSTONE_BRICKS"), - CRACKED_STONE_BRICKS(2, "SMOOTH_BRICK"), - CRAFTING_TABLE("WORKBENCH"), - CREEPER_BANNER_PATTERN, - CREEPER_HEAD(4, "SKULL", "SKULL_ITEM"), - CREEPER_SPAWN_EGG(50, "MONSTER_EGG"), - CREEPER_WALL_HEAD(4, "SKULL", "SKULL_ITEM"), - CRIMSON_BUTTON("1.16"), - CRIMSON_DOOR("1.16"), - CRIMSON_FENCE("1.16"), - CRIMSON_FENCE_GATE("1.16"), - CRIMSON_FUNGUS("1.16"), - CRIMSON_HYPHAE("1.16"), - CRIMSON_NYLIUM("1.16"), - CRIMSON_PLANKS("1.16"), - CRIMSON_PRESSURE_PLATE("1.16"), - CRIMSON_ROOTS("1.16"), - CRIMSON_SIGN("1.16", "SIGN_POST"), - CRIMSON_SLAB("1.16"), - CRIMSON_STAIRS("1.16"), - CRIMSON_STEM("1.16"), - CRIMSON_TRAPDOOR("1.16"), - CRIMSON_WALL_SIGN("1.16", "WALL_SIGN"), - CROSSBOW, - CRYING_OBSIDIAN("1.16"), - CUT_RED_SANDSTONE("1.13"), - CUT_RED_SANDSTONE_SLAB("STONE_SLAB2"), - CUT_SANDSTONE("1.13"), - CUT_SANDSTONE_SLAB("STEP"), - CYAN_BANNER(6, "STANDING_BANNER", "BANNER"), - CYAN_BED(9, "BED_BLOCK", "BED"), - CYAN_CARPET(9, "CARPET"), - CYAN_CONCRETE(9, "CONCRETE"), - CYAN_CONCRETE_POWDER(9, "CONCRETE_POWDER"), - CYAN_DYE(6, "INK_SACK"), - CYAN_GLAZED_TERRACOTTA(9, "1.12", "HARD_CLAY", "STAINED_CLAY", "CYAN_TERRACOTTA"), - CYAN_SHULKER_BOX, - CYAN_STAINED_GLASS(9, "STAINED_GLASS"), - CYAN_STAINED_GLASS_PANE(9, "STAINED_GLASS_PANE"), - CYAN_TERRACOTTA(9, "HARD_CLAY", "STAINED_CLAY"), - CYAN_WALL_BANNER(6, "WALL_BANNER"), - CYAN_WOOL(9, "WOOL"), - DAMAGED_ANVIL(2, "ANVIL"), - DANDELION("YELLOW_FLOWER"), - DARK_OAK_BOAT("BOAT_DARK_OAK"), - DARK_OAK_BUTTON("WOOD_BUTTON"), - DARK_OAK_DOOR("DARK_OAK_DOOR_ITEM", "DARK_OAK_DOOR"), - DARK_OAK_FENCE, - DARK_OAK_FENCE_GATE, - DARK_OAK_LEAVES(4, "LEAVES", "LEAVES_2"), - DARK_OAK_LOG(1, "LOG", "LOG_2"), - DARK_OAK_PLANKS(5, "WOOD"), - DARK_OAK_PRESSURE_PLATE("WOOD_PLATE"), - DARK_OAK_SAPLING(5, "SAPLING"), - DARK_OAK_SIGN("SIGN_POST", "SIGN"), - DARK_OAK_SLAB(5, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - DARK_OAK_STAIRS, - DARK_OAK_TRAPDOOR("TRAP_DOOR"), - DARK_OAK_WALL_SIGN("WALL_SIGN"), - DARK_OAK_WOOD(1, "LOG", "LOG_2"), - DARK_PRISMARINE(1, "PRISMARINE"), - DARK_PRISMARINE_SLAB("1.13"), - DARK_PRISMARINE_STAIRS("1.13"), - DAYLIGHT_DETECTOR("DAYLIGHT_DETECTOR_INVERTED"), - DEAD_BRAIN_CORAL("1.13"), - DEAD_BRAIN_CORAL_BLOCK("1.13"), - DEAD_BRAIN_CORAL_FAN("1.13"), - DEAD_BRAIN_CORAL_WALL_FAN("1.13"), - DEAD_BUBBLE_CORAL("1.13"), - DEAD_BUBBLE_CORAL_BLOCK("1.13"), - DEAD_BUBBLE_CORAL_FAN("1.13"), - DEAD_BUBBLE_CORAL_WALL_FAN("1.13"), - DEAD_BUSH, - DEAD_FIRE_CORAL("1.13"), - DEAD_FIRE_CORAL_BLOCK("1.13"), - DEAD_FIRE_CORAL_FAN("1.13"), - DEAD_FIRE_CORAL_WALL_FAN("1.13"), - DEAD_HORN_CORAL("1.13"), - DEAD_HORN_CORAL_BLOCK("1.13"), - DEAD_HORN_CORAL_FAN("1.13"), - DEAD_HORN_CORAL_WALL_FAN("1.13"), - DEAD_TUBE_CORAL("1.13"), - DEAD_TUBE_CORAL_BLOCK("1.13"), - DEAD_TUBE_CORAL_FAN("1.13"), - DEAD_TUBE_CORAL_WALL_FAN("1.13"), - DEBUG_STICK("1.13", "STICK", ""), - DETECTOR_RAIL, - DIAMOND, - DIAMOND_AXE, - DIAMOND_BLOCK, - DIAMOND_BOOTS, - DIAMOND_CHESTPLATE, - DIAMOND_HELMET, - DIAMOND_HOE, - DIAMOND_HORSE_ARMOR("DIAMOND_BARDING"), - DIAMOND_LEGGINGS, - DIAMOND_ORE, - DIAMOND_PICKAXE, - DIAMOND_SHOVEL("DIAMOND_SPADE"), - DIAMOND_SWORD, - DIORITE(3, "STONE"), - DIORITE_SLAB, - DIORITE_STAIRS, - DIORITE_WALL, - DIRT, - DISPENSER, - DOLPHIN_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - DONKEY_SPAWN_EGG(32, "MONSTER_EGG"), - DRAGON_BREATH("DRAGONS_BREATH"), - DRAGON_EGG, - DRAGON_HEAD(5, "1.9", "SKULL", "SKULL_ITEM"), - DRAGON_WALL_HEAD(5, "SKULL", "SKULL_ITEM"), - DRIED_KELP("1.13"), - DRIED_KELP_BLOCK("1.13"), - DROPPER, - DROWNED_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - EGG, - ELDER_GUARDIAN_SPAWN_EGG(4, "MONSTER_EGG"), - ELYTRA, - EMERALD, - EMERALD_BLOCK, - EMERALD_ORE, - ENCHANTED_BOOK, - ENCHANTED_GOLDEN_APPLE(1, "GOLDEN_APPLE"), - ENCHANTING_TABLE("ENCHANTMENT_TABLE"), - ENDERMAN_SPAWN_EGG(58, "MONSTER_EGG"), - ENDERMITE_SPAWN_EGG(67, "MONSTER_EGG"), - ENDER_CHEST, - ENDER_EYE("EYE_OF_ENDER"), - ENDER_PEARL, - END_CRYSTAL, - END_GATEWAY("1.9"), - END_PORTAL("ENDER_PORTAL"), - END_PORTAL_FRAME("ENDER_PORTAL_FRAME"), - END_ROD("1.9", "BLAZE_ROD", ""), - END_STONE("ENDER_STONE"), - END_STONE_BRICKS("END_BRICKS"), - END_STONE_BRICK_SLAB(6, "STEP"), - END_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), - END_STONE_BRICK_WALL, - EVOKER_SPAWN_EGG(34, "MONSTER_EGG"), - EXPERIENCE_BOTTLE("EXP_BOTTLE"), - FARMLAND("SOIL"), - FEATHER, - FERMENTED_SPIDER_EYE, - FERN(2, "LONG_GRASS"), - /** - * For some reasons filled map items are really special. - * Their data value starts from 0 and every time a player - * creates a new map that maps data value increases. - */ - FILLED_MAP("MAP"), - FIRE, - FIREWORK_ROCKET("FIREWORK"), - FIREWORK_STAR("FIREWORK_CHARGE"), - FIRE_CHARGE("FIREBALL"), - FIRE_CORAL("1.13"), - FIRE_CORAL_BLOCK("1.13"), - FIRE_CORAL_FAN("1.13"), - FIRE_CORAL_WALL_FAN, - FISHING_ROD, - FLETCHING_TABLE("1.14", "CRAFTING_TABLE", ""), - FLINT, - FLINT_AND_STEEL, - FLOWER_BANNER_PATTERN, - FLOWER_POT("FLOWER_POT_ITEM"), - FOX_SPAWN_EGG("1.14"), - /** - * This special material cannot be obtained as an item. - */ - FROSTED_ICE("1.9", "PACKED_ICE", ""), - FURNACE("BURNING_FURNACE"), - FURNACE_MINECART("POWERED_MINECART"), - GHAST_SPAWN_EGG(56, "MONSTER_EGG"), - GHAST_TEAR, - GILDED_BLACKSTONE("1.16"), - GLASS, - GLASS_BOTTLE, - GLASS_PANE("THIN_GLASS"), - GLISTERING_MELON_SLICE("SPECKLED_MELON"), - GLOBE_BANNER_PATTERN, - GLOWSTONE, - GLOWSTONE_DUST, - GOLDEN_APPLE, - GOLDEN_AXE("GOLD_AXE"), - GOLDEN_BOOTS("GOLD_BOOTS"), - GOLDEN_CARROT, - GOLDEN_CHESTPLATE("GOLD_CHESTPLATE"), - GOLDEN_HELMET("GOLD_HELMET"), - GOLDEN_HOE("GOLD_HOE"), - GOLDEN_HORSE_ARMOR("GOLD_BARDING"), - GOLDEN_LEGGINGS("GOLD_LEGGINGS"), - GOLDEN_PICKAXE("GOLD_PICKAXE"), - GOLDEN_SHOVEL("GOLD_SPADE"), - GOLDEN_SWORD("GOLD_SWORD"), - GOLD_BLOCK, - GOLD_INGOT, - GOLD_NUGGET, - GOLD_ORE, - GRANITE(1, "STONE"), - GRANITE_SLAB, - GRANITE_STAIRS, - GRANITE_WALL, - GRASS(1, "LONG_GRASS"), - GRASS_BLOCK("GRASS"), - GRASS_PATH, - GRAVEL, - GRAY_BANNER(8, "STANDING_BANNER", "BANNER"), - GRAY_BED(7, "BED_BLOCK", "BED"), - GRAY_CARPET(7, "CARPET"), - GRAY_CONCRETE(7, "CONCRETE"), - GRAY_CONCRETE_POWDER(7, "CONCRETE_POWDER"), - GRAY_DYE(8, "INK_SACK"), - GRAY_GLAZED_TERRACOTTA(7, "1.12", "HARD_CLAY", "STAINED_CLAY", "GRAY_TERRACOTTA"), - GRAY_SHULKER_BOX, - GRAY_STAINED_GLASS(7, "STAINED_GLASS"), - GRAY_STAINED_GLASS_PANE(7, "THIN_GLASS", "STAINED_GLASS_PANE"), - GRAY_TERRACOTTA(7, "HARD_CLAY", "STAINED_CLAY"), - GRAY_WALL_BANNER(8, "WALL_BANNER"), - GRAY_WOOL(7, "WOOL"), - GREEN_BANNER(2, "STANDING_BANNER", "BANNER"), - GREEN_BED(13, "BED_BLOCK", "BED"), - GREEN_CARPET(13, "CARPET"), - GREEN_CONCRETE(13, "CONCRETE"), - GREEN_CONCRETE_POWDER(13, "CONCRETE_POWDER"), - GREEN_DYE(2, "INK_SACK", "CACTUS_GREEN"), - GREEN_GLAZED_TERRACOTTA(13, "1.12", "HARD_CLAY", "STAINED_CLAY", "GREEN_TERRACOTTA"), - GREEN_SHULKER_BOX, - GREEN_STAINED_GLASS(13, "STAINED_GLASS"), - GREEN_STAINED_GLASS_PANE(13, "THIN_GLASS", "STAINED_GLASS_PANE"), - GREEN_TERRACOTTA(13, "HARD_CLAY", "STAINED_CLAY"), - GREEN_WALL_BANNER(2, "WALL_BANNER"), - GREEN_WOOL(13, "WOOL"), - GRINDSTONE("1.14", "ANVIL", ""), - GUARDIAN_SPAWN_EGG(68, "MONSTER_EGG"), - GUNPOWDER("SULPHUR"), - HAY_BLOCK, - HEART_OF_THE_SEA("1.13"), - HEAVY_WEIGHTED_PRESSURE_PLATE("IRON_PLATE"), - HOGLIN_SPAWN_EGG("1.16", "MONSTER_EGG"), - HONEYCOMB("1.15"), - HONEYCOMB_BLOCK("1.15"), - HONEY_BLOCK("1.15", "SLIME_BLOCK", ""), - HONEY_BOTTLE("1.15", "GLASS_BOTTLE", ""), - HOPPER, - HOPPER_MINECART, - HORN_CORAL("1.13"), - HORN_CORAL_BLOCK("1.13"), - HORN_CORAL_FAN("1.13"), - HORN_CORAL_WALL_FAN, - HORSE_SPAWN_EGG(100, "MONSTER_EGG"), - HUSK_SPAWN_EGG(23, "MONSTER_EGG"), - ICE, - INFESTED_CHISELED_STONE_BRICKS(5, "MONSTER_EGGS", "SMOOTH_BRICK"), - INFESTED_COBBLESTONE(1, "MONSTER_EGGS"), - INFESTED_CRACKED_STONE_BRICKS(4, "MONSTER_EGGS", "SMOOTH_BRICK"), - INFESTED_MOSSY_STONE_BRICKS(3, "MONSTER_EGGS"), - INFESTED_STONE("MONSTER_EGGS"), - INFESTED_STONE_BRICKS(2, "MONSTER_EGGS", "SMOOTH_BRICK"), - /** - * We will only add "INK_SAC" for {@link #BLACK_DYE} since it's - * the only material (linked with this material) that is added - * after 1.13, which means it can use both INK_SACK and INK_SAC. - */ - INK_SAC("INK_SACK"), - IRON_AXE, - IRON_BARS("IRON_FENCE"), - IRON_BLOCK, - IRON_BOOTS, - IRON_CHESTPLATE, - IRON_DOOR("IRON_DOOR_BLOCK"), - IRON_HELMET, - IRON_HOE, - IRON_HORSE_ARMOR("IRON_BARDING"), - IRON_INGOT, - IRON_LEGGINGS, - IRON_NUGGET, - IRON_ORE, - IRON_PICKAXE, - IRON_SHOVEL("IRON_SPADE"), - IRON_SWORD, - IRON_TRAPDOOR, - ITEM_FRAME, - JACK_O_LANTERN, - JIGSAW("1.14", "COMMAND_BLOCK", "STRUCTURE_BLOCK", ""), - JUKEBOX, - JUNGLE_BOAT("BOAT_JUNGLE"), - JUNGLE_BUTTON("WOOD_BUTTON"), - JUNGLE_DOOR("JUNGLE_DOOR_ITEM", "JUNGLE_DOOR"), - JUNGLE_FENCE, - JUNGLE_FENCE_GATE, - JUNGLE_LEAVES(3, "LEAVES"), - JUNGLE_LOG(3, "LOG"), - JUNGLE_PLANKS(3, "WOOD"), - JUNGLE_PRESSURE_PLATE("WOOD_PLATE"), - JUNGLE_SAPLING(3, "SAPLING"), - JUNGLE_SIGN("SIGN_POST", "SIGN"), - JUNGLE_SLAB(3, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - JUNGLE_STAIRS("JUNGLE_WOOD_STAIRS"), - JUNGLE_TRAPDOOR("TRAP_DOOR"), - JUNGLE_WALL_SIGN("WALL_SIGN"), - JUNGLE_WOOD(3, "LOG"), - KELP("1.13"), - KELP_PLANT("1.13"), - KNOWLEDGE_BOOK("1.12", "BOOK"), - LADDER, - LANTERN("1.14", "SEA_LANTERN", ""), - LAPIS_BLOCK, - LAPIS_LAZULI(4, "INK_SACK"), - LAPIS_ORE, - LARGE_FERN(3, "DOUBLE_PLANT"), - LAVA("STATIONARY_LAVA"), - LAVA_BUCKET, - LEAD("LEASH"), - LEATHER, - LEATHER_BOOTS, - LEATHER_CHESTPLATE, - LEATHER_HELMET, - LEATHER_HORSE_ARMOR("1.14", "IRON_HORSE_ARMOR", ""), - LEATHER_LEGGINGS, - LECTERN("1.14", "BOOKSHELF", ""), - LEVER, - LIGHT_BLUE_BANNER(12, "STANDING_BANNER", "BANNER"), - LIGHT_BLUE_BED(3, "BED_BLOCK", "BED"), - LIGHT_BLUE_CARPET(3, "CARPET"), - LIGHT_BLUE_CONCRETE(3, "CONCRETE"), - LIGHT_BLUE_CONCRETE_POWDER(3, "CONCRETE_POWDER"), - LIGHT_BLUE_DYE(12, "INK_SACK"), - LIGHT_BLUE_GLAZED_TERRACOTTA(3, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_BLUE_TERRACOTTA"), - LIGHT_BLUE_SHULKER_BOX, - LIGHT_BLUE_STAINED_GLASS(3, "STAINED_GLASS"), - LIGHT_BLUE_STAINED_GLASS_PANE(3, "THIN_GLASS", "STAINED_GLASS_PANE"), - LIGHT_BLUE_TERRACOTTA(3, "STAINED_CLAY"), - LIGHT_BLUE_WALL_BANNER(12, "WALL_BANNER", "STANDING_BANNER", "BANNER"), - LIGHT_BLUE_WOOL(3, "WOOL"), - LIGHT_GRAY_BANNER(7, "STANDING_BANNER", "BANNER"), - LIGHT_GRAY_BED(8, "BED_BLOCK", "BED"), - LIGHT_GRAY_CARPET(8, "CARPET"), - LIGHT_GRAY_CONCRETE(8, "CONCRETE"), - LIGHT_GRAY_CONCRETE_POWDER(8, "CONCRETE_POWDER"), - LIGHT_GRAY_DYE(7, "INK_SACK"), - /** - * Renamed to SILVER_GLAZED_TERRACOTTA in 1.12 - * Renamed to LIGHT_GRAY_GLAZED_TERRACOTTA in 1.14 - */ - LIGHT_GRAY_GLAZED_TERRACOTTA("1.12", "HARD_CLAY", "STAINED_CLAY", "LIGHT_GRAY_TERRACOTTA", "SILVER_GLAZED_TERRACOTTA"), - LIGHT_GRAY_SHULKER_BOX("SILVER_SHULKER_BOX"), - LIGHT_GRAY_STAINED_GLASS(8, "STAINED_GLASS"), - LIGHT_GRAY_STAINED_GLASS_PANE(8, "THIN_GLASS", "STAINED_GLASS_PANE"), - LIGHT_GRAY_TERRACOTTA(8, "HARD_CLAY", "STAINED_CLAY"), - LIGHT_GRAY_WALL_BANNER(7, "WALL_BANNER"), - LIGHT_GRAY_WOOL(8, "WOOL"), - LIGHT_WEIGHTED_PRESSURE_PLATE("GOLD_PLATE"), - LILAC(1, "DOUBLE_PLANT"), - LILY_OF_THE_VALLEY(15, "1.14", "WHITE_DYE", ""), - LILY_PAD("WATER_LILY"), - LIME_BANNER(10, "STANDING_BANNER", "BANNER"), - LIME_BED(5, "BED_BLOCK", "BED"), - LIME_CARPET(5, "CARPET"), - LIME_CONCRETE(5, "CONCRETE"), - LIME_CONCRETE_POWDER(5, "CONCRETE_POWDER"), - LIME_DYE(10, "INK_SACK"), - LIME_GLAZED_TERRACOTTA(5, "1.12", "HARD_CLAY", "STAINED_CLAY", "LIME_TERRACOTTA"), - LIME_SHULKER_BOX, - LIME_STAINED_GLASS(5, "STAINED_GLASS"), - LIME_STAINED_GLASS_PANE(5, "STAINED_GLASS_PANE"), - LIME_TERRACOTTA(5, "HARD_CLAY", "STAINED_CLAY"), - LIME_WALL_BANNER(10, "WALL_BANNER"), - LIME_WOOL(5, "WOOL"), - LINGERING_POTION, - LLAMA_SPAWN_EGG(103, "MONSTER_EGG"), - LODESTONE("1.16"), - LOOM("1.14"), - MAGENTA_BANNER(13, "STANDING_BANNER", "BANNER"), - MAGENTA_BED(2, "BED_BLOCK", "BED"), - MAGENTA_CARPET(2, "CARPET"), - MAGENTA_CONCRETE(2, "CONCRETE"), - MAGENTA_CONCRETE_POWDER(2, "CONCRETE_POWDER"), - MAGENTA_DYE(13, "INK_SACK"), - MAGENTA_GLAZED_TERRACOTTA(2, "1.12", "HARD_CLAY", "STAINED_CLAY", "MAGENTA_TERRACOTTA"), - MAGENTA_SHULKER_BOX, - MAGENTA_STAINED_GLASS(2, "STAINED_GLASS"), - MAGENTA_STAINED_GLASS_PANE(2, "THIN_GLASS", "STAINED_GLASS_PANE"), - MAGENTA_TERRACOTTA(2, "HARD_CLAY", "STAINED_CLAY"), - MAGENTA_WALL_BANNER(13, "WALL_BANNER"), - MAGENTA_WOOL(2, "WOOL"), - MAGMA_BLOCK("1.10", "MAGMA"), - MAGMA_CREAM, - MAGMA_CUBE_SPAWN_EGG(62, "MONSTER_EGG"), - /** - * Adding this to the duplicated list will give you a filled map - * for 1.13+ versions and removing it from duplicated list will - * still give you a filled map in -1.12 versions. - * Since higher versions are our priority I'll keep 1.13+ support - * until I can come up with something to fix it. - */ - MAP("EMPTY_MAP"), - MELON("MELON_BLOCK"), - MELON_SEEDS, - MELON_SLICE("MELON"), - MELON_STEM, - MILK_BUCKET, - MINECART, - MOJANG_BANNER_PATTERN, - MOOSHROOM_SPAWN_EGG(96, "MONSTER_EGG"), - MOSSY_COBBLESTONE, - MOSSY_COBBLESTONE_SLAB(3, "STEP"), - MOSSY_COBBLESTONE_STAIRS, - MOSSY_COBBLESTONE_WALL(1, "COBBLE_WALL", "COBBLESTONE_WALL"), - MOSSY_STONE_BRICKS(1, "SMOOTH_BRICK"), - MOSSY_STONE_BRICK_SLAB(5, "STEP"), - MOSSY_STONE_BRICK_STAIRS("SMOOTH_STAIRS"), - MOSSY_STONE_BRICK_WALL, - MOVING_PISTON("PISTON_BASE", "PISTON_MOVING_PIECE"), - MULE_SPAWN_EGG(32, "MONSTER_EGG"), - MUSHROOM_STEM("BROWN_MUSHROOM"), - MUSHROOM_STEW("MUSHROOM_SOUP"), - MUSIC_DISC_11("GOLD_RECORD"), - MUSIC_DISC_13("GREEN_RECORD"), - MUSIC_DISC_BLOCKS("RECORD_3"), - MUSIC_DISC_CAT("RECORD_4"), - MUSIC_DISC_CHIRP("RECORD_5"), - MUSIC_DISC_FAR("RECORD_6"), - MUSIC_DISC_MALL("RECORD_7"), - MUSIC_DISC_MELLOHI("RECORD_8"), - MUSIC_DISC_PIGSTEP("1.16"), - MUSIC_DISC_STAL("RECORD_9"), - MUSIC_DISC_STRAD("RECORD_10"), - MUSIC_DISC_WAIT("RECORD_11"), - MUSIC_DISC_WARD("RECORD_12"), - MUTTON, - MYCELIUM("MYCEL"), - NAME_TAG, - NAUTILUS_SHELL("1.13"), - NETHERITE_AXE("1.16"), - NETHERITE_BLOCK("1.16"), - NETHERITE_BOOTS("1.16"), - NETHERITE_CHESTPLATE("1.16"), - NETHERITE_HELMET("1.16"), - NETHERITE_HOE("1.16"), - NETHERITE_INGOT("1.16"), - NETHERITE_LEGGINGS("1.16"), - NETHERITE_PICKAXE("1.16"), - NETHERITE_SCRAP("1.16"), - NETHERITE_SHOVEL("1.16"), - NETHERITE_SWORD("1.16"), - NETHERRACK, - NETHER_BRICK("NETHER_BRICK_ITEM"), - NETHER_BRICKS("NETHER_BRICK"), - NETHER_BRICK_FENCE("NETHER_FENCE"), - NETHER_BRICK_SLAB(6, "STEP"), - NETHER_BRICK_STAIRS, - NETHER_BRICK_WALL, - NETHER_GOLD_ORE("1.16"), - NETHER_PORTAL("PORTAL"), - NETHER_QUARTZ_ORE("QUARTZ_ORE"), - NETHER_SPROUTS("1.16"), - NETHER_STAR, - /** - * Just like mentioned in https://minecraft.gamepedia.com/Nether_Wart - * Nether wart is also known as nether stalk in the code. - * NETHER_STALK is the planted state of nether warts. - */ - NETHER_WART("NETHER_WARTS", "NETHER_STALK"), - NETHER_WART_BLOCK, - NOTE_BLOCK, - OAK_BOAT("BOAT"), - OAK_BUTTON("WOOD_BUTTON"), - OAK_DOOR("WOOD_DOOR", "WOODEN_DOOR"), - OAK_FENCE("FENCE"), - OAK_FENCE_GATE("FENCE_GATE"), - OAK_LEAVES("LEAVES"), - OAK_LOG("LOG"), - OAK_PLANKS("WOOD"), - OAK_PRESSURE_PLATE("WOOD_PLATE"), - OAK_SAPLING("SAPLING"), - OAK_SIGN("SIGN_POST", "SIGN"), - OAK_SLAB("WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - OAK_STAIRS("WOOD_STAIRS"), - OAK_TRAPDOOR("TRAP_DOOR"), - OAK_WALL_SIGN("WALL_SIGN"), - OAK_WOOD("LOG"), - OBSERVER, - OBSIDIAN, - OCELOT_SPAWN_EGG(98, "MONSTER_EGG"), - ORANGE_BANNER(14, "STANDING_BANNER", "BANNER"), - ORANGE_BED(1, "BED_BLOCK", "BED"), - ORANGE_CARPET(1, "CARPET"), - ORANGE_CONCRETE(1, "CONCRETE"), - ORANGE_CONCRETE_POWDER(1, "CONCRETE_POWDER"), - ORANGE_DYE(14, "INK_SACK"), - ORANGE_GLAZED_TERRACOTTA(1, "1.12", "HARD_CLAY", "STAINED_CLAY", "ORANGE_TERRACOTTA"), - ORANGE_SHULKER_BOX, - ORANGE_STAINED_GLASS(1, "STAINED_GLASS"), - ORANGE_STAINED_GLASS_PANE(1, "STAINED_GLASS_PANE"), - ORANGE_TERRACOTTA(1, "HARD_CLAY", "STAINED_CLAY"), - ORANGE_TULIP(5, "RED_ROSE"), - ORANGE_WALL_BANNER(14, "WALL_BANNER"), - ORANGE_WOOL(1, "WOOL"), - OXEYE_DAISY(8, "RED_ROSE"), - PACKED_ICE, - PAINTING, - PANDA_SPAWN_EGG("1.14"), - PAPER, - PARROT_SPAWN_EGG(105, "MONSTER_EGG"), - PEONY(5, "DOUBLE_PLANT"), - PETRIFIED_OAK_SLAB("WOOD_STEP"), - PHANTOM_MEMBRANE("1.13"), - PHANTOM_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - PIGLIN_BANNER_PATTERN("1.16"), - PIGLIN_SPAWN_EGG(57, "MONSTER_EGG"), - PIG_SPAWN_EGG(90, "MONSTER_EGG"), - PILLAGER_SPAWN_EGG("1.14"), - PINK_BANNER(9, "STANDING_BANNER", "BANNER"), - PINK_BED(6, "BED_BLOCK", "BED"), - PINK_CARPET(6, "CARPET"), - PINK_CONCRETE(6, "CONCRETE"), - PINK_CONCRETE_POWDER(6, "CONCRETE_POWDER"), - PINK_DYE(9, "INK_SACK"), - PINK_GLAZED_TERRACOTTA(6, "1.12", "HARD_CLAY", "STAINED_CLAY", "PINK_TERRACOTTA"), - PINK_SHULKER_BOX, - PINK_STAINED_GLASS(6, "STAINED_GLASS"), - PINK_STAINED_GLASS_PANE(6, "THIN_GLASS", "STAINED_GLASS_PANE"), - PINK_TERRACOTTA(6, "HARD_CLAY", "STAINED_CLAY"), - PINK_TULIP(7, "RED_ROSE"), - PINK_WALL_BANNER(9, "WALL_BANNER"), - PINK_WOOL(6, "WOOL"), - PISTON("PISTON_BASE"), - PISTON_HEAD("PISTON_EXTENSION"), - PLAYER_HEAD(3, "SKULL", "SKULL_ITEM"), - PLAYER_WALL_HEAD(3, "SKULL", "SKULL_ITEM"), - PODZOL(2, "DIRT"), - POISONOUS_POTATO, - POLAR_BEAR_SPAWN_EGG(102, "MONSTER_EGG"), - POLISHED_ANDESITE(6, "STONE"), - POLISHED_ANDESITE_SLAB, - POLISHED_ANDESITE_STAIRS, - POLISHED_BASALT("1.16"), - POLISHED_BLACKSTONE("1.16"), - POLISHED_BLACKSTONE_BRICKS("1.16"), - POLISHED_BLACKSTONE_BRICK_SLAB("1.16"), - POLISHED_BLACKSTONE_BRICK_STAIRS("1.16"), - POLISHED_BLACKSTONE_BRICK_WALL("1.16"), - POLISHED_BLACKSTONE_BUTTON("1.16"), - POLISHED_BLACKSTONE_PRESSURE_PLATE("1.16"), - POLISHED_BLACKSTONE_SLAB("1.16"), - POLISHED_BLACKSTONE_STAIRS("1.16"), - POLISHED_BLACKSTONE_WALL("1.16"), - POLISHED_DIORITE(4, "STONE"), - POLISHED_DIORITE_SLAB, - POLISHED_DIORITE_STAIRS, - POLISHED_GRANITE(2, "STONE"), - POLISHED_GRANITE_SLAB, - POLISHED_GRANITE_STAIRS, - POPPED_CHORUS_FRUIT("CHORUS_FRUIT_POPPED"), - POPPY("RED_ROSE"), - PORKCHOP("PORK"), - POTATO("POTATO_ITEM"), - POTATOES("POTATO"), - POTION, - POTTED_ACACIA_SAPLING(4, "SAPLING", "FLOWER_POT"), - POTTED_ALLIUM(2, "RED_ROSE", "FLOWER_POT"), - POTTED_AZURE_BLUET(3, "RED_ROSE", "FLOWER_POT"), - POTTED_BAMBOO, - POTTED_BIRCH_SAPLING(2, "SAPLING", "FLOWER_POT"), - POTTED_BLUE_ORCHID(1, "RED_ROSE", "FLOWER_POT"), - POTTED_BROWN_MUSHROOM("FLOWER_POT"), - POTTED_CACTUS("FLOWER_POT"), - POTTED_CORNFLOWER, - POTTED_CRIMSON_FUNGUS("1.16"), - POTTED_CRIMSON_ROOTS("1.16"), - POTTED_DANDELION("YELLOW_FLOWER", "FLOWER_POT"), - POTTED_DARK_OAK_SAPLING(5, "SAPLING", "FLOWER_POT"), - POTTED_DEAD_BUSH("FLOWER_POT"), - POTTED_FERN(2, "LONG_GRASS", "FLOWER_POT"), - POTTED_JUNGLE_SAPLING(3, "SAPLING", "FLOWER_POT"), - POTTED_LILY_OF_THE_VALLEY, - POTTED_OAK_SAPLING("SAPLING", "FLOWER_POT"), - POTTED_ORANGE_TULIP(5, "RED_ROSE", "FLOWER_POT"), - POTTED_OXEYE_DAISY(8, "RED_ROSE", "FLOWER_POT"), - POTTED_PINK_TULIP(7, "RED_ROSE", "FLOWER_POT"), - POTTED_POPPY("RED_ROSE", "FLOWER_POT"), - POTTED_RED_MUSHROOM("FLOWER_POT"), - POTTED_RED_TULIP(4, "RED_ROSE", "FLOWER_POT"), - POTTED_SPRUCE_SAPLING(1, "SAPLING", "FLOWER_POT"), - POTTED_WARPED_FUNGUS("1.16"), - POTTED_WARPED_ROOTS("1.16"), - POTTED_WHITE_TULIP(6, "RED_ROSE", "FLOWER_POT"), - POTTED_WITHER_ROSE, - POWERED_RAIL, - PRISMARINE, - PRISMARINE_BRICKS(2, "PRISMARINE"), - PRISMARINE_BRICK_SLAB(4, "STEP"), - PRISMARINE_BRICK_STAIRS("1.13"), - PRISMARINE_CRYSTALS, - PRISMARINE_SHARD, - PRISMARINE_SLAB("1.13"), - PRISMARINE_STAIRS("1.13"), - PRISMARINE_WALL, - PUFFERFISH(3, "RAW_FISH"), - PUFFERFISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), - PUFFERFISH_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - PUMPKIN, - PUMPKIN_PIE, - PUMPKIN_SEEDS, - PUMPKIN_STEM, - PURPLE_BANNER(5, "STANDING_BANNER", "BANNER"), - PURPLE_BED(10, "BED_BLOCK", "BED"), - PURPLE_CARPET(10, "CARPET"), - PURPLE_CONCRETE(10, "CONCRETE"), - PURPLE_CONCRETE_POWDER(10, "CONCRETE_POWDER"), - PURPLE_DYE(5, "INK_SACK"), - PURPLE_GLAZED_TERRACOTTA(10, "1.12", "HARD_CLAY", "STAINED_CLAY", "PURPLE_TERRACOTTA"), - PURPLE_SHULKER_BOX, - PURPLE_STAINED_GLASS(10, "STAINED_GLASS"), - PURPLE_STAINED_GLASS_PANE(10, "THIN_GLASS", "STAINED_GLASS_PANE"), - PURPLE_TERRACOTTA(10, "HARD_CLAY", "STAINED_CLAY"), - PURPLE_WALL_BANNER(5, "WALL_BANNER"), - PURPLE_WOOL(10, "WOOL"), - PURPUR_BLOCK, - PURPUR_PILLAR, - PURPUR_SLAB("PURPUR_DOUBLE_SLAB"), - PURPUR_STAIRS, - QUARTZ, - QUARTZ_BLOCK, - QUARTZ_BRICKS("1.16"), - QUARTZ_PILLAR(2, "QUARTZ_BLOCK"), - QUARTZ_SLAB(7, "STEP"), - QUARTZ_STAIRS, - RABBIT, - RABBIT_FOOT, - RABBIT_HIDE, - RABBIT_SPAWN_EGG(101, "MONSTER_EGG"), - RABBIT_STEW, - RAIL("RAILS"), - RAVAGER_SPAWN_EGG("1.14"), - REDSTONE, - REDSTONE_BLOCK, - /** - * Unlike redstone torch, REDSTONE_LAMP_ON isn't an item. - * The name is just here on the list for matching. - * - * @see #REDSTONE_TORCH - */ - REDSTONE_LAMP("REDSTONE_LAMP_ON", "REDSTONE_LAMP_OFF"), - REDSTONE_ORE("GLOWING_REDSTONE_ORE"), - /** - * REDSTONE_TORCH_OFF isn't an item, but a block. - * But REDSTONE_TORCH_ON is the item. - * The name is just here on the list for matching. - */ - REDSTONE_TORCH("REDSTONE_TORCH_OFF", "REDSTONE_TORCH_ON"), - REDSTONE_WALL_TORCH, - REDSTONE_WIRE, - RED_BANNER(1, "STANDING_BANNER", "BANNER"), - /** - * Data value 14 or 0 - */ - RED_BED(0, "BED_BLOCK", "BED"), - RED_CARPET(14, "CARPET"), - RED_CONCRETE(14, "CONCRETE"), - RED_CONCRETE_POWDER(14, "CONCRETE_POWDER"), - RED_DYE(1, "INK_SACK", "ROSE_RED"), - RED_GLAZED_TERRACOTTA(14, "1.12", "HARD_CLAY", "STAINED_CLAY", "RED_TERRACOTTA"), - RED_MUSHROOM, - RED_MUSHROOM_BLOCK("RED_MUSHROOM", "HUGE_MUSHROOM_2"), - RED_NETHER_BRICKS("RED_NETHER_BRICK"), - RED_NETHER_BRICK_SLAB(4, "STEP"), - RED_NETHER_BRICK_STAIRS, - RED_NETHER_BRICK_WALL, - RED_SAND(1, "SAND"), - RED_SANDSTONE, - RED_SANDSTONE_SLAB("STONE_SLAB2", "DOUBLE_STONE_SLAB2"), - RED_SANDSTONE_STAIRS, - RED_SANDSTONE_WALL, - RED_SHULKER_BOX, - RED_STAINED_GLASS(14, "STAINED_GLASS"), - RED_STAINED_GLASS_PANE(14, "THIN_GLASS", "STAINED_GLASS_PANE"), - RED_TERRACOTTA(14, "HARD_CLAY", "STAINED_CLAY"), - RED_TULIP(4, "RED_ROSE"), - RED_WALL_BANNER(1, "WALL_BANNER"), - RED_WOOL(14, "WOOL"), - REPEATER("DIODE_BLOCK_ON", "DIODE_BLOCK_OFF", "DIODE"), - REPEATING_COMMAND_BLOCK("COMMAND", "COMMAND_REPEATING"), - RESPAWN_ANCHOR("1.16"), - ROSE_BUSH(4, "DOUBLE_PLANT"), - ROTTEN_FLESH, - SADDLE, - SALMON(1, "RAW_FISH"), - SALMON_BUCKET("1.13", "BUCKET", "WATER_BUCKET", ""), - SALMON_SPAWN_EGG("1.13", "MONSTER_EGG", ""), - SAND, - SANDSTONE, - SANDSTONE_SLAB(1, "STEP", "STONE_SLAB", "DOUBLE_STEP"), - SANDSTONE_STAIRS, - SANDSTONE_WALL, - SCAFFOLDING("1.14", "SLIME_BLOCK", ""), - SCUTE("1.13"), - SEAGRASS("1.13", "GRASS", ""), - SEA_LANTERN, - SEA_PICKLE("1.13"), - SHEARS, - SHEEP_SPAWN_EGG(91, "MONSTER_EGG"), - SHIELD, - SHROOMLIGHT("1.16"), - SHULKER_BOX("PURPLE_SHULKER_BOX"), - SHULKER_SHELL, - SHULKER_SPAWN_EGG(69, "MONSTER_EGG"), - SILVERFISH_SPAWN_EGG(60, "MONSTER_EGG"), - SKELETON_HORSE_SPAWN_EGG(28, "MONSTER_EGG"), - SKELETON_SKULL("SKULL", "SKULL_ITEM"), - SKELETON_SPAWN_EGG(51, "MONSTER_EGG"), - SKELETON_WALL_SKULL("SKULL", "SKULL_ITEM"), - SKULL_BANNER_PATTERN, - SLIME_BALL, - SLIME_BLOCK, - SLIME_SPAWN_EGG(55, "MONSTER_EGG"), - SMITHING_TABLE, - SMOKER("1.14", "FURNACE", ""), - SMOOTH_QUARTZ("1.13", "QUARTZ", ""), - SMOOTH_QUARTZ_SLAB(7, "STEP"), - SMOOTH_QUARTZ_STAIRS, - SMOOTH_RED_SANDSTONE(2, "RED_SANDSTONE"), - SMOOTH_RED_SANDSTONE_SLAB("STONE_SLAB2"), - SMOOTH_RED_SANDSTONE_STAIRS, - SMOOTH_SANDSTONE(2, "SANDSTONE"), - SMOOTH_SANDSTONE_SLAB("STEP"), - SMOOTH_SANDSTONE_STAIRS, - SMOOTH_STONE("STEP"), - SMOOTH_STONE_SLAB("STEP"), - SNOW, - SNOWBALL("SNOW_BALL"), - SNOW_BLOCK, - SOUL_CAMPFIRE("1.16"), - SOUL_FIRE("1.16"), - SOUL_LANTERN("1.16"), - SOUL_SAND, - SOUL_SOIL("1.16"), - SOUL_TORCH("1.16"), - SOUL_WALL_TORCH("1.16"), - SPAWNER("MOB_SPAWNER"), - SPECTRAL_ARROW("1.9", "ARROW", ""), - SPIDER_EYE, - SPIDER_SPAWN_EGG(52, "MONSTER_EGG"), - SPLASH_POTION, - SPONGE, - SPRUCE_BOAT("BOAT_SPRUCE"), - SPRUCE_BUTTON("WOOD_BUTTON"), - SPRUCE_DOOR("SPRUCE_DOOR_ITEM", "SPRUCE_DOOR"), - SPRUCE_FENCE, - SPRUCE_FENCE_GATE, - SPRUCE_LEAVES(1, "LEAVES", "LEAVES_2"), - SPRUCE_LOG(1, "LOG"), - SPRUCE_PLANKS(1, "WOOD"), - SPRUCE_PRESSURE_PLATE("WOOD_PLATE"), - SPRUCE_SAPLING(1, "SAPLING"), - SPRUCE_SIGN("SIGN_POST", "SIGN"), - SPRUCE_SLAB(1, "WOOD_STEP", "WOODEN_SLAB", "WOOD_DOUBLE_STEP"), - SPRUCE_STAIRS("SPRUCE_WOOD_STAIRS"), - SPRUCE_TRAPDOOR("TRAP_DOOR"), - SPRUCE_WALL_SIGN("WALL_SIGN"), - SPRUCE_WOOD(1, "LOG"), - SQUID_SPAWN_EGG(94, "MONSTER_EGG"), - STICK, - STICKY_PISTON("PISTON_BASE", "PISTON_STICKY_BASE"), - STONE, - STONECUTTER("1.14"), - STONE_AXE, - STONE_BRICKS("SMOOTH_BRICK"), - STONE_BRICK_SLAB(4, "STEP", "STONE_SLAB", "DOUBLE_STEP"), - STONE_BRICK_STAIRS("SMOOTH_STAIRS"), - STONE_BRICK_WALL, - STONE_BUTTON, - STONE_HOE, - STONE_PICKAXE, - STONE_PRESSURE_PLATE("STONE_PLATE"), - STONE_SHOVEL("STONE_SPADE"), - STONE_SLAB("STEP", "DOUBLE_STEP"), - STONE_STAIRS, - STONE_SWORD, - STRAY_SPAWN_EGG(6, "MONSTER_EGG"), - STRIDER_SPAWN_EGG("1.16"), - STRING, - STRIPPED_ACACIA_LOG("LOG_2"), - STRIPPED_ACACIA_WOOD("LOG_2"), - STRIPPED_BIRCH_LOG(2, "LOG"), - STRIPPED_BIRCH_WOOD(2, "LOG"), - STRIPPED_CRIMSON_HYPHAE("1.16"), - STRIPPED_CRIMSON_STEM("1.16"), - STRIPPED_DARK_OAK_LOG("LOG"), - STRIPPED_DARK_OAK_WOOD("LOG"), - STRIPPED_JUNGLE_LOG(3, "LOG"), - STRIPPED_JUNGLE_WOOD(3, "LOG"), - STRIPPED_OAK_LOG("LOG"), - STRIPPED_OAK_WOOD("LOG"), - STRIPPED_SPRUCE_LOG(1, "LOG"), - STRIPPED_SPRUCE_WOOD(1, "LOG"), - STRIPPED_WARPED_HYPHAE("1.16"), - STRIPPED_WARPED_STEM("1.16"), - STRUCTURE_BLOCK, - /** - * Originally developers used barrier blocks for its purpose. - * So technically this isn't really considered as a suggested material. - */ - STRUCTURE_VOID("1.10", "", "BARRIER"), - SUGAR, - /** - * Sugar Cane is a known material in pre-1.13 - * Use XBlock when comparing block types. - */ - SUGAR_CANE("SUGAR_CANE_BLOCK"), - SUNFLOWER("DOUBLE_PLANT"), - SUSPICIOUS_STEW("1.14", "MUSHROOM_STEW", ""), - SWEET_BERRIES("1.14"), - SWEET_BERRY_BUSH("1.14", "GRASS", ""), - TALL_GRASS(2, "DOUBLE_PLANT"), - TALL_SEAGRASS(2, "1.13", "TALL_GRASS", ""), - TARGET("1.16"), - TERRACOTTA("HARD_CLAY"), - TIPPED_ARROW("1.9", "ARROW", ""), - TNT, - TNT_MINECART("EXPLOSIVE_MINECART"), - TORCH, - TOTEM_OF_UNDYING("TOTEM"), - TRADER_LLAMA_SPAWN_EGG(103, "1.14", "MONSTER_EGG", ""), - TRAPPED_CHEST, - TRIDENT("1.13"), - TRIPWIRE, - TRIPWIRE_HOOK, - TROPICAL_FISH(2, "RAW_FISH"), - TROPICAL_FISH_BUCKET("1.13", "BUCKET", "WATER_BUCKET"), - TROPICAL_FISH_SPAWN_EGG("1.13", "MONSTER_EGG"), - TUBE_CORAL("1.13"), - TUBE_CORAL_BLOCK("1.13"), - TUBE_CORAL_FAN("1.13"), - TUBE_CORAL_WALL_FAN, - TURTLE_EGG("1.13", "EGG", ""), - TURTLE_HELMET("1.13", "IRON_HELMET", ""), - TURTLE_SPAWN_EGG("1.13", "CHICKEN_SPAWN_EGG", ""), - TWISTING_VINES("1.16"), - TWISTING_VINES_PLANT("1.16"), - VEX_SPAWN_EGG(35, "MONSTER_EGG"), - VILLAGER_SPAWN_EGG(120, "MONSTER_EGG"), - VINDICATOR_SPAWN_EGG(36, "MONSTER_EGG"), - VINE, - /** - * 1.13 tag is not added because it's the same thing as {@link #AIR} - * - * @see #CAVE_AIR - */ - VOID_AIR("AIR"), - WALL_TORCH("TORCH"), - WANDERING_TRADER_SPAWN_EGG("1.14", "VILLAGER_SPAWN_EGG", ""), - WARPED_BUTTON("1.16"), - WARPED_DOOR("1.16"), - WARPED_FENCE("1.16"), - WARPED_FENCE_GATE("1.16"), - WARPED_FUNGUS("1.16"), - WARPED_FUNGUS_ON_A_STICK("1.16"), - WARPED_HYPHAE("1.16"), - WARPED_NYLIUM("1.16"), - WARPED_PLANKS("1.16"), - WARPED_PRESSURE_PLATE("1.16"), - WARPED_ROOTS("1.16"), - WARPED_SIGN("1.16", "SIGN_POST"), - WARPED_SLAB("1.16"), - WARPED_STAIRS("1.16"), - WARPED_STEM("1.16"), - WARPED_TRAPDOOR("1.16"), - WARPED_WALL_SIGN("1.16", "WALL_SIGN"), - WARPED_WART_BLOCK("1.16"), - /** - * This is used for blocks only. - * In 1.13- WATER will turn into STATIONARY_WATER after it finished spreading. - * After 1.13+ this uses - * https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/data/Levelled.html water flowing system. - * Use XBlock for this instead. - */ - WATER("STATIONARY_WATER"), - WATER_BUCKET, - WEEPING_VINES("1.16"), - WEEPING_VINES_PLANT("1.16"), - WET_SPONGE(1, "SPONGE"), - /** - * Wheat is a known material in pre-1.13 - * Use XBlock when comparing block types. - */ - WHEAT("CROPS"), - WHEAT_SEEDS("SEEDS"), - WHITE_BANNER(15, "STANDING_BANNER", "BANNER"), - WHITE_BED("BED_BLOCK", "BED"), - WHITE_CARPET("CARPET"), - WHITE_CONCRETE("CONCRETE"), - WHITE_CONCRETE_POWDER("CONCRETE_POWDER"), - WHITE_DYE(15, "1.14", "INK_SACK", "BONE_MEAL"), - WHITE_GLAZED_TERRACOTTA("1.12", "HARD_CLAY", "STAINED_CLAY"), - WHITE_SHULKER_BOX, - WHITE_STAINED_GLASS("STAINED_GLASS"), - WHITE_STAINED_GLASS_PANE("THIN_GLASS", "STAINED_GLASS_PANE"), - WHITE_TERRACOTTA("HARD_CLAY", "STAINED_CLAY", "TERRACOTTA"), - WHITE_TULIP(6, "RED_ROSE"), - WHITE_WALL_BANNER(15, "WALL_BANNER"), - WHITE_WOOL("WOOL"), - WITCH_SPAWN_EGG(66, "MONSTER_EGG"), - WITHER_ROSE("1.14", "BLACK_DYE", ""), - WITHER_SKELETON_SKULL(1, "SKULL", "SKULL_ITEM"), - WITHER_SKELETON_SPAWN_EGG(5, "MONSTER_EGG"), - WITHER_SKELETON_WALL_SKULL(1, "SKULL", "SKULL_ITEM"), - WOLF_SPAWN_EGG(95, "MONSTER_EGG"), - WOODEN_AXE("WOOD_AXE"), - WOODEN_HOE("WOOD_HOE"), - WOODEN_PICKAXE("WOOD_PICKAXE"), - WOODEN_SHOVEL("WOOD_SPADE"), - WOODEN_SWORD("WOOD_SWORD"), - WRITABLE_BOOK("BOOK_AND_QUILL"), - WRITTEN_BOOK, - YELLOW_BANNER(11, "STANDING_BANNER", "BANNER"), - YELLOW_BED(4, "BED_BLOCK", "BED"), - YELLOW_CARPET(4, "CARPET"), - YELLOW_CONCRETE(4, "CONCRETE"), - YELLOW_CONCRETE_POWDER(4, "CONCRETE_POWDER"), - YELLOW_DYE(11, "INK_SACK", "DANDELION_YELLOW"), - YELLOW_GLAZED_TERRACOTTA(4, "1.12", "HARD_CLAY", "STAINED_CLAY", "YELLOW_TERRACOTTA"), - YELLOW_SHULKER_BOX, - YELLOW_STAINED_GLASS(4, "STAINED_GLASS"), - YELLOW_STAINED_GLASS_PANE(4, "THIN_GLASS", "STAINED_GLASS_PANE"), - YELLOW_TERRACOTTA(4, "HARD_CLAY", "STAINED_CLAY"), - YELLOW_WALL_BANNER(11, "WALL_BANNER"), - YELLOW_WOOL(4, "WOOL"), - ZOGLIN_SPAWN_EGG("1.16"), - ZOMBIE_HEAD(2, "SKULL", "SKULL_ITEM"), - ZOMBIE_HORSE_SPAWN_EGG(29, "MONSTER_EGG"), - ZOMBIE_SPAWN_EGG(54, "MONSTER_EGG"), - ZOMBIE_VILLAGER_SPAWN_EGG(27, "MONSTER_EGG"), - ZOMBIE_WALL_HEAD(2, "SKULL", "SKULL_ITEM"), - ZOMBIFIED_PIGLIN_SPAWN_EGG(57, "MONSTER_EGG", "ZOMBIE_PIGMAN_SPAWN_EGG"); - - - /** - * Cached set of {@link XMaterial#values()} to avoid allocating memory for - * calling the method every time. - * This list is unmodifiable. - * - * @since 2.0.0 - */ - public static final List VALUES = Collections.unmodifiableList(Arrays.asList(values())); - - /** - * We don't want to use {@link Enums#getIfPresent(Class, String)} to avoid a few checks. - * - * @since 5.1.0 - */ - private static final Map NAMES = new HashMap<>(); - - /** - * A set of material names that can be damaged. - *

- * Most of the names are not complete as this list is intended to be - * checked with {@link String#contains} for memory usage. - * - * @since 1.0.0 - */ - private static final Set DAMAGEABLE = new HashSet<>(Arrays.asList( - "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", - "SWORD", "AXE", "PICKAXE", "SHOVEL", "HOE", - "ELYTRA", "TRIDENT", "HORSE_ARMOR", "BARDING", - "SHEARS", "FLINT_AND_STEEL", "BOW", "FISHING_ROD", - "CARROT_ON_A_STICK", "CARROT_STICK", "SPADE", "SHIELD" - )); - /** - * XMaterial Paradox (Duplication Check) - *

- * A map of duplicated material names in 1.13 and 1.12 that will conflict with the legacy names. - * Values are the new material names. - *
- * Duplicates are normally only checked by keys, not values. - * - * @since 3.0.0 - */ - private static final EnumMap DUPLICATED = new EnumMap(XMaterial.class); - /** - * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. - * For strings that match a certain XMaterial. Mostly cached for configs. - * - * @since 1.0.0 - */ - private static final Cache NAME_CACHE = CacheBuilder.newBuilder() - .expireAfterAccess(15, TimeUnit.MINUTES) - .build(); - /** - * Guava (Google Core Libraries for Java)'s cache for performance and timed caches. - * For XMaterials that are already parsed once. - * - * @since 3.0.0 - */ - private static final Cache> PARSED_CACHE = CacheBuilder.newBuilder() - .expireAfterAccess(10, TimeUnit.MINUTES) - .build(); - /* - * A set of all the legacy names without duplicates. - *

- * It'll help to free up a lot of memory if it's not used. - * Add it back if you need it. - * - * @see #containsLegacy(String) - * @since 2.2.0 - * - private static final ImmutableSet LEGACY_VALUES = VALUES.stream().map(XMaterial::getLegacy) - .flatMap(Arrays::stream) - .filter(m -> m.charAt(1) == '.') - .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf)); - */ - /** - * This is used for {@link #isOneOf(Collection)} - * - * @since 3.4.0 - */ - private static final LoadingCache CACHED_REGEX = CacheBuilder.newBuilder() - .expireAfterAccess(1, TimeUnit.HOURS) - .build(new CacheLoader() { - @Override - public Pattern load(@Nonnull String str) { - try { - return Pattern.compile(str); - } catch (PatternSyntaxException ex) { - ex.printStackTrace(); - return null; - } - } - }); - /** - * The current version of the server in the a form of a major version. - * - * @since 1.0.0 - */ - private static final int VERSION = Integer.parseInt(getMajorVersion(Bukkit.getVersion()).substring(2)); - /** - * Cached result if the server version is after the v1.13 flattening update. - * Please don't mistake this with flat-chested people. It happened. - * - * @since 3.0.0 - */ - private static final boolean ISFLAT = supports(13); - - static { - DUPLICATED.put(MELON, MELON_SLICE); - DUPLICATED.put(CARROT, CARROTS); - DUPLICATED.put(POTATO, POTATOES); - DUPLICATED.put(BEETROOT, BEETROOTS); - DUPLICATED.put(BROWN_MUSHROOM, BROWN_MUSHROOM_BLOCK); - DUPLICATED.put(BRICK, BRICKS); - DUPLICATED.put(NETHER_BRICK, NETHER_BRICKS); - - // Illegal Elements - // Since both 1.12 and 1.13 have _DOOR XMaterial will use it - // for 1.12 to parse the material, but it needs _DOOR_ITEM. - // We'll trick XMaterial into thinking this needs to be parsed - // using the old methods. - // Some of these materials have their enum name added to the legacy list as well. - DUPLICATED.put(DARK_OAK_DOOR, DARK_OAK_DOOR); - DUPLICATED.put(ACACIA_DOOR, ACACIA_DOOR); - DUPLICATED.put(BIRCH_DOOR, BIRCH_DOOR); - DUPLICATED.put(JUNGLE_DOOR, JUNGLE_DOOR); - DUPLICATED.put(SPRUCE_DOOR, SPRUCE_DOOR); - DUPLICATED.put(CAULDRON, CAULDRON); - DUPLICATED.put(BREWING_STAND, BREWING_STAND); - } - - static { - for (XMaterial material : VALUES) NAMES.put(material.name(), material); - } - - /** - * The data value of this material https://minecraft.gamepedia.com/Java_Edition_data_values/Pre-flattening - * - * @see #getData() - */ - private final byte data; - /** - * A list of material names that was being used for older verions. - * - * @see #getLegacy() - */ - private final String[] legacy; - - XMaterial(int data, String... legacy) { - this.data = (byte) data; - this.legacy = legacy; - } - - XMaterial() { - this(0); - } - - XMaterial(String... legacy) { - this(0, legacy); - } - - /** - * Checks if the version is 1.13 Aquatic Update or higher. - * An invocation of this method yields the cached result from the expression: - *

- *

- * {@link #supports(int) 13}} - *
- * - * @return true if 1.13 or higher. - * @see #getVersion() - * @see #supports(int) - * @since 1.0.0 - */ - public static boolean isNewVersion() { - return ISFLAT; - } - - /** - * This is just an extra method that method that can be used for many cases. - * It can be used in {@link org.bukkit.event.player.PlayerInteractEvent} - * or when accessing {@link org.bukkit.entity.Player#getMainHand()}, - * or other compatibility related methods. - *

- * An invocation of this method yields exactly the same result as the expression: - *

- *

- * !{@link #supports(int)} 9 - *
- * - * @since 2.0.0 - */ - public static boolean isOneEight() { - return !supports(9); - } - - /** - * Gets the {@link XMaterial} with this name without throwing an exception. - * - * @param name the name of the material. - * @return an optional that can be empty. - * @since 5.1.0 - */ - @Nonnull - private static Optional getIfPresent(@Nonnull String name) { - return Optional.ofNullable(NAMES.get(name)); - } - - /** - * The current version of the server. - * - * @return the current server version or 0.0 if unknown. - * @see #isNewVersion() - * @since 2.0.0 - */ - public static double getVersion() { - return VERSION; - } - - /** - * When using newer versions of Minecraft ({@link #isNewVersion()}), helps - * to find the old material name with its data value using a cached search for optimization. - * - * @see #matchDefinedXMaterial(String, byte) - * @since 1.0.0 - */ - @Nullable - private static XMaterial requestOldXMaterial(@Nonnull String name, byte data) { - String holder = name + data; - XMaterial cache = NAME_CACHE.getIfPresent(holder); - if (cache != null) return cache; - - for (XMaterial material : VALUES) { - // Not using material.name().equals(name) check is intended. - if ((data == -1 || data == material.data) && material.anyMatchLegacy(name)) { - NAME_CACHE.put(holder, material); - return material; - } - } - - return null; - } - - /** - * Checks if XMaterial enum contains a material with the given name. - *

- * You should use {@link #matchXMaterial(String)} instead if you're going - * to get the XMaterial object after checking if it's available in the list - * by doing a simple {@link Optional#isPresent()} check. - * This is just to avoid multiple loops for maximum performance. - * - * @param name name of the material. - * @return true if XMaterial enum has this material. - * @since 1.0.0 - */ - public static boolean contains(@Nonnull String name) { - Validate.notEmpty(name, "Cannot check for null or empty material name"); - name = format(name); - - for (XMaterial materials : VALUES) { - if (materials.name().equals(name)) return true; - } - return false; - } - - /** - * Parses the given material name as an XMaterial with unspecified data value. - * - * @see #matchXMaterialWithData(String) - * @since 2.0.0 - */ - @Nonnull - public static Optional matchXMaterial(@Nonnull String name) { - Validate.notEmpty(name, "Cannot match a material with null or empty material name"); - Optional oldMatch = matchXMaterialWithData(name); - if (oldMatch.isPresent()) return oldMatch; - return matchDefinedXMaterial(format(name), (byte) -1); - } - - /** - * Parses material name and data value from the specified string. - * The separator for the material name and its data value is {@code :} - * Spaces are allowed. Mostly used when getting materials from config for old school minecrafters. - *

- * Examples - *

-     *     {@code INK_SACK:1 -> RED_DYE}
-     *     {@code WOOL: 14  -> RED_WOOL}
-     * 
- * - * @param name the material string that consists of the material name, data and separator character. - * @return the parsed XMaterial. - * @see #matchXMaterial(String) - * @since 3.0.0 - */ - @Nonnull - private static Optional matchXMaterialWithData(String name) { - int index = name.indexOf(':'); - if (index != -1) { - String mat = format(name.substring(0, index)); - - try { - byte data = (byte) Integer.parseInt(StringUtils.deleteWhitespace(name.substring(index + 1))); - return matchDefinedXMaterial(mat, data); - } catch (NumberFormatException ignored) { - } - } - - return Optional.empty(); - } - - /** - * Parses the given material as an XMaterial. - * - * @throws IllegalArgumentException may be thrown as an unexpected exception. - * @see #matchDefinedXMaterial(String, byte) - * @see #matchXMaterial(ItemStack) - * @since 2.0.0 - */ - @Nonnull - public static XMaterial matchXMaterial(@Nonnull Material material) { - Objects.requireNonNull(material, "Cannot match null material"); - return matchDefinedXMaterial(material.name(), (byte) -1) - .orElseThrow(() -> new IllegalArgumentException("Unsupported material with no data value: " + material.name())); - } - - /** - * Parses the given item as an XMaterial using its material and data value (durability). - * - * @param item the ItemStack to match. - * @return an XMaterial if matched any. - * @throws IllegalArgumentException may be thrown as an unexpected exception. - * @see #matchDefinedXMaterial(String, byte) - * @since 2.0.0 - */ - @Nonnull - @SuppressWarnings("deprecation") - public static XMaterial matchXMaterial(@Nonnull ItemStack item) { - Objects.requireNonNull(item, "Cannot match null ItemStack"); - String material = item.getType().name(); - byte data = (byte) (ISFLAT || isDamageable(material) ? 0 : item.getDurability()); - - return matchDefinedXMaterial(material, data) - .orElseThrow(() -> new IllegalArgumentException("Unsupported material: " + material + " (" + data + ')')); - } - - /** - * Parses the given material name and data value as an XMaterial. - * All the values passed to this method will not be null or empty and are formatted correctly. - * - * @param name the formatted name of the material. - * @param data the data value of the material. - * @return an XMaterial (with the same data value if specified) - * @see #matchXMaterial(Material) - * @see #matchXMaterial(int, byte) - * @see #matchXMaterial(ItemStack) - * @since 3.0.0 - */ - @Nonnull - private static Optional matchDefinedXMaterial(@Nonnull String name, byte data) { - boolean duplicated = isDuplicated(name); - - // Do basic number and boolean checks before accessing more complex enum stuff. - // Maybe we can simplify (ISFLAT || !duplicated) with the (!ISFLAT && duplicated) under it to save a few nanoseconds? - // if (!Boolean.valueOf(Boolean.getBoolean(Boolean.TRUE.toString())).equals(Boolean.FALSE.booleanValue())) return null; - Optional xMaterial = null; - if (data <= 0 && (ISFLAT || !duplicated)) { - // Apparently the transform method is more efficient than toJavaUtil() - // toJavaUtil isn't even supported in older versions. - xMaterial = getIfPresent(name); - if (xMaterial.isPresent()) return xMaterial; - } - - // XMaterial Paradox (Duplication Check) - // I've concluded that this is just an infinite loop that keeps - // going around the Singular Form and the Plural Form materials. A waste of brain cells and a waste of time. - // This solution works just fine anyway. - XMaterial xMat = requestOldXMaterial(name, data); - if (xMat == null) { - // Special case. Refer to FILLED_MAP for more info. - if (data > 0 && name.endsWith("MAP")) return Optional.of(FILLED_MAP); - return Optional.empty(); - } - - if (!ISFLAT && duplicated && xMat.name().charAt(xMat.name().length() - 1) == 'S') { - // A solution for XMaterial Paradox. - // Manually parses the duplicated materials to find the exact material based on the server version. - // If ends with "S" -> Plural Form Material - return xMaterial == null ? getIfPresent(name) : xMaterial; - } - return Optional.ofNullable(xMat); - } - - /** - * XMaterial Paradox (Duplication Check) - * Checks if the material has any duplicates. - *

- * Example: - *

{@code MELON, CARROT, POTATO, BEETROOT -> true} - * - * @param name the name of the material to check. - * @return true if there's a duplicated material for this material, otherwise false. - * @see #isDuplicated() - * @since 2.0.0 - */ - private static boolean isDuplicated(@Nonnull String name) { - // Don't use matchXMaterial() since this method is being called from matchXMaterial() itself and will cause a StackOverflowError. - for (Map.Entry duplicated : DUPLICATED.entrySet()) { - XMaterial material = duplicated.getKey(); - if (material.name().equals(name) || material.anyMatchLegacy(name)) return true; - } - return false; - } - - /** - * Gets the XMaterial based on the material's ID (Magic Value) and data value.
- * You should avoid using this for performance issues. - * - * @param id the ID (Magic value) of the material. - * @param data the data value of the material. - * @return a parsed XMaterial with the same ID and data value. - * @see #matchXMaterial(ItemStack) - * @since 2.0.0 - */ - @Nonnull - public static Optional matchXMaterial(int id, byte data) { - if (id < 0 || data < 0) return Optional.empty(); - - // Looping through Material.values() will take longer. - for (XMaterial materials : VALUES) - if (materials.data == data && materials.getId() == id) return Optional.of(materials); - return Optional.empty(); - } - - /** - * Attempts to build the string like an enum name. - * Removes all the spaces, and extra non-English characters. Also removes some config/in-game based strings. - * While this method is hard to maintain, it's extremely efficient. It's approximately more than x5 times faster than - * the normal RegEx + String Methods approach for both formatted and unformatted material names. - * - * @param name the material name to modify. - * @return a Material enum name. - * @since 2.0.0 - */ - @Nonnull - protected static String format(@Nonnull String name) { - int len = name.length(); - char[] chs = new char[len]; - int count = 0; - boolean appendUnderline = false; - - for (int i = 0; i < len; ++i) { - char ch = name.charAt(i); - - if (!appendUnderline && count != 0 && (ch == '-' || ch == ' ' || ch == '_') && chs[count] != '_') appendUnderline = true; - else { - boolean number = false; - // Old materials have numbers in them. - if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (number = (ch >= '0' && ch <= '9'))) { - if (appendUnderline) { - chs[count++] = '_'; - appendUnderline = false; - } - - if (number) chs[count++] = ch; - else chs[count++] = (char) (ch & 0x5f); - } - } - } - - return new String(chs, 0, count); - } - - /** - * Checks if the specified version is the same version or higher than the current server version. - * - * @param version the major version to be checked. "1." is ignored. E.g. 1.12 = 12 | 1.9 = 9 - * @return true of the version is equal or higher than the current version. - * @since 2.0.0 - */ - public static boolean supports(int version) { - return VERSION >= version; - } - - /** - * Converts the enum names to a more friendly and readable string. - * - * @return a formatted string. - * @see #toWord(String) - * @since 2.1.0 - */ - @Nonnull - public static String toWord(@Nonnull Material material) { - Objects.requireNonNull(material, "Cannot translate a null material to a word"); - return toWord(material.name()); - } - - /** - * Parses an enum name to a normal word. - * Normal names have underlines removed and each word capitalized. - *

- * Examples: - *

-     *     EMERALD                 -> Emerald
-     *     EMERALD_BLOCK           -> Emerald Block
-     *     ENCHANTED_GOLDEN_APPLE  -> Enchanted Golden Apple
-     * 
- * - * @param name the name of the enum. - * @return a cleaned more readable enum name. - * @since 2.1.0 - */ - @Nonnull - private static String toWord(@Nonnull String name) { - return WordUtils.capitalize(name.replace('_', ' ').toLowerCase(Locale.ENGLISH)); - } - - /** - * Gets the exact major version (..., 1.9, 1.10, ..., 1.14) - * - * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14" - * @return the exact major version. - * @since 2.0.0 - */ - @Nonnull - public static String getMajorVersion(@Nonnull String version) { - Validate.notEmpty(version, "Cannot get major Minecraft version from null or empty string"); - - // getVersion() - int index = version.lastIndexOf("MC:"); - if (index != -1) { - version = version.substring(index + 4, version.length() - 1); - } else if (version.endsWith("SNAPSHOT")) { - // getBukkitVersion() - index = version.indexOf('-'); - version = version.substring(0, index); - } - - // 1.13.2, 1.14.4, etc... - int lastDot = version.lastIndexOf('.'); - if (version.indexOf('.') != lastDot) version = version.substring(0, lastDot); - - return version; - } - - /** - * Checks if the material can be damaged by using it. - * Names going through this method are not formatted. - * - * @param name the name of the material. - * @return true of the material can be damaged. - * @see #isDamageable() - * @since 1.0.0 - */ - public static boolean isDamageable(@Nonnull String name) { - Objects.requireNonNull(name, "Material name cannot be null"); - for (String damageable : DAMAGEABLE) { - if (name.contains(damageable)) return true; - } - return false; - } - - /** - * Checks if the list of given material names matches the given base material. - * Mostly used for configs. - *

- * Supports {@link String#contains} {@code CONTAINS:NAME} and Regular Expression {@code REGEX:PATTERN} formats. - *

- * Example: - *

-     *     XMaterial material = {@link #matchXMaterial(ItemStack)};
-     *     if (material.isOneOf(plugin.getConfig().getStringList("disabled-items")) return;
-     * 
- *
- * {@code CONTAINS} Examples: - *
-     *     {@code "CONTAINS:CHEST" -> CHEST, ENDERCHEST, TRAPPED_CHEST -> true}
-     *     {@code "cOnTaINS:dYe" -> GREEN_DYE, YELLOW_DYE, BLUE_DYE, INK_SACK -> true}
-     * 
- *

- * {@code REGEX} Examples - *

-     *     {@code "REGEX:^.+_.+_.+$" -> Every Material with 3 underlines or more: SHULKER_SPAWN_EGG, SILVERFISH_SPAWN_EGG, SKELETON_HORSE_SPAWN_EGG}
-     *     {@code "REGEX:^.{1,3}$" -> Material names that have 3 letters only: BED, MAP, AIR}
-     * 
- *

- * The reason that there are tags for {@code CONTAINS} and {@code REGEX} - * is for the performance. - * Please avoid using the {@code REGEX} tag if you can use the {@code CONTAINS} tag. - * It'll have a huge impact on performance. - * Please avoid using {@code (capturing groups)} there's no use for them in this case. - * If you want to use groups, use {@code (?: non-capturing groups)}. It's faster. - *

- * You can make a cache for pre-compiled RegEx patterns from your config. - * It's better, but not much faster since these patterns are not that complex. - *

- * Want to learn RegEx? You can mess around in RegExr website. - * - * @param materials the material names to check base material on. - * @return true if one of the given material names is similar to the base material. - * @since 3.1.1 - */ - public boolean isOneOf(@Nullable Collection materials) { - if (materials == null || materials.isEmpty()) return false; - String name = this.name(); - - for (String comp : materials) { - String checker = comp.toUpperCase(Locale.ENGLISH); - if (checker.startsWith("CONTAINS:")) { - comp = format(checker.substring(9)); - if (name.contains(comp)) return true; - continue; - } - if (checker.startsWith("REGEX:")) { - comp = comp.substring(6); - Pattern pattern = CACHED_REGEX.getUnchecked(comp); - if (pattern != null && pattern.matcher(name).matches()) return true; - continue; - } - - // Direct Object Equals - Optional xMat = matchXMaterial(comp); - if (xMat.isPresent() && xMat.get() == this) return true; - } - return false; - } - - /** - * Gets the version which this material was added in. - * If the material doesn't have a version it'll return 0; - * - * @return the Minecraft version which tihs material was added in. - * @since 3.0.0 - */ - public int getMaterialVersion() { - if (this.legacy.length == 0) return 0; - String version = this.legacy[0]; - if (version.charAt(1) != '.') return 0; - - return Integer.parseInt(version.substring(2)); - } - - /** - * Sets the {@link Material} (and data value on older versions) of an item. - * Damageable materials will not have their durability changed. - *

- * Use {@link #parseItem()} instead when creating new ItemStacks. - * - * @param item the item to change its type. - * @see #parseItem() - * @since 3.0.0 - */ - @Nonnull - @SuppressWarnings("deprecation") - public ItemStack setType(@Nonnull ItemStack item) { - Objects.requireNonNull(item, "Cannot set material for null ItemStack"); - Material material = this.parseMaterial(); - Objects.requireNonNull(material, "Unsupported material: " + this.name()); - - item.setType(material); - if (!ISFLAT && !this.isDamageable()) item.setDurability(this.data); - return item; - } - - /** - * Checks if the given string matches any of this material's legacy material names. - * All the values passed to this method will not be null or empty and are formatted correctly. - * - * @param name the name to check - * @return true if it's one of the legacy names. - * @since 2.0.0 - */ - private boolean anyMatchLegacy(@Nonnull String name) { - for (String legacy : this.legacy) { - if (legacy.isEmpty()) break; // Left-side suggestion list - if (name.equals(legacy)) return true; - } - return false; - } - - /** - * User-friendly readable name for this material - * In most cases you should be using {@link #name()} instead. - * - * @return string of this object. - * @see #toWord(String) - * @since 3.0.0 - */ - @Override - public String toString() { - return toWord(this.name()); - } - - /** - * Gets the ID (Magic value) of the material. - * - * @return the ID of the material or -1 if it's a new block or the material is not supported. - * @see #matchXMaterial(int, byte) - * @since 2.2.0 - */ - @SuppressWarnings("deprecation") - public int getId() { - if (this.data != 0 || (this.legacy.length != 0 && this.legacy[0].charAt(1) == '.' && Integer.parseInt(this.legacy[0].substring(2)) >= 13)) return -1; - Material material = this.parseMaterial(); - return material == null ? -1 : material.getId(); - } - - /** - * Checks if the material has any duplicates. - * - * @return true if there is a duplicated name for this material, otherwise false. - * @see #isDuplicated(String) - * @since 2.0.0 - */ - public boolean isDuplicated() { - return DUPLICATED.containsKey(this); - } - - /** - * Checks if the material can be damaged by using it. - * Names going through this method are not formatted. - * - * @return true if the item can be damaged (have its durability changed), otherwise false. - * @see #isDamageable(String) - * @since 1.0.0 - */ - public boolean isDamageable() { - return isDamageable(this.name()); - } - - /** - * The data value of this material pre-flattening. - *

- * Can be accessed with {@link ItemStack#getData()} then {@code MaterialData#getData()} - * or {@link ItemStack#getDurability()} if not damageable. - * - * @return data of this material, or 0 if none. - * @since 1.0.0 - */ - public byte getData() { - return data; - } - - /** - * Get a list of materials names that was previously used by older versions. - * If the material was added in a new version {@link #isNewVersion()}, - * then the first element will indicate which version the material was added in. - * - * @return a list of legacy material names and the first element as the version the material was added in if new. - * @since 1.0.0 - */ - @Nonnull - public String[] getLegacy() { - return legacy; - } - - /** - * Parses an item from this XMaterial. - * Uses data values on older versions. - * - * @return an ItemStack with the same material (and data value if in older versions.) - * @see #parseItem(boolean) - * @see #setType(ItemStack) - * @since 1.0.0 - */ - @Nullable - public ItemStack parseItem() { - return parseItem(false); - } - - /** - * Parses an item from this XMaterial. - * Uses data values on older versions. - * - * @param suggest if true {@link #parseMaterial(boolean)} true will be used. - * @return an ItemStack with the same material (and data value if in older versions.) - * @see #setType(ItemStack) - * @since 2.0.0 - */ - @Nullable - @SuppressWarnings("deprecation") - public ItemStack parseItem(boolean suggest) { - Material material = this.parseMaterial(suggest); - if (material == null) return null; - return ISFLAT ? new ItemStack(material) : new ItemStack(material, 1, this.data); - } - - /** - * Parses the material of this XMaterial. - * - * @return the material related to this XMaterial based on the server version. - * @see #parseMaterial(boolean) - * @since 1.0.0 - */ - @Nullable - public Material parseMaterial() { - return parseMaterial(false); - } - - /** - * Parses the material of this XMaterial and accepts suggestions. - * - * @param suggest use a suggested material (from older materials) if the material is added in a later version of Minecraft. - * @return the material related to this XMaterial based on the server version. - * @since 2.0.0 - */ - @Nullable - public Material parseMaterial(boolean suggest) { - Optional cache = PARSED_CACHE.getIfPresent(this); - if (cache != null) return cache.orElse(null); - Material mat; - - if (!ISFLAT && this.isDuplicated()) mat = requestOldMaterial(suggest); - else { - mat = Material.getMaterial(this.name()); - if (mat == null) mat = requestOldMaterial(suggest); - } - - Optional opt = Optional.ofNullable(mat); - PARSED_CACHE.put(this, opt); - return mat; - } - - /** - * Parses a material for older versions of Minecraft. - * Accepts suggestions if specified. - * - * @param suggest if true suggested materials will be considered for old versions. - * @return a parsed material suitable for the current Minecraft version. - * @see #parseMaterial(boolean) - * @since 2.0.0 - */ - @Nullable - private Material requestOldMaterial(boolean suggest) { - for (int i = this.legacy.length - 1; i >= 0; i--) { - String legacy = this.legacy[i]; - - // Check if we've reached the end and the last string is our - // material version. - if (i == 0 && legacy.charAt(1) == '.') return null; - - // According to the suggestion list format, all the other names continuing - // from here are considered as a "suggestion" - // The empty string is an indicator for suggestion list on the left side. - if (legacy.isEmpty()) { - if (suggest) continue; - break; - } - - Material material = Material.getMaterial(legacy); - if (material != null) return material; - } - return null; - } - - /** - * Checks if an item has the same material (and data value on older versions). - * - * @param item item to check. - * @return true if the material is the same as the item's material (and data value if on older versions), otherwise false. - * @since 1.0.0 - */ - @SuppressWarnings("deprecation") - public boolean isSimilar(@Nonnull ItemStack item) { - Objects.requireNonNull(item, "Cannot compare with null ItemStack"); - if (item.getType() != this.parseMaterial()) return false; - return ISFLAT || this.isDamageable() || item.getDurability() == this.data; - } - - /** - * Gets the suggested material names that can be used - * if the material is not supported in the current version. - * - * @return a list of suggested material names. - * @see #parseMaterial(boolean) - * @since 2.0.0 - */ - @Nonnull - public List getSuggestions() { - if (this.legacy.length == 0 || this.legacy[0].charAt(1) != '.') return new ArrayList<>(); - List suggestions = new ArrayList<>(); - for (String legacy : this.legacy) { - if (legacy.isEmpty()) break; - suggestions.add(legacy); - } - return suggestions; - } - - /** - * Checks if this material is supported in the current version. - * Suggested materials will be ignored. - *

- * Note that you should use {@link #parseMaterial()} and check if it's null - * if you're going to parse and use the material later. - * - * @return true if the material exists in {@link Material} list. - * @since 2.0.0 - */ - public boolean isSupported() { - int version = this.getMaterialVersion(); - if (version != 0) return supports(version); - - Material material = Material.getMaterial(this.name()); - if (material != null) return true; - return requestOldMaterial(false) != null; - } - - /** - * Checks if the material is newly added after the 1.13 Aquatic Update. - * - * @return true if the material was newly added, otherwise false. - * @see #getMaterialVersion() - * @since 2.0.0 - */ - public boolean isFromNewSystem() { - return this.legacy.length != 0 && Integer.parseInt(this.legacy[0].substring(2)) > 13; - } -} \ No newline at end of file diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/enterprise/Database.java b/src/main/java/com/rammelkast/anticheatreloaded/util/enterprise/Database.java deleted file mode 100644 index 3badb22..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/enterprise/Database.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util.enterprise; - -import org.bukkit.Bukkit; -import org.bukkit.scheduler.BukkitTask; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public class Database { - - private static final String EVENTS_TABLE = "logs"; - - private String sqlLogEvent; - private String sqlCleanEvents; - private String sqlCreateEvents; - - public enum DatabaseType { - MySQL, - } - - private DatabaseType type; - private String hostname; - private int port; - private String username; - private String password; - private String prefix; - private String schema; - private String serverName; - - private long logInterval; - private long logLife; - - private boolean syncLevels; - private long syncInterval; - - private Connection connection; - - private PreparedStatement eventBatch; - - private BukkitTask eventTask; - private BukkitTask syncTask; - - public Database(DatabaseType type, String hostname, int port, String username, String password, String prefix, String schema, String serverName, String logInterval, String logLife, boolean syncLevels, String syncInterval) { - this.type = type; - this.hostname = hostname; - this.port = port; - this.username = username; - this.password = password; - this.prefix = prefix; - this.schema = schema; - this.serverName = serverName; - - this.logInterval = Utilities.lifeToSeconds(logInterval); - this.logLife = Utilities.lifeToSeconds(logLife); - - this.syncLevels = syncLevels; - this.syncInterval = Utilities.lifeToSeconds(syncInterval); - - sqlLogEvent = "INSERT INTO " + prefix + EVENTS_TABLE + - " (server, user, check_type) " + - "VALUES (?, ?, ?)"; - - sqlCleanEvents = "DELETE FROM " + prefix + EVENTS_TABLE + " " + - "WHERE time < (CURRENT_TIMESTAMP - INTERVAL ? SECOND)"; - - sqlCreateEvents = "CREATE TABLE IF NOT EXISTS " + prefix + EVENTS_TABLE + "(" + - " `id` INT NOT NULL AUTO_INCREMENT," + - " `server` VARCHAR(45) NOT NULL," + - " `time` TIMESTAMP NOT NULL DEFAULT NOW()," + - " `user` VARCHAR(45) NOT NULL," + - " `check_type` VARCHAR(45) NOT NULL," + - " PRIMARY KEY (`id`));"; - } - - public DatabaseType getType() { - return type; - } - - public String getHostname() { - return hostname; - } - - public int getPort() { - return port; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getPrefix() { - return prefix; - } - - public String getSchema() { - return schema; - } - - public void connect() { - String url = "jdbc:" + type.toString().toLowerCase() + "://" + hostname + ":" + port + "/" + schema; - - try { - connection = DriverManager.getConnection(url, username, password); - eventBatch = connection.prepareStatement(sqlLogEvent); - - connection.prepareStatement(sqlCreateEvents).executeUpdate(); - - connection.setAutoCommit(false); - - if (logInterval != 0) { - eventTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - flushEvents(); - } - }, logInterval * 20, logInterval * 20); - } - - if(syncLevels && syncInterval != 0) { - syncTask = Bukkit.getScheduler().runTaskTimerAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - syncUsers(); - } - }, syncInterval * 20, syncInterval * 20); - } - - AntiCheatReloaded.getPlugin().verboseLog("Connected to the database."); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void shutdown() { - if (eventTask != null) eventTask.cancel(); - if (syncTask != null) syncTask.cancel(); - - flushEvents(); - - try { - eventBatch.close(); - connection.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public Connection getConnection() { - return connection; - } - - public void logEvent(User user, CheckType checkType) { - try { - eventBatch.setString(1, serverName); - eventBatch.setString(2, user.getUUID().toString()); - eventBatch.setString(3, checkType.toString()); - - eventBatch.addBatch(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void flushEvents() { - try { - eventBatch.executeBatch(); - connection.commit(); - - eventBatch = connection.prepareStatement(sqlLogEvent); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public void cleanEvents() { - if (logLife != 0) { - Bukkit.getScheduler().runTaskAsynchronously(AntiCheatReloaded.getPlugin(), new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement(sqlCleanEvents); - statement.setLong(1, logLife); - - statement.executeUpdate(); - - connection.commit(); - AntiCheatReloaded.getPlugin().verboseLog("Cleaned " + statement.getUpdateCount() + " old events from the database"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - }); - } - } - - private void syncUsers() { - for (User user : AntiCheatReloaded.getManager().getUserManager().getUsers()) { - AntiCheatReloaded.getManager().getConfiguration().getLevels().updateLevelToUser(user); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/ConditionalRule.java b/src/main/java/com/rammelkast/anticheatreloaded/util/rule/ConditionalRule.java deleted file mode 100644 index 2c29292..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/ConditionalRule.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util.rule; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.util.User; - -import java.util.SortedMap; - -/** - * The conditional rule follows the same syntax as the traditional CS conditional operator.
- * (CONDITION) ? (TRUE RESULT) : (FALSE RESULT)
- * Where CONDITION is a statement that will be evaluated as either TRUE or FALSE - * and the results are actions to be taken for either outcome. - *

- *

- * Should you need additional actions, the system will recursively parse the following values and handle appropriately. - *
- * For instance, (CONDITION) ? (TRUE RESULT) : (CONDITION) ? (TRUE RESULT) : (FALSE RESULT) is a valid rule - *

- *

- * An example of a valid Conditional Rule:
- * Check_SPIDER > 0 ? Player.KICK : null
- * The above statement would read 'If the spider check has been failed over zero times, kick the player. Otherwise, do nothing.' - *

- * To see syntax for variables and functions that you may use, see {@link com.rammelkast.anticheatreloaded.util.rule.Rule} - */ -public class ConditionalRule extends Rule { - - private static ScriptEngineManager factory = new ScriptEngineManager(); - private static ScriptEngine engine = factory.getEngineByName("js"); - - private static final String TRUE_DELIMITER = "\\?"; - private static final String FALSE_DELIMITER = ":"; - private static final Type TYPE = Type.CONDITIONAL; - - public ConditionalRule(String string) { - super(string, TYPE); - } - - @Override - public boolean check(User user, CheckType type) { - try { - // Load all variables - SortedMap map = getVariables(user, type); - for (String key : map.keySet()) { - engine.put(key, map.get(key)); - } - - boolean value = (Boolean) engine.eval(getString().split(TRUE_DELIMITER)[0]); - // Yo dawg I heard you like conditionals... - String next = value ? getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[0] : getString().split(TRUE_DELIMITER)[1].split(FALSE_DELIMITER)[1]; - - execute(next, user, type); - return value; - } catch (ScriptException e) { - e.printStackTrace(); - } - return true; - } - - private void execute(String string, User user, CheckType type) { - // If we're told to do nothing - if (string.equalsIgnoreCase("null") || string.equalsIgnoreCase("none")) return; - - // If this string is a new conditional statement - if (TYPE.matches(string)) { - new ConditionalRule(string).check(user, type); - } else if (isVariableSet(string)) { - setVariable(string.split("=")[0], string.split("=")[1], user); - } else if (isFunction(string)) { - doFunction(string, type, user); - } - } -} diff --git a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java b/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java deleted file mode 100644 index dcfbc5f..0000000 --- a/src/main/java/com/rammelkast/anticheatreloaded/util/rule/Rule.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * AntiCheatReloaded for Bukkit and Spigot. - * Copyright (c) 2012-2015 AntiCheat Team - * Copyright (c) 2016-2020 Rammelkast - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.rammelkast.anticheatreloaded.util.rule; - -import org.bukkit.GameMode; - -import com.rammelkast.anticheatreloaded.AntiCheatReloaded; -import com.rammelkast.anticheatreloaded.check.CheckType; -import com.rammelkast.anticheatreloaded.util.Group; -import com.rammelkast.anticheatreloaded.util.User; -import com.rammelkast.anticheatreloaded.util.Utilities; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * A rule is a scriptable function used to customize the functions of AntiCheat
- * Rules are executed whenever a user's level rises.

- *

- * There are various variables you can use to interact with AntiCheat through your rules
- * Variables are denoted with the type followed by a _ followed by the variable name.
- * For instance, a variable coming from a user who has used FLY 5 times and is checked by a rule containing 'Check_FLY' will produce a value of 5. - *

- *

- * Types of variables:
- *

    - *
  • Check - *
      - *
    • Contains all valid checks as listed in {@link com.rammelkast.anticheatreloaded.check.CheckType}
    • - *
    • Will return the number of times this user has failed the given check
    • - *
    • Example: Check_SPRINT
    • - *
    - *
  • - *
  • Player - *
      - *
    • Contains NAME, the name of the player
    • - *
    • Contains LEVEL*, the player's current level
    • - *
    • Contains GROUP*, the name of the player's current hack group
    • - *
    • Contains CHECK, the check that was just failed
    • - *
    • Contains GAMEMODE*, the player's current Game Mode (Survival, Creative, Adventure)/li> - *
    • Contains WORLD, the name of the world the player is in/li> - *
    • Contains HEALTH*, the player's current health/li> - *
    • A * denotes that this value can be set, for example Player_HEALTH = 20.0/li> - *
    - *
  • - *
- *

- * There are also functions you can use to execute an action within AntiCheat
- * Functions are denoted with the type followed by a period followed by the function name.
- * For instance, a rule containing Player.KICK will result in the user being kicked.
- *

- *

- * Types of functions:
- * - Player: RESET, KICK, BAN, COMMAND[command] OR COMMAND[command1;command2] - * - when using commands %player% will be replaced by the player name, &world will be replaced by the player's world, - * and &check will be replaced by the check that caused this rule to be run
- *

- *

- * The Rule class itself is not an functional rule setup, - * it is inherited and made functional by different implementations of the rule parser.
- * The only current Rule implementation is the {@link com.rammelkast.anticheatreloaded.util.rule.ConditionalRule} - */ -public class Rule { - - private static final String VARIABLE_SET_REGEX = ".*(_).*=.*"; - private static final String FUNCTION_REGEX = ".*\\..*"; - private String string; - private Type type; - - public enum Type { - CONDITIONAL(".*[?]*.*:.*", "com.rammelkast.anticheatreloaded.util.rule.ConditionalRule"); - - private String regex; - private String c; - - private Type(String regex, String c) { - this.regex = regex; - this.c = c; - } - - public boolean matches(String s) { - return s.matches(regex); - } - - public String getInstance() { - return c; - } - } - - public Rule(String string, Type type) { - this.string = Utilities.removeWhitespace(string).toLowerCase(); - this.type = type; - } - - /** - * Check if the rule passed or failed - * - * @param user the user to check - * @return true if the rule has passed, false if failed - */ - public boolean check(User user, CheckType type) { - // Default value - return true; - } - - /** - * Load a rule by its string value - * - * @param string the string value to load - * @return an instance of Rule if an implementation exists to handle this rule, null if none are found - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Rule load(String string) { - for (Type type : Type.values()) { - if (type.matches(string)) { - try { - Class c = Class.forName(type.getInstance()); - Constructor con = c.getConstructor(String.class); - return (Rule) con.newInstance(string); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - return null; - } - - /** - * Get the type of rule this is - * - * @return a {@link com.rammelkast.anticheatreloaded.util.rule.Rule.Type} - */ - public Type getType() { - return type; - } - - protected String getString() { - return string; - } - - protected SortedMap getVariables(User user, CheckType type) { - SortedMap map = new TreeMap(); - map.put("player_check", type.name().toLowerCase()); - map.put("player_level", user.getLevel()); - map.put("player_group", user.getGroup() != null ? user.getGroup().getName().toLowerCase() : "low"); - map.put("player_uuid", user.getUUID().toString()); - map.put("player_gamemode", user.getPlayer().getGameMode().toString()); - map.put("player_world", user.getPlayer().getWorld().getName()); - map.put("player_health", user.getPlayer().getHealth()); - for (CheckType t : CheckType.values()) { - map.put("check_" + t.name().toLowerCase(), t.getUses(user.getUUID())); - } - return map; - } - - protected void setVariable(String variable, String value, User user) { - if (variable.equals("player_level") && Utilities.isInt(value)) { - user.setLevel(Integer.parseInt(value)); - } else if (variable.equals("player_group") && Utilities.isInt(value)) { - for (Group group : AntiCheatReloaded.getManager().getConfiguration().getGroups().getGroups()) { - if (group.getName().equalsIgnoreCase(value)) { - user.setLevel(group.getLevel()); - } - } - } else if (variable.equals("player_gamemode")) { - try { - GameMode mode = GameMode.valueOf(value); - user.getPlayer().setGameMode(mode); - } catch (IllegalArgumentException ex) { - } - } else if (variable.equals("player_health") && Utilities.isDouble(value)) { - user.getPlayer().setHealth(Double.parseDouble(value)); - } - } - - protected void doFunction(String text, CheckType type, User user) { - if (text.toLowerCase().startsWith("player")) { - text = text.split("\\.")[1]; - List action = new ArrayList(); - action.add(text); - AntiCheatReloaded.getManager().getUserManager().execute(user, action, type); - } - } - - protected boolean isFunction(String string) { - return string.matches(FUNCTION_REGEX); - } - - protected boolean isVariableSet(String string) { - return string.matches(VARIABLE_SET_REGEX); - } - - @Override - public String toString() { - return type + "{" + string + "}"; - } -} diff --git a/src/main/resources/checks.yml b/src/main/resources/checks.yml deleted file mode 100644 index fb66460..0000000 --- a/src/main/resources/checks.yml +++ /dev/null @@ -1,450 +0,0 @@ -# AntiCheatReloaded checks configuration file -# Checks that have multiple modules need to be disabled on a per-module basis -# If you have a false positive and can't determine what subcheck it's from, -# enable debug-mode in config.yml and compare the results against the commented values -# Flight check settings -# Checks if a player moves wrongly in the air -flight: - # Checks for prolonged air movement - # Debugs as 'tried to fly on the Y-axis' or 'had too little Y dropoff' - airFlight: - # Should this part of the check be enabled? - enabled: true - # How many milliseconds to account for block placement - # Increase this if you get false positives when building a tower - accountForBlockPlacement: 1200 - # How many milliseconds to account for TPS drops - # Increase this if you get false positives when building a tower during TPS drops - accountForTpsDrops: 250 - # How many milliseconds to account for teleports - # Increase this is you debug 'had too little Y dropoff' after teleports - accountForTeleports: 150 - # Checks for climbing behaviour in air - # Debugs as 'tried to climb air' - airClimb: - # Should this part of the check be enabled? - enabled: true - # How many milliseconds to account for teleports - # Increase this is you debug 'tried to climb air' after teleports - accountForTeleports: 50 - # Checks if a player is faking it's ground status to fly - # Debugs as 'faked ground to fly' - groundFlight: - # Should this part of the check be enabled? - enabled: true - # Checks if a player ignores gravity - # Debugs as 'ignored gravity' - gravity: - # Should this part of the check be enabled? - enabled: true - # Maximum offset between predicted and actual gravity - maxOffset: 0.005 - # How many milliseconds to account for teleports - # Increase this is you debug 'ignored gravity' after teleports - accountForTeleports: 100 - # Amount of illegal moves before flagging - vlBeforeFlag: 5 - -# ElytraFly check settings -# Checks for illegal upward elytra movement -elytrafly: - # Should this check be enabled? - enabled: true - -# Speed check settings -# Checks if a player moves too fast -speed: - # Checks movement speed in the air - # Debugs as 'moved too fast in air' - airSpeed: - # Should this part of the check be enabled? - enabled: true - # Base unadjusted air speed limit - baseLimit: 0.03125 - # Prediction multiplier for custom walk speeds - walkSpeedMultiplier: 1.4 - - # Checks movement acceleration in the air - # Debugs as 'exceeded acceleration limits' - airAcceleration: - # Should this part of the check be enabled? - enabled: true - # Base unadjusted air acceleration limit - baseLimit: 0.3725 - # Limit multiplier for custom walk speeds - walkSpeedMultiplier: 1.4 - - # Checks movement acceleration in the air - # Debugs as 'had unexpected jumping behaviour' - jumpBehaviour: - # Should this part of the check be enabled? - enabled: true - # Minimum movement distance needed to flag - minimumDistXZ: 0.42 - - # Checks movement speed on the ground - # Debugs as 'moved too fast on ground' - groundSpeed: - # Should this part of the check be enabled? - enabled: true - # Initial speed limit value - initialLimit: 0.34 - - # Checks movement acceleration in the air - # Debugs as 'exceeded vertical speed limit' - verticalSpeed: - # Should this part of the check be enabled? - enabled: true - # Extra compensation when moving off a ladder up a slab - climbableCompensation: 0.04 - -# Strafe check settings -# Checks if a player switches movement angle in air -strafe: - # Should this check be enabled? - enabled: true - # How many milliseconds to account for teleports - accountForTeleports: 100 - # Maximum angle change when moving in air - maxAngleChange: 0.50 - # Minimum movement distance for the strafe check to be active - minActivationDistance: 0.025 - -# WaterWalk check settings -# Checks if a player is walking on water -waterwalk: - # Checks for vanilla water walking/jumping - # Debugs as 'tried to walk on water' - walk: - # Should this part of the check be enabled? - enabled: true - # Minimum xz distance before flagging - # This combats false positives, while giving hackers not much leniency - minimumDistXZ: 0.092 - # Checks for small hops on top of water - # Debugs as 'tried to hop on water' - hop: - # Should this part of the check be enabled? - enabled: true - # Maximum lunge Y motion to flag - maxMotionY: 0.10 - # Checks for small lunges in water - # Debugs as 'tried to lunge in water' - lunge: - # Should this part of the check be enabled? - enabled: true - # Minimum xz distance before flagging - # This combats false positives, while giving hackers not much leniency - minimumDistXZ: 0.098 - -# FastLadder check settings -# Checks if a player moves too fast on a ladder -fastladder: - # Should this check be enabled? - enabled: true - # Maximum speed a player on a ladder can travel upwards - speedUpMax: 0.11761 - # Maximum speed a player on a ladder can travel downwards - speedDownMax: 0.15 - # Amount of illegal ladder moves before flagging - vlBeforeFlag: 3 - -# BoatFly check settings -# Checks if the player is flying in a boat -boatfly: - # Should this check be enabled? - enabled: true - # Amount of in-boat airborne moments before flagging - vlBeforeFlag: 2 - -# KillAura check settings -# Checks if the player uses a form of kill aura -killaura: - # Checks reach distance in fights - # Debugs as 'reached too far' - reach: - # Should this part of the check be enabled? - enabled: true - # Maximum base reach distances - baseMaxValue: - # Maximum base reach value - normal: 3.6 - # Maximum base reach value when a player has velocity - velocitized: 4.0 - # Settings for lag compensation - lagCompensation: - # Basic extra allowed reach when a player is lagging - lagExtraReach: 0.2 - # Extra allowed reach distance per millisecond of ping - pingCompensation: 0.0025 - # The multiplier of extra compensation for velocity - velocityMultiplier: 1.2 - - # Checks if the target it within a players viewing angle - # Debugs as 'tried to attack from an illegal angle' - angle: - # Should this part of the check be enabled? - enabled: true - # Maximum difference in angle from the players view - maxDifference: 50 - # Amount of illegally angled hits before flagging - vlBeforeFlag: 3 - - # Checks if the player has a suspicious packet order - # Debugs as 'suspicious packet order' - packetOrder: - # Should this part of the check be enabled? - enabled: true - # Minimum server TPS needed for BadPackets to be active - minimumTps: 17.5 - # Minimum elapsed time in milliseconds between a movement packet and a combat packet - minElapsedTime: 5 - # Amount of suspicious combat packet situations before flagging - vlBeforeFlag: 3 - -# Aimbot check settings -# Checks if the player is sending aimbot-like movements -aimbot: - # Should this check be enabled? - enabled: true - # Minimum yaw difference when repeated - minYaw: 30 - # Maximum yaw difference when repeated - maxYaw: 355 - -# Criticals check settings -# Checks if the player tries to do a crit without needed conditions -criticals: - # Should this check be enabled? - enabled: true - -# Velocity check settings -# Checks if the player ignores knockback -velocity: - # Should this check be enabled? - enabled: true - # Minimum percentage of the given knockback a player has to meet - minimumPercentage: 75 - # Amount of low-velocity moments before flagging - vlBeforeFlag: 2 - -# FastPlace check settings -# Checks if the player places blocks too fast -fastplace: - # Should this check be enabled? - enabled: true - # Minimum time in milliseconds between block places - minimumTime: 50 - # Amount of fastplace-moments before flagging a survival player - vlBeforeFlagSurvival: 2 - # Amount of fastplace-moments before flagging a creative player - vlBeforeFlagCreative: 3 - # Amount of time in milliseconds to prevent a player from placing blocks after flagging - blockPlacementTime: 1000 - -# IllegalInteract check settings -# Checks if the player is using, placing or breaking blocks from illegal angles -illegalinteract: - # Maximum difference in angle from the players view - maxAngleDifference: 90 - # Checks angle when breaking a block - # Debugs as 'tried to break a block which was out of view' - break: - # Should this part of the check be enabled? - enabled: true - # Checks angle when placing a block - # Debugs as 'tried to place a block which was out of view' - place: - # Should this part of the check be enabled? - enabled: true - # Checks angle when placing a block - # Debugs as 'tried to interact out of range' or 'tried to interact out of view' - interact: - # Should this part of the check be enabled? - enabled: true - # Default survival interact range - survivalRange: 5.8 - # Default creative interact range - creativeRange: 6.8 - # Extra allowed reach distance per millisecond of ping - pingCompensation: 0.0045 - # The multiplier of extra compensation for velocity - velocityMultiplier: 1.5 - -# BadPackets check settings -# Checks for illegal packets -badpackets: - # Should this check be enabled? - enabled: true - # Minimum server TPS needed for BadPackets to be active - minimumTps: 17.5 - # Maximum distance a player can move between packets - maxDistance: 25.0 - -# MorePackets check settings -# Checks for an extra amount of packets and modified game timers -morepackets: - # Should this check be enabled? - enabled: true - # Minimum server TPS needed for MorePackets to be active - minimumTps: 17.5 - # Maximum amount of lag compensation a player can acquire (50ms = 1 tick) - minimumClamp: 500 - # The amount of milliseconds offset between packets before flagging (50ms = 1 tick) - triggerBalance: 100 - # The amount of milliseconds to compensate for a teleport (50ms = 1 tick) - teleportCompensation: 150 - # Should MorePackets be disabled for 'lagging' players? - # This can easily be spoofed by clients! - disableForLagging: false - # Maximum ping value before MorePackets stops checking a player (-1 to disable) - # This can easily be spoofed by clients! - maxPing: -1 - -# Sneak check settings -# Checks if the player toggles sneak too fast -sneak: - # Should this check be enabled? - enabled: true - # Should MorePackets be disabled for 'lagging' players? - # This can easily be spoofed by clients! - disableForLagging: false - # Minimum server TPS needed for sneak - minimumTps: 12 - # Minimum time in milliseconds between sneak toggles - minToggleTime: 75 - -# NoSlow check settings -# Checks if the player moves too fast while blocking -noslow: - # Should this check be enabled? - enabled: true - # Minimum time difference in milliseconds between toggling use item state - minimumDifference: 75 - # Minimum movement distance needed to flag - minimumDistXZ: 0.15 - # Amount of no slowdown moments before flagging - vlBeforeFlag: 3 - -# Spider check settings -# Checks if the player tries to climb a non-climbable block -spider: - # Should this check be enabled? - enabled: true - -# NoFall check settings -# Checks if the player tries to ignore fall damage -nofall: - # Should this check be enabled? - enabled: true - # Amount of moves with a modified fall distance before flagging - vlBeforeFlag: 6 - -# Sprint check settings -# Checks if the player tries to sprint without the needed conditions -sprint: - # Should this check be enabled? - enabled: true - # Minimum food level needed to sprint - sprintFoodMin: 6 - -# FastBow check settings -# Checks if the player fires a bow too fast -fastbow: - # Should this check be enabled? - enabled: true - # Maximum percent error between predicted bow force and actual bow force - bowError: 0.25 - -# FastEat check settings -# Checks if the player consumes food too fast -fasteat: - # Should this check be enabled? - enabled: true - # Minimum time in milliseconds it takes to consume food - eatTimeMin: 1000 - -# FastHeal check settings -# Checks if the player regains health too fast -fastheal: - # Should this check be enabled? - enabled: true - # Minimum server TPS needed for FastHeal to be active - minimumTps: 17.5 - # Should FastHeal be disabled for 'lagging' players? - # This can easily be spoofed by clients! - disableForLagging: false - # The minimum time it takes to regenerate health in milliseconds - minHealTime: 495 - # Amount of milliseconds a player can heal faster per millisecond of ping - pingCompensation: 0.15 - -# FastProjectile check settings -# Checks if the player fires a projectile too fast -fastprojectile: - # Should this check be enabled? - enabled: true - # Number of projectiles to wait for before checking how long they took to fire off - projectilesToWait: 10 - # The minimum time in milliseconds it should have taken for the player fire 'projectilesToWait' projectiles - minimumTime: 1500 - -# ItemSpam check settings -# Checks if the player drops items too fast -itemspam: - # Should this check be enabled? - enabled: true - # The number of item drops we should wait before checking if the player has used item spam - dropsToWait: 10 - # The minimum time in milliseconds it should have taken for the player to drop items 'dropsToWait' times - minimumTime: 800 - -# FastInventory check settings -# Checks if the player moves items in the inventory too fast -fastinventory: - # Should this check be enabled? - enabled: true - # The number of clicks we should wait before checking if the player has used fast inventory - clicksToWait: 10 - # The minimum time in milliseconds it should have taken for the player to click 'clicksToWait' times - minimumTime: 50 - -# vClip check settings -# Checks if the player is clipping -vclip: - # Should this check be enabled? - enabled: true - -# ChatUnicode check settings -# Checks for illegal unicode characters in the chat -chatunicode: - # Should this check be enabled? - enabled: true - -# ChatSpam check settings -# Checks for a spam of chat messages -chatspam: - # Should this check be enabled? - enabled: true - # Minimum time between chats - timeMin: 500 - # Time in milliseconds after which repeating yourself in chat is ignored - repeatIgnore: 600 - # Number of chat spam violations before action one (see config.yml) is executed - levelActionOne: 5 - # Number of chat spam violations before action two (see config.yml) is executed - levelActionTwo: 10 - -# CommandSpam check settings -# Checks for a spam of commands -commandspam: - # Should this check be enabled? - enabled: true - # Minimum time between commands - timeMin: 400 - # Time in milliseconds after which repeating a command is ignored - repeatIgnore: 500 - # Number of command spam violations before action one (see config.yml) is executed - levelActionOne: 5 - # Number of command spam violations before action two (see config.yml) is executed - levelActionTwo: 10 \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml deleted file mode 100644 index 3e27b7a..0000000 --- a/src/main/resources/config.yml +++ /dev/null @@ -1,50 +0,0 @@ -# AntiCheatReloaded configuration file -spam: - chat: - # Should AntiCheatReloaded block players spamming messages in chat? - block-speed: true - block-repetition: true - # Valid actions = NONE,KICK,BAN,COMMAND[command] - action-one: KICK - action-two: BAN - # Should AntiCheatReloaded block players spamming commands in chat? - command: - block-speed: true - block-repetition: true - # Valid actions = NONE,KICK,BAN,COMMAND[command] - action-one: KICK - action-two: BAN -system: - # Should AntiCheatReloaded log ALL failed checks to console? - log-to-console: false - # Should AntiCheatReloaded log to file? - log-to-file: true - # Should AntiCheatReloaded display extra debug information when starting? - verbose-startup: false - # If silent mode is on, players will not be stopped when they try to hack, and AntiCheatReloaded will do everything possible to keep them unaware of their rising hack level. - # However, alerts will still be sent to console and to admins online, and events will still take place. - silent-mode: false - # Disable broadcasts about why a player was kicked - disable-broadcast: false - # Should ops be exempt from all checks? - exempt-op: false - # Should AntiCheatReloaded track plugins in its own registered events? - event-chains: true - # Should Enterprise options be enabled? Only set this to true if you're an advanced user. - enterprise: false - # Running AntiCheatReloaded in debug mode will send alerts to the cheating players and enable debug logging - # Use this when locating and/or reporting false positives or when testing AntiCheatReloaded - # Do NOT enable this in a production environment! - debug-mode: false - # To prevent spamming, staff and the console will only be notified every x violations - # Minimum value is 1, default is 8 - # Example with 5: notifications after 5 vl, 10vl, 15vl, etc. - notify-every-vl: 8 - # Maximum distance a player can be set back - # If the last known valid location is further away than this, - # the player will be rubberbanded at their current location - # Minimum value is 5, default is 50 - max-setback-distance: 50 -disable-in: -- example-world -- example-world-2 diff --git a/src/main/resources/enterprise.yml b/src/main/resources/enterprise.yml deleted file mode 100644 index bce2aa0..0000000 --- a/src/main/resources/enterprise.yml +++ /dev/null @@ -1,45 +0,0 @@ -# AntiCheatReloaded configuration file -# Server-specific settings -server: - # An identifiable name for this server - name: 'server-1' -# Database settings -database: - # Type of database. - type: MySQL - # Address of the server - hostname: '' - # Port of the server - port: 3306 - # Username to connect with - username: '' - # Password for the user - password: '' - # Prefix for the tables - prefix: 'acr_' - # Database/Schema to use - database: 'anticheat' -# Logging settings -log: - # Upload cheat logs to the database? - enable: true - # Time for logs to stay in the database (you can use any combination of d,h,m,s). Set to '' to disable pruning. - life: 2d - # How often to upload logs to the database (you can use any combination of d,h,m,s) - interval: 5m -# Syncing settings -sync: - # Keep user's levels synced in the database? - levels: true - # How often to check for changes to user's levels? (you can use any combination of d,h,m,s) - interval: 1m -# Configuration settings -config: - # Load groups configuration from the database? - groups: true - # Load rules configuration from the database? - rules: true - # Load magic configuration from the database? - magic: false - # Load language configuration from the database? - lang: false \ No newline at end of file diff --git a/src/main/resources/groups.yml b/src/main/resources/groups.yml deleted file mode 100644 index c242db8..0000000 --- a/src/main/resources/groups.yml +++ /dev/null @@ -1,8 +0,0 @@ -# AntiCheatReloaded configuration file -# Options; WARN, KICK, COMMAND[your command here] or NONE -# To disable warnings or kicking, change WARN and/or KICK to NONE -groups: - - 'Low : 50 : GREEN : NONE' - - 'Medium : 60 : YELLOW : WARN' - - 'High : 75 : RED : KICK' - - 'Custom : -1 : GREEN : COMMAND[ban %player%;]' diff --git a/src/main/resources/lang.yml b/src/main/resources/lang.yml deleted file mode 100644 index 59cc9f4..0000000 --- a/src/main/resources/lang.yml +++ /dev/null @@ -1,35 +0,0 @@ -# AntiCheatReloaded language file -# The alert message when a player enters a higher group -ALERT: -- '&6&lACR &8> &7%player% has just entered the %group% hack group.' -- '&6&lACR &8> &7%player%''s last failed check was: %check%.' -- '&6&lACR &8> &7Type ''/acr report %player%'' for more information.' -# The warning a player receives when reaching a certain level -# Only sent when enabled in groups.yml -WARNING: -- '&6&lACR &8>&7 You have been flagged for using cheats.' -- '&6&lACR &8>&7 If you continue to cheat, action will be taken.' -# Ban message -BAN_REASON: '&6&lACR &8> &7Banned for unfair advantage' -# Message to broadcast when banned -# Only sent when enabled in config.yml -BAN_BROADCAST: '&6&lACR &8> &7%player% was banned for cheating' -# Kick message -KICK_REASON: '&6&lACR &8> &7Kicked for unfair advantage' -# Message to broadcast when kicked -# Only sent when enabled in config.yml -KICK_BROADCAST: '&6&lACR &8> &7%player% was kicked for cheating' -# The warning message to send when a player is spamming -SPAM_WARNING: '&6&lACR &8> &7Stop spamming the server or you will be kicked!' -# Kick reason when spamming -SPAM_KICK_REASON: '&6&lACR &8> &7Kicked for spamming' -# Message to broadcast when kicked for spamming -# Only sent when enabled in config.yml -SPAM_KICK_BROADCAST: '&6&lACR &8> &7%player% was kicked for spamming' -# Ban reason when spamming -SPAM_BAN_REASON: '&6&lACR &8> &7Banned for spamming' -# Message to broadcast when banned for spamming -# Only sent when enabled in config.yml -SPAM_BAN_BROADCAST: '&c%player% was banned for spamming' -# The prefix for staff and debug alerts -ALERT_PREFIX: "&6&lACR &8> &7" \ No newline at end of file diff --git a/src/main/resources/magic.yml b/src/main/resources/magic.yml deleted file mode 100644 index b853f12..0000000 --- a/src/main/resources/magic.yml +++ /dev/null @@ -1,37 +0,0 @@ -# Time to exempt a player from moving because of entering/exiting a vehicle -# Increase in case of false positives -ENTERED_EXITED_TIME: 2500 -# Time to exempt a player from moving because of teleporting -# Increase in case of false positives -TELEPORT_TIME: 1500 -# Time to exempt a player from moving because of joining the server -# If your server is slow when a player joins, increasing this value is important -# Shouldn't be lower than 1500 or higher than 5000 -JOIN_TIME: 2000 -# Time to exempt a player from moving because of taking damage -# Can be decreased very slightly to increase detection -# Increase in case of false positives after taking damage -DAMAGE_TIME: 500 -# Time to exempt a player from moving because of taking damage with knockback effects -# Can be decreased very slightly to increase detection -# Increase in case of false positives after knockback -KNOCKBACK_DAMAGE_TIME: 2000 -# Time to exempt a player from moving because of taking damage from an explosion -# Can be decreased very slightly to increase detection -# Increasing in case of false positives after explosions -EXPLOSION_DAMAGE_TIME: 2500 -# Amount of seconds to extend a players velocitized state after receiving velocity again -VELOCITY_EXTENSION: 2 -# Time a player is considered to have a change in velocity -VELOCITY_TIME: 1000 -# This is a set value and shouldn't be changed unless you know what you're doing -VELOCITY_PREVENT: 2000 -# This is a set value and shouldn't be changed unless you know what you're doing -VELOCITY_MAXTIMES: 2 -# Minimum travel distance for move to be considered a teleport and subsequently be ignored -# This is a set value and shouldn't be changed unless you know what you're doing -TELEPORT_MIN: 400 -# The change milliseconds between two keepalives before considering a player to be lagging -# Decrease this in case of clientside lag-related false positives -# Do not lower below 50 or increase above 75 -LAG_DETERMINATION: 60 \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 94be273..4136afb 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -7,166 +7,8 @@ depend: [ProtocolLib] startup: postworld version: ${project.build.version} commands: - anticheat: - description: Control and view info about AntiCheatReloaded - usage: /anticheat help + anticheatreloaded: + description: Main AntiCheatReloaded command + usage: /anticheatreloaded help aliases: acr -permissions: - anticheat.system.notice: - description: See broadcasts when a player is kicked or banned for hacking - anticheat.system.alert: - description: See alerts when a player might be cheating - anticheat.system.help: - description: Access the help message - anticheat.system.mute: - description: Access the mute function - anticheat.system.report: - description: Access cheat reports - anticheat.mod: - description: Mod helper perm - children: - anticheat.system.notice: true - anticheat.system.alert: true - anticheat.system.help: true - anticheat.system.report: true - anticheat.system.mute: true - anticheat.system.log: - description: Access turning console logging on or off - anticheat.system.reload: - description: Access reloading the system - anticheat.system.reset: - description: Access resetting a player's cheat level - anticheat.system.version: - description: Access information about whether the system is updated - anticheat.admin: - description: Admin helper perm - children: - anticheat.mod: true - anticheat.system.log: true - anticheat.system.reload: true - anticheat.system.reset: true - anticheat.system.mute: true - anticheat.check.flight: - description: Allow players to use fly cheats - default: false - anticheat.check.elytrafly: - description: Allow players to use ElytraFly cheats - default: false - anticheat.check.waterwalk: - description: Allow players to walk on water - default: false - anticheat.check.fastplace: - description: Allow players to use build hacks and fastplace - default: false - anticheat.check.chatspam: - description: Allow players to spam chat messages - default: false - anticheat.check.commandspam: - description: Allow players to spam chat messages - default: false - anticheat.check.sprint: - description: Allow players to sprint when hungry - default: false - anticheat.check.sneak: - description: Allow players to use sneak hacks - default: false - anticheat.check.speed: - description: Allow players to use speed hacks - default: false - anticheat.check.vclip: - description: Allow players clip through walls - default: false - anticheat.check.spider: - description: Allow players to climb non-climbable surfaces - default: false - anticheat.check.nofall: - description: Allow players to avoid fall damage - default: false - anticheat.check.fastbow: - description: Allow players to quickly fire bows - default: false - anticheat.check.fasteat: - description: Allow players to eat food instantly - default: false - anticheat.check.fastheal: - description: Allow players to heal up instantly - default: false - anticheat.check.killaura: - description: Allow players to use killaura - default: false - anticheat.check.unicode: - description: Allow players to use unicode in chat - default: false - anticheat.check.fastprojectile: - description: Allow players to spam projectiles (fastbow etc.) - default: false - anticheat.check.itemspam: - description: Allow players to use inventory drop spam hacks - default: false - anticheat.check.fastinventory: - description: Allow players to use fastloot and similar inventory hacks - default: false - anticheat.check.morepackets: - description: Allow players to send lots of movement packets or modify their timer - default: false - anticheat.check.badpackets: - description: Allow players to send invalid movement packets - default: false - anticheat.check.velocity: - description: Allow players to use knockback prevention - default: false - anticheat.check.criticals: - description: Allow players to use criticals - default: false - anticheat.check.illegalinteract: - description: Allow players to place blocks in illegal places - default: false - anticheat.check.fastladder: - description: Allow players to climb ladders faster - default: false - anticheat.check.aimbot: - description: Allow players to use aimbot - default: false - anticheat.check.strafe: - description: Allow players to use strafe hacks - default: false - anticheat.check.noslow: - description: Allow players to use NoSlow hacks - default: false - anticheat.check.boatfly: - description: Allow players to use boat fly hacks - default: false - anticheat.check.exempt: - description: Total exemption from checks - default: false - children: - anticheat.check.flight: true - anticheat.check.elytrafly: true - anticheat.check.waterwalk: true - anticheat.check.fastplace: true - anticheat.check.chatspam: true - anticheat.check.commandspam: true - anticheat.check.sprint: true - anticheat.check.sneak: true - anticheat.check.speed: true - anticheat.check.vclip: true - anticheat.check.spider: true - anticheat.check.nofall: true - anticheat.check.fastbow: true - anticheat.check.fasteat: true - anticheat.check.fastheal: true - anticheat.check.killaura: true - anticheat.check.fastprojectile: true - anticheat.check.itemspam: true - anticheat.check.fastinventory: true - anticheat.check.morepackets: true - anticheat.check.badpackets: true - anticheat.check.velocity: true - anticheat.check.criticals: true - anticheat.check.unicode: true - anticheat.check.illegalinteract: true - anticheat.check.fastladder: true - anticheat.check.aimbot: true - anticheat.check.strafe: true - anticheat.check.noslow: true - anticheat.check.boatfly: true \ No newline at end of file +permissions: \ No newline at end of file diff --git a/src/main/resources/rules.yml b/src/main/resources/rules.yml deleted file mode 100644 index fc45a2f..0000000 --- a/src/main/resources/rules.yml +++ /dev/null @@ -1,4 +0,0 @@ -# AntiCheatReloaded rules file -rules: - # if spider check is less than 0, set group to 20. otherwise, do nothing - - 'Check_SPIDER < 0 ? Player.KICK : null'