diff options
author | Zenexer <Zenexer@e251c2fe-e539-e718-e476-b85c1f46cddb> | 2011-03-30 04:03:21 +0000 |
---|---|---|
committer | Zenexer <Zenexer@e251c2fe-e539-e718-e476-b85c1f46cddb> | 2011-03-30 04:03:21 +0000 |
commit | cb21bc4d7a67f0974c2773fdd0f5376f177c068e (patch) | |
tree | f1584fe391f77c648a1d7d25385ef16229b756de /EssentialsGroupManager/src/org/anjocaido | |
download | Essentials-cb21bc4d7a67f0974c2773fdd0f5376f177c068e.tar Essentials-cb21bc4d7a67f0974c2773fdd0f5376f177c068e.tar.gz Essentials-cb21bc4d7a67f0974c2773fdd0f5376f177c068e.tar.lz Essentials-cb21bc4d7a67f0974c2773fdd0f5376f177c068e.tar.xz Essentials-cb21bc4d7a67f0974c2773fdd0f5376f177c068e.zip |
2.1 prerelease, part 2 of 3
git-svn-id: https://svn.java.net/svn/essentials~svn/trunk2.1@1015 e251c2fe-e539-e718-e476-b85c1f46cddb
Diffstat (limited to 'EssentialsGroupManager/src/org/anjocaido')
18 files changed, 5390 insertions, 0 deletions
diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java new file mode 100644 index 000000000..68253eccc --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java @@ -0,0 +1,120 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; +import java.util.logging.Level; +import org.anjocaido.groupmanager.utils.Tasks; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + +/** + * + * @author gabrielcouto + */ +public class GMConfiguration { + + private GroupManager plugin; + private Map<String, Object> rootDataNode; + private File configFile; + + public GMConfiguration(GroupManager plugin) { + this.plugin = plugin; + load(); + } + + public void load() { + if (!plugin.getDataFolder().exists()) { + plugin.getDataFolder().mkdirs(); + } + configFile = new File(plugin.getDataFolder(), "config.yml"); + + if (!configFile.exists()) { + try { + Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + + Yaml yaml = new Yaml(new SafeConstructor()); + FileInputStream rx = null; + try { + rx = new FileInputStream(configFile); + } catch (FileNotFoundException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + try { + rootDataNode = (Map<String, Object>) yaml.load(new UnicodeReader(rx)); + if (rootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex); + } finally { + try { + rx.close(); + } catch (IOException ex) { + } + } + adjustLoggerLevel(); + } + + public Map<String, Object> getMirrorsMap() { + if (rootDataNode.get("settings") instanceof Map) { + Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings"); + if (settingsNode.get("permission") instanceof Map) { + Map<String, Object> permissionNode = (Map<String, Object>) settingsNode.get("permission"); + if (permissionNode.get("world") instanceof Map) { + Map<String, Object> worldsNode = (Map<String, Object>) permissionNode.get("world"); + if (worldsNode.get("mirror") instanceof Map) { + Map<String, Object> mirrorsNode = (Map<String, Object>) worldsNode.get("mirror"); + return mirrorsNode; + } + } + } + } + return null; + } + + public Integer getSaveInterval() { + if (rootDataNode.get("settings") instanceof Map) { + Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings"); + if (settingsNode.get("data") instanceof Map) { + Map<String, Object> dataNode = (Map<String, Object>) settingsNode.get("data"); + if (dataNode.get("save") instanceof Map) { + Map<String, Object> saveNode = (Map<String, Object>) dataNode.get("save"); + if (saveNode.get("minutes") instanceof Integer) { + return (Integer) saveNode.get("minutes"); + } + } + } + } + return 10; + } + + public void adjustLoggerLevel() { + if (rootDataNode.get("settings") instanceof Map) { + Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings"); + if (settingsNode.get("logging") instanceof Map) { + Map<String, Object> loggingNode = (Map<String, Object>) settingsNode.get("logging"); + if (loggingNode.get("level") instanceof String) { + String level = (String) loggingNode.get("level"); + try { + GroupManager.logger.setLevel(Level.parse(level)); + return; + } catch (Exception e) { + } + } + } + } + GroupManager.logger.setLevel(Level.INFO); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java new file mode 100644 index 000000000..2ea0007b0 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java @@ -0,0 +1,1634 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager; + +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.anjocaido.groupmanager.utils.GroupManagerPermissions; +import org.anjocaido.groupmanager.data.Variables; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder; +import org.anjocaido.groupmanager.utils.GMLoggerHandler; +import org.anjocaido.groupmanager.utils.PermissionCheckResult; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; + +/** + * + * @author gabrielcouto + */ +public class GroupManager extends JavaPlugin { + + private File configFile; + private File backupFolder; + private Runnable commiter; + private ScheduledThreadPoolExecutor scheduler; + private Map<String, ArrayList<User>> overloadedUsers = new HashMap<String, ArrayList<User>>(); + private Map<CommandSender, String> selectedWorlds = new HashMap<CommandSender, String>(); + private WorldsHolder worldsHolder; + private boolean validateOnlinePlayer = true; + private boolean isReady = false; + private GMConfiguration config; + public static final Logger logger = Logger.getLogger(GroupManager.class.getName()); + + @Override + public void onDisable() { + if (worldsHolder != null) { + worldsHolder.saveChanges(); + } + disableScheduler(); + // EXAMPLE: Custom code, here we just output some info so we can check all is well + PluginDescriptionFile pdfFile = this.getDescription(); + System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is disabled!"); + } + + @Override + public void onEnable() { + GroupManager.logger.setUseParentHandlers(false); + GMLoggerHandler ch = new GMLoggerHandler(); + GroupManager.logger.addHandler(ch); + logger.setLevel(Level.ALL); + if (worldsHolder == null) { + prepareFileFields(); + prepareConfig(); + worldsHolder = new WorldsHolder(this); + } + + PluginDescriptionFile pdfFile = this.getDescription(); + if (worldsHolder == null) { + GroupManager.logger.severe("Can't enable " + pdfFile.getName() + " version " + pdfFile.getVersion() + ", bad loading!"); + this.getServer().getPluginManager().disablePlugin(this); + throw new IllegalStateException("An error ocurred while loading GroupManager"); + } + + enableScheduler(); + System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); + } + + public InputStream getResourceAsStream(String fileName) { + return this.getClassLoader().getResourceAsStream(fileName); + } + + private void prepareFileFields() { + configFile = new File(this.getDataFolder(), "config.yml"); + backupFolder = new File(this.getDataFolder(), "backup"); + if (!backupFolder.exists()) { + getBackupFolder().mkdirs(); + } + } + + private void prepareConfig() { + config = new GMConfiguration(this); + } + + public void enableScheduler() { + if (worldsHolder != null) { + disableScheduler(); + commiter = new Runnable() { + + @Override + public void run() { + GroupManager.this.worldsHolder.saveChanges(); + } + }; + scheduler = new ScheduledThreadPoolExecutor(1); + int minutes = getConfig().getSaveInterval(); + scheduler.scheduleAtFixedRate(commiter, minutes, minutes, TimeUnit.MINUTES); + GroupManager.logger.info("Scheduled Data Saving is set for every " + minutes + " minutes!"); + } + } + + public void disableScheduler() { + if (scheduler != null) { + try { + scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + scheduler.shutdown(); + } catch (Exception e) { + } + scheduler = null; + GroupManager.logger.info("Scheduled Data Saving is disabled!"); + } + } + + /** + * Use the WorldsHolder saveChanges directly instead + * Saves the data on file + */ + @Deprecated + public void commit() { + if (worldsHolder != null) { + worldsHolder.saveChanges(); + } + } + + /** + * Use worlds holder to reload a specific world + * Reloads the data + */ + @Deprecated + public void reload() { + worldsHolder.reloadAll(); + } + + public WorldsHolder getWorldsHolder() { + return worldsHolder; + } + + /** + * The handler in the interface created by AnjoCaido + * @return + */ + @Deprecated + public AnjoPermissionsHandler getPermissionHandler() { + return worldsHolder.getDefaultWorld().getPermissionsHandler(); + } + + /** + * A simple interface, for ones that don't want to mess with overloading. + * Yet it is affected by overloading. But seamless. + * @return the dataholder with all information + */ + @Deprecated + public WorldDataHolder getData() { + return worldsHolder.getDefaultWorld(); + } + + /** + * Use this if you want to play with overloading. + * @return a dataholder with overloading interface + */ + @Deprecated + public OverloadedWorldHolder getOverloadedClassData() { + return worldsHolder.getDefaultWorld(); + } + + /** + * Called when a command registered by this plugin is received. + * @param sender + * @param cmd + * @param args + */ + @Override + public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { + boolean playerCanDo = false; + boolean isConsole = false; + Player senderPlayer = null; + Group senderGroup = null; + User senderUser = null; + + + //DETERMINING PLAYER INFORMATION + if (sender instanceof Player) { + senderPlayer = (Player) sender; + senderUser = worldsHolder.getWorldData(senderPlayer).getUser(senderPlayer.getName()); + senderGroup = senderUser.getGroup(); + if (worldsHolder.getWorldPermissions(senderPlayer).has(senderPlayer, "groupmanager." + cmd.getName())) { + playerCanDo = true; + } + } else if (sender instanceof ConsoleCommandSender) { + isConsole = true; + } + + //PERMISSIONS FOR COMMAND BEING LOADED + OverloadedWorldHolder dataHolder = null; + AnjoPermissionsHandler permissionHandler = null; + + if (senderPlayer != null) { + dataHolder = worldsHolder.getWorldData(senderPlayer); + } + + String selectedWorld = selectedWorlds.get(sender); + if (selectedWorld != null) { + dataHolder = worldsHolder.getWorldData(selectedWorld); + } + + if (dataHolder != null) { + permissionHandler = dataHolder.getPermissionsHandler(); + } + + //VARIABLES USED IN COMMANDS + + + int count; + PermissionCheckResult permissionResult = null; + ArrayList<User> removeList = null; + String auxString = null; + List<Player> match = null; + User auxUser = null; + Group auxGroup = null; + Group auxGroup2 = null; + + GroupManagerPermissions execCmd = null; + try { + execCmd = GroupManagerPermissions.valueOf(cmd.getName()); + } catch (Exception e) { + //this error happened once with someone. now im prepared... i think + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= ERROR REPORT START ="); + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= COPY AND PASTE THIS TO GROUPMANAGER DEVELOPER ="); + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe(this.getDescription().getName()); + GroupManager.logger.severe(this.getDescription().getVersion()); + GroupManager.logger.severe("An error occured while trying to execute command:"); + GroupManager.logger.severe(cmd.getName()); + GroupManager.logger.severe("With " + args.length + " arguments:"); + for (String ar : args) { + GroupManager.logger.severe(ar); + } + GroupManager.logger.severe("The field '" + cmd.getName() + "' was not found in enum."); + GroupManager.logger.severe("And could not be parsed."); + GroupManager.logger.severe("FIELDS FOUND IN ENUM:"); + for (GroupManagerPermissions val : GroupManagerPermissions.values()) { + GroupManager.logger.severe(val.name()); + } + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= ERROR REPORT ENDED ="); + GroupManager.logger.severe("==================================================="); + sender.sendMessage("An error occurred. Ask the admin to take a look at the console."); + } + + if (isConsole || playerCanDo) { + switch (execCmd) { + case manuadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' group to '" + auxGroup.getName() + "'."); + + return true; + //break; + case manudel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + dataHolder.removeUser(auxUser.getName()); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' to default settings."); + + return true; + case manuaddsub: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.addSubGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' group to '" + auxGroup.getName() + "'."); + + return true; + case manudelsub: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.removeSubGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You removed subgroup '" + auxGroup.getName() + "' from player '" + auxUser.getName() + "' list."); + + return true; + case mangadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup != null) { + sender.sendMessage(ChatColor.RED + "Group already exists!"); + return false; + } + //PARECE OK + auxGroup = dataHolder.createGroup(args[0]); + sender.sendMessage(ChatColor.YELLOW + "You created a group named: " + auxGroup.getName()); + + return true; + case mangdel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not exists!"); + return false; + } + //PARECE OK + dataHolder.removeGroup(auxGroup.getName()); + sender.sendMessage(ChatColor.YELLOW + "You deleted a group named " + auxGroup.getName() + ", it's users are default group now."); + + return true; + case manuaddp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO SUA PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same group than you, or higher."); + return false; + } + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't add a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (args[1].startsWith("+")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else if (args[1].startsWith("-")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The user already has an exception for this node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } else if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user already has a matching node "); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.FOUND)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } + //PARECE OK + auxUser.addPermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You added '" + args[1] + "' to player '" + auxUser.getName() + "' permissions."); + return true; + //break; + case manudelp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO SUA PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same group than you, or higher."); + return false; + } + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't remove a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The user doesn't have direct access to that permission."); + return false; + } + if (!auxUser.hasSamePermissionNode(args[1])) { + sender.sendMessage(ChatColor.RED + "This permission node doesn't match any node."); + sender.sendMessage(ChatColor.RED + "But might match node: " + permissionResult.accessLevel); + return false; + } + //PARECE OK + auxUser.removePermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You removed '" + args[1] + "' from player '" + auxUser.getName() + "' permissions."); + + return true; + //break; + case manulistp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String perm : auxUser.getPermissionList()) { + auxString += perm + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "The player '" + auxUser.getName() + "' has following permissions: " + ChatColor.WHITE + auxString); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from group: " + auxUser.getGroupName()); + auxString = ""; + for (String subGroup : auxUser.subGroupListStringCopy()) { + auxString += subGroup + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from subgroups: " + auxString); + } + } else { + sender.sendMessage(ChatColor.YELLOW + "The player '" + auxUser.getName() + "' has no specific permissions."); + sender.sendMessage(ChatColor.YELLOW + "Only all permissions from group: " + auxUser.getGroupName()); + auxString = ""; + for (String subGroup : auxUser.subGroupListStringCopy()) { + auxString += subGroup + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from subgroups: " + auxString); + } + } + return true; + case manucheckp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(auxUser, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The player doesn't have access to that permission"); + return false; + } + //PARECE OK + //auxString = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.owner instanceof User) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user has directly a negation node for that permission."); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user has directly this permission."); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + } else if (permissionResult.owner instanceof Group) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user inherits the a negation permission from group: " + permissionResult.owner.getName()); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user inherits the permission from group: " + permissionResult.owner.getName()); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + } + return true; + case mangaddp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO SUA PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't add a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkGroupOnlyPermission(auxGroup, args[1]); + if (args[1].startsWith("+")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The group already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else if (args[1].startsWith("-")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The group already has an exception for this node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } else if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The group already has a matching node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.FOUND)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } + //PARECE OK + auxGroup.addPermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You added '" + args[1] + "' to group '" + auxGroup.getName() + "' permissions."); + + return true; + case mangdelp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO SUA PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't remove a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkGroupOnlyPermission(auxGroup, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The group doesn't have direct access to that permission."); + return false; + } + if (!auxGroup.hasSamePermissionNode(args[1])) { + sender.sendMessage(ChatColor.RED + "This permission node doesn't match any node."); + sender.sendMessage(ChatColor.RED + "But might match node: " + permissionResult.accessLevel); + return false; + } + //PARECE OK + auxGroup.removePermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You removed '" + args[1] + "' from group '" + auxGroup.getName() + "' permissions."); + + return true; + case manglistp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + + //PARECE OK + auxString = ""; + for (String perm : auxGroup.getPermissionList()) { + auxString += perm + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "The group '" + auxGroup.getName() + "' has following permissions: " + ChatColor.WHITE + auxString); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from groups: " + auxString); + } + + } else { + sender.sendMessage(ChatColor.YELLOW + "The grpup '" + auxGroup.getName() + "' has no specific permissions."); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "Only all permissions from groups: " + auxString); + } + + } + return true; + case mangcheckp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + permissionResult = permissionHandler.checkGroupPermissionWithInheritance(auxGroup, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The group doesn't have access to that permission"); + return false; + } + //PARECE OK + //auxString = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.owner instanceof Group) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The group inherits the a negation permission from group: " + permissionResult.owner.getName()); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user inherits the permission from group: " + permissionResult.owner.getName()); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + + } + return true; + case mangaddi: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group 1 does not exists!"); + return false; + } + auxGroup2 = dataHolder.getGroup(args[1]); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "Group 2 does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (permissionHandler.searchGroupInInheritance(auxGroup, auxGroup2.getName(), null)) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " already inherits " + auxGroup2.getName() + " (might not be directly)"); + return false; + } + //PARECE OK + auxGroup.addInherits(auxGroup2); + sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " is now in " + auxGroup.getName() + " inheritance list."); + + return true; + case mangdeli: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group 1 does not exists!"); + return false; + } + auxGroup2 = dataHolder.getGroup(args[1]); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "Group 2 does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (!permissionHandler.searchGroupInInheritance(auxGroup, auxGroup2.getName(), null)) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " does not inherits " + auxGroup2.getName() + "."); + return false; + } + if (!auxGroup.getInherits().contains(auxGroup2.getName())) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " does not inherits " + auxGroup2.getName() + " directly."); + return false; + } + //PARECE OK + auxGroup.removeInherits(auxGroup2.getName()); + sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " was removed from " + auxGroup.getName() + " inheritance list."); + + return true; + case manuaddv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (int i = 2; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + auxUser.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the user " + auxUser.getName()); + return true; + case manudelv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!auxUser.getVariables().hasVar(args[1])) { + sender.sendMessage(ChatColor.RED + "The user doesn't have directly that variable!"); + } + //PARECE OK + auxUser.getVariables().removeVar(args[1]); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the user " + ChatColor.GREEN + auxUser.getName()); + return true; + case manulistv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String varKey : auxUser.getVariables().getVarKeyList()) { + Object o = auxUser.getVariables().getVarObject(varKey); + auxString += ChatColor.GOLD + varKey + ChatColor.WHITE + ":'" + ChatColor.GREEN + o.toString() + ChatColor.WHITE + "', "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + "Variables of user " + auxUser.getName() + ": "); + sender.sendMessage(auxString + "."); + sender.sendMessage(ChatColor.YELLOW + "Plus all variables from group: " + auxUser.getGroupName()); + return true; + case manucheckv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + auxGroup = auxUser.getGroup(); + auxGroup2 = permissionHandler.nextGroupWithVariable(auxGroup, args[1], null); + + if (!auxUser.getVariables().hasVar(args[1])) { + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "The user doesn't have access to that variable!"); + } + } + //PARECE OK + if (auxUser.getVariables().hasVar(auxString)) { + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxUser.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + sender.sendMessage(ChatColor.YELLOW + "This user own directly the variable"); + } + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxGroup2.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + if (!auxGroup.equals(auxGroup2)) { + sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); + } + return true; + case mangaddv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (int i = 2; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + auxGroup.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the group " + auxGroup.getName()); + + return true; + case mangdelv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (!auxGroup.getVariables().hasVar(args[1])) { + sender.sendMessage(ChatColor.RED + "The group doesn't have directly that variable!"); + } + //PARECE OK + auxGroup.getVariables().removeVar(args[1]); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the group " + ChatColor.GREEN + auxGroup.getName()); + + return true; + case manglistv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String varKey : auxGroup.getVariables().getVarKeyList()) { + Object o = auxGroup.getVariables().getVarObject(varKey); + auxString += ChatColor.GOLD + varKey + ChatColor.WHITE + ":'" + ChatColor.GREEN + o.toString() + ChatColor.WHITE + "', "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + "Variables of group " + auxGroup.getName() + ": "); + sender.sendMessage(auxString + "."); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "Plus all variables from groups: " + auxString); + } + return true; + case mangcheckv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + auxGroup2 = permissionHandler.nextGroupWithVariable(auxGroup, args[1], null); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "The group doesn't have access to that variable!"); + } + //PARECE OK + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxGroup2.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + if (!auxGroup.equals(auxGroup2)) { + sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); + } + return true; + case manwhois: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //PARECE OK + sender.sendMessage(ChatColor.YELLOW + "Name: " + ChatColor.GREEN + auxUser.getName()); + sender.sendMessage(ChatColor.YELLOW + "Group: " + ChatColor.GREEN + auxUser.getGroup().getName()); + sender.sendMessage(ChatColor.YELLOW + "Overloaded: " + ChatColor.GREEN + dataHolder.isOverloaded(auxUser.getName())); + auxGroup = dataHolder.surpassOverload(auxUser.getName()).getGroup(); + if (!auxGroup.equals(auxUser.getGroup())) { + sender.sendMessage(ChatColor.YELLOW + "Original Group: " + ChatColor.GREEN + auxGroup.getName()); + } + //victim.permissions.add(args[1]); + return true; + //break; + case tempadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList<User>()); + } + dataHolder.overloadUser(auxUser.getName()); + overloadedUsers.get(dataHolder.getName().toLowerCase()).add(dataHolder.getUser(auxUser.getName())); + sender.sendMessage(ChatColor.YELLOW + "Player overloaded!"); + + return true; + //break; + case tempdel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList<User>()); + } + dataHolder.removeOverload(auxUser.getName()); + if (overloadedUsers.get(dataHolder.getName().toLowerCase()).contains(auxUser)) { + overloadedUsers.get(dataHolder.getName().toLowerCase()).remove(auxUser); + } + sender.sendMessage(ChatColor.YELLOW + "You removed that player overload. He's back to normal!"); + + return true; + //break; + case templist: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //WORKING + auxString = ""; + removeList = new ArrayList<User>(); + count = 0; + for (User u : overloadedUsers.get(dataHolder.getName().toLowerCase())) { + if (!dataHolder.isOverloaded(u.getName())) { + removeList.add(u); + } else { + auxString += u.getName() + ", "; + count++; + } + } + if (count == 0) { + sender.sendMessage(ChatColor.YELLOW + "There is no users in overload mode"); + return true; + } + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList<User>()); + } + overloadedUsers.get(dataHolder.getName().toLowerCase()).removeAll(removeList); + sender.sendMessage(ChatColor.YELLOW + " " + count + " Users in overload mode: " + ChatColor.WHITE + auxString); + return true; + case tempdelall: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //WORKING + removeList = new ArrayList<User>(); + count = 0; + for (User u : overloadedUsers.get(dataHolder.getName().toLowerCase())) { + if (dataHolder.isOverloaded(u.getName())) { + dataHolder.removeOverload(u.getName()); + count++; + } + } + if (count == 0) { + sender.sendMessage(ChatColor.YELLOW + "There is no users in overload mode"); + return true; + } + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList<User>()); + } + overloadedUsers.get(dataHolder.getName().toLowerCase()).clear(); + sender.sendMessage(ChatColor.YELLOW + " " + count + " Users in overload mode. Now they are normal again."); + + return true; + case mansave: + worldsHolder.saveChanges(); + sender.sendMessage(ChatColor.YELLOW + " The changes were saved."); + return true; + case manload: + //THIS CASE DONT NEED SENDER + if (args.length > 0) { + auxString = ""; + for (int i = 0; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + worldsHolder.loadWorld(auxString); + sender.sendMessage("The request to world '" + auxString + "' was sent."); + return true; + } + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //WORKING + config.load(); + if (args.length > 0) { + auxString = ""; + for (int i = 0; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + worldsHolder.loadWorld(auxString); + sender.sendMessage("The request to world '" + auxString + "' was sent."); + } else { + worldsHolder.reloadAll(); + sender.sendMessage(ChatColor.YELLOW + " The current world was reloaded."); + } + worldsHolder.mirrorSetUp(); + return true; + case listgroups: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //WORKING + auxString = ""; + for (Group g : dataHolder.getGroupList()) { + auxString += g.getName() + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + " Groups Available: " + ChatColor.WHITE + auxString); + return true; + case manpromote: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, senderGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "The destination group can't be the same as yours, or higher."); + return false; + } + if (!isConsole && (!permissionHandler.inGroup(senderUser.getName(), auxUser.getGroupName()) || !permissionHandler.inGroup(senderUser.getName(), auxGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player involving a group that you don't inherit."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxUser.getGroup(), auxGroup.getName()) && !permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player using groups with different heritage line."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "The new group must be a higher rank."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getName() + " group to " + auxGroup.getName() + "."); + + return true; + //break; + case mandemote: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect <world>"); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, senderGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "The destination group can't be the same as yours, or higher."); + return false; + } + if (!isConsole && (!permissionHandler.inGroup(senderUser.getName(), auxUser.getGroupName()) || !permissionHandler.inGroup(senderUser.getName(), auxGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player involving a group that you don' inherit."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxUser.getGroup(), auxGroup.getName()) && !permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player using groups with different heritage line."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "The new group must be a lower rank."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getName() + " group to " + auxGroup.getName() + "."); + + return true; + //break; + case mantogglevalidate: + validateOnlinePlayer = !validateOnlinePlayer; + sender.sendMessage(ChatColor.YELLOW + "Validade if player is online, now set to: " + Boolean.toString(validateOnlinePlayer)); + if (!validateOnlinePlayer) { + sender.sendMessage(ChatColor.GOLD + "From now on you can edit players not connected... BUT:"); + sender.sendMessage(ChatColor.LIGHT_PURPLE + "From now on you should type the whole name of the player, correctly."); + } + return true; + case mantogglesave: + if (scheduler == null) { + enableScheduler(); + sender.sendMessage(ChatColor.YELLOW + "The auto-saving is enabled!"); + } else { + disableScheduler(); + sender.sendMessage(ChatColor.YELLOW + "The auto-saving is disabled!"); + } + return true; + case manworld: + auxString = selectedWorlds.get(sender); + if (auxString != null) { + sender.sendMessage(ChatColor.YELLOW + "You have the world '" + dataHolder.getName() + "' in your selection."); + } else { + if (dataHolder == null) { + sender.sendMessage(ChatColor.YELLOW + "There is no world selected. And no world is available now."); + } else { + sender.sendMessage(ChatColor.YELLOW + "You don't have a world in your selection.."); + sender.sendMessage(ChatColor.YELLOW + "Working with the direct world where your player is."); + sender.sendMessage(ChatColor.YELLOW + "Your world now uses permissions of world name: '" + dataHolder.getName() + "' "); + } + } + return true; + case manselect: + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + sender.sendMessage(ChatColor.YELLOW + "Worlds available: "); + ArrayList<OverloadedWorldHolder> worlds = worldsHolder.allWorldsDataList(); + auxString = ""; + for (int i = 0; i < worlds.size(); i++) { + auxString += worlds.get(i).getName(); + if ((i + 1) < worlds.size()) { + auxString += ", "; + } + } + sender.sendMessage(ChatColor.YELLOW + auxString); + return false; + } + auxString = ""; + for (int i = 0; i < args.length; i++) { + if (args[i] == null) { + logger.warning("Bukkit gave invalid arguments array! Cmd: " + cmd.getName() + " args.length: " + args.length); + return false; + } + auxString += args[i]; + if (i < (args.length - 1)) { + auxString += " "; + } + } + dataHolder = worldsHolder.getWorldData(auxString); + permissionHandler = dataHolder.getPermissionsHandler(); + selectedWorlds.put(sender, dataHolder.getName()); + sender.sendMessage(ChatColor.YELLOW + "You have selected world '" + dataHolder.getName() + "'."); + return true; + case manclear: + if (args.length != 0) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + selectedWorlds.remove(sender); + sender.sendMessage(ChatColor.YELLOW + "You have removed your world selection. Working with current world(if possible)."); + return true; + default: + break; + } + } + sender.sendMessage(ChatColor.RED + "You are not allowed to use that command."); + return false; + } + + /** + * @return the config + */ + public GMConfiguration getConfig() { + return config; + } + + /** + * @return the backupFolder + */ + public File getBackupFolder() { + return backupFolder; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java new file mode 100644 index 000000000..3eb7491dd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java @@ -0,0 +1,114 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.ArrayList; +import java.util.Collections; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.utils.StringPermissionComparator; + +/** + * + * @author gabrielcouto + */ +public abstract class DataUnit { + + private WorldDataHolder dataSource; + private String name; + private boolean changed; + private ArrayList<String> permissions = new ArrayList<String>(); + + public DataUnit(WorldDataHolder dataSource, String name) { + this.dataSource = dataSource; + this.name = name; + } + + /** + * Every group is matched only by their names and DataSources names. + * @param o + * @return true if they are equal. false if not. + */ + @Override + public boolean equals(Object o) { + if (o instanceof DataUnit) { + DataUnit go = (DataUnit) o; + if (this.getName().equalsIgnoreCase(go.getName()) && this.dataSource.getName().equalsIgnoreCase(go.getDataSource().getName())) { + return true; + } + } + return false; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 71 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0); + return hash; + } + + + + + /** + * @return the dataSource + */ + public WorldDataHolder getDataSource() { + return dataSource; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + public void flagAsChanged() { + GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - DataUnit: "+getName()+" flagged as changed!"); +// for(StackTraceElement st: Thread.currentThread().getStackTrace()){ +// GroupManager.logger.finest(st.toString()); +// } + changed = true; + } + + public boolean isChanged() { + return changed; + } + + public void flagAsSaved() { + GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - DataUnit: "+getName()+" flagged as saved!"); + changed = false; + } + + public boolean hasSamePermissionNode(String permission) { + return permissions.contains(permission); + } + + public void addPermission(String permission) { + if (!hasSamePermissionNode(permission)) { + permissions.add(permission); + } + flagAsChanged(); + } + + public boolean removePermission(String permission) { + flagAsChanged(); + return permissions.remove(permission); + } + + /** + * Use this only to list permissions. + * You can't edit the permissions using the returned ArrayList instance + * @return a copy of the permission list + */ + public ArrayList<String> getPermissionList() { + return (ArrayList<String>) permissions.clone(); + } + + public void sortPermissions(){ + Collections.sort(permissions, StringPermissionComparator.getInstance()); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java new file mode 100644 index 000000000..c734b208e --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java @@ -0,0 +1,122 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.util.ArrayList; +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class Group extends DataUnit implements Cloneable { + + /** + * The group it inherits DIRECTLY! + */ + private ArrayList<String> inherits = new ArrayList<String>(); + /** + *This one holds the fields in INFO node. + * like prefix = 'c' + * or build = false + */ + private GroupVariables variables = new GroupVariables(this); + + /** + * + * @param name + */ + public Group(WorldDataHolder source, String name) { + super(source,name); + } + + /** + * Clone this group + * @return a clone of this group + */ + @Override + public Group clone() { + Group clone = new Group(getDataSource(), this.getName()); + clone.inherits = ((ArrayList<String>) this.getInherits().clone()); + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + clone.variables = ((GroupVariables) variables).clone(clone); + //clone.flagAsChanged(); + return clone; + } + + /** + * Use this to deliver a group from a different dataSource to another + * @param dataSource + * @return + */ + public Group clone(WorldDataHolder dataSource) { + if (dataSource.groupExists(this.getName())) { + return null; + } + Group clone = getDataSource().createGroup(this.getName()); + clone.inherits = ((ArrayList<String>) this.getInherits().clone()); + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + clone.variables = variables.clone(clone); + clone.flagAsChanged(); //use this to make the new dataSource save the new group + return clone; + } + + /** + * a COPY of inherits list + * You can't manage the list by here + * Lol... version 0.6 had a problem because this. + * @return the inherits + */ + public ArrayList<String> getInherits() { + return (ArrayList<String>) inherits.clone(); + } + + /** + * @param inherits the inherits to set + */ + public void addInherits(Group inherit) { + if (!this.getDataSource().groupExists(inherit.getName())) { + getDataSource().addGroup(inherit); + } + if (!inherits.contains(inherit.getName().toLowerCase())) { + inherits.add(inherit.getName().toLowerCase()); + } + flagAsChanged(); + } + + public boolean removeInherits(String inherit) { + if (this.inherits.contains(inherit.toLowerCase())) { + this.inherits.remove(inherit.toLowerCase()); + flagAsChanged(); + return true; + } + return false; + } + + /** + * @return the variables + */ + public GroupVariables getVariables() { + return variables; + } + + /** + * + * @param varList + */ + public void setVariables(Map<String, Object> varList) { + GroupVariables temp = new GroupVariables(this, varList); + variables.clearVars(); + for(String key: temp.getVarKeyList()){ + variables.addVar(key, temp.getVarObject(key)); + } + flagAsChanged(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java new file mode 100644 index 000000000..87c34de2b --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java @@ -0,0 +1,87 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class GroupVariables extends Variables implements Cloneable { + + private Group owner; + + public GroupVariables(Group owner) { + super(owner); + this.owner = owner; + addVar("prefix", ""); + addVar("suffix", ""); + addVar("build", false); + } + + public GroupVariables(Group owner, Map<String, Object> varList) { + super(owner); + variables = varList; + if (variables.get("prefix") == null) { + variables.put("prefix", ""); + owner.flagAsChanged(); + } + //thisGrp.prefix = infoNode.get("prefix").toString(); + + if (variables.get("suffix") == null) { + variables.put("suffix", ""); + owner.flagAsChanged(); + } + //thisGrp.suffix = infoNode.get("suffix").toString(); + + if (variables.get("build") == null) { + variables.put("build", false); + owner.flagAsChanged(); + } + this.owner = owner; + } + + /** + * A clone of all vars here. + * @return + */ + protected GroupVariables clone(Group newOwner) { + GroupVariables clone = new GroupVariables(newOwner); + for (String key : variables.keySet()) { + clone.variables.put(key, variables.get(key)); + } + newOwner.flagAsChanged(); + return clone; + } + + /** + * Remove a var from the list + * @param name + */ + @Override + public void removeVar(String name) { + try { + this.variables.remove(name); + } catch (Exception e) { + } + if (name.equals("prefix")) { + addVar("prefix", ""); + } else if (name.equals("suffix")) { + addVar("suffix", ""); + } else if (name.equals("build")) { + addVar("build", false); + } + owner.flagAsChanged(); + } + + /** + * @return the owner + */ + @Override + public Group getOwner() { + return owner; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java new file mode 100644 index 000000000..ceecbfa21 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java @@ -0,0 +1,187 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import com.sun.org.apache.bcel.internal.generic.AALOAD; +import java.util.ArrayList; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class User extends DataUnit implements Cloneable { + + /** + * + */ + private String group = null; + private ArrayList<String> subGroups = new ArrayList<String>(); + /** + *This one holds the fields in INFO node. + * like prefix = 'c' + * or build = false + */ + private UserVariables variables = new UserVariables(this); + + + /** + * + * @param name + */ + public User(WorldDataHolder source, String name) { + super(source,name); + this.group = source.getDefaultGroup().getName(); + } + + /** + * + * @return + */ + @Override + public User clone() { + User clone = new User(getDataSource(), this.getName()); + clone.group = this.group; + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + //clone.variables = this.variables.clone(); + //clone.flagAsChanged(); + return clone; + } + + /** + * Use this to deliver a user from one WorldDataHolder to another + * @param dataSource + * @return null if given dataSource already contains the same user + */ + public User clone(WorldDataHolder dataSource) { + if (dataSource.isUserDeclared(this.getName())) { + return null; + } + User clone = dataSource.createUser(this.getName()); + if (dataSource.getGroup(group) == null) { + clone.setGroup(dataSource.getDefaultGroup()); + } else { + clone.setGroup(this.getGroupName()); + } + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + //clone.variables = this.variables.clone(); + clone.flagAsChanged(); + return clone; + } + + public Group getGroup() { + Group result = getDataSource().getGroup(group); + if (result == null) { + this.setGroup(getDataSource().getDefaultGroup()); + result = getDataSource().getDefaultGroup(); + } + return result; + } + + /** + * @return the group + */ + public String getGroupName() { + Group result = getDataSource().getGroup(group); + if (result == null) { + group = getDataSource().getDefaultGroup().getName(); + } + return group; + } + + /** + * @param group the group to set + */ + @Deprecated + public void setGroup(String group) { + this.group = group; + flagAsChanged(); + } + + /** + * @param group the group to set + */ + public void setGroup(Group group) { + if (!this.getDataSource().groupExists(group.getName())) { + getDataSource().addGroup(group); + } + group = getDataSource().getGroup(group.getName()); + this.group = group.getName(); + flagAsChanged(); + } + + public void addSubGroup(Group subGroup){ + if(this.group.equalsIgnoreCase(subGroup.getName())){ + return; + } + if (!this.getDataSource().groupExists(subGroup.getName())) { + getDataSource().addGroup(subGroup); + } + subGroup = getDataSource().getGroup(subGroup.getName()); + removeSubGroup(subGroup); + subGroups.add(subGroup.getName()); + flagAsChanged(); + } + public int subGroupsSize(){ + return subGroups.size(); + } + public boolean isSubGroupsEmpty(){ + return subGroups.isEmpty(); + } + public boolean containsSubGroup(Group subGroup){ + return subGroups.contains(subGroup.getName()); + } + public boolean removeSubGroup(Group subGroup){ + try{ + if(subGroups.remove(subGroup.getName())){ + flagAsChanged(); + return true; + } + } catch (Exception e){ + + } + return false; + } + public ArrayList<Group> subGroupListCopy(){ + ArrayList<Group> val = new ArrayList<Group>(); + for(String gstr: subGroups){ + Group g = getDataSource().getGroup(gstr); + if(g==null){ + removeSubGroup(g); + continue; + } + val.add(g); + } + return val; + } + public ArrayList<String> subGroupListStringCopy(){ + return (ArrayList<String>) subGroups.clone(); + } + + /** + * @return the variables + */ + public UserVariables getVariables() { + return variables; + } + + /** + * + * @param varList + */ + public void setVariables(Map<String, Object> varList) { + UserVariables temp = new UserVariables(this, varList); + variables.clearVars(); + for(String key: temp.getVarKeyList()){ + variables.addVar(key, temp.getVarObject(key)); + } + flagAsChanged(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java new file mode 100644 index 000000000..45dfc31e7 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java @@ -0,0 +1,45 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.anjocaido.groupmanager.data; + +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class UserVariables extends Variables{ + private User owner; + public UserVariables(User owner){ + super(owner); + this.owner = owner; + } + public UserVariables(User owner, Map<String, Object> varList) { + super(owner); + this.variables = varList; + this.owner = owner; + } + /** + * A clone of all vars here. + * @return + */ + protected UserVariables clone(User newOwner) { + UserVariables clone = new UserVariables(newOwner); + for (String key : variables.keySet()) { + clone.variables.put(key, variables.get(key)); + } + newOwner.flagAsChanged(); + return clone; + } + /** + * @return the owner + */ + @Override + public User getOwner() { + return owner; + } + +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java new file mode 100644 index 000000000..31ed0d795 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java @@ -0,0 +1,192 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + *A class that holds variables of a user/group. + * In groups, it holds the contents of INFO node. + * Like: + * prefix + * suffix + * build + * + * @author gabrielcouto + */ +public abstract class Variables implements Cloneable { + private DataUnit owner; + protected Map<String, Object> variables = new HashMap<String, Object>(); + + public Variables(DataUnit owner){ + this.owner = owner; + } + /** + * Add var to the the INFO node. + * examples: + * addVar("build",true); + * addVar("prefix","c"); + * @param name key name of the var + * @param o the object value of the var + */ + public void addVar(String name, Object o) { + if (o == null) { + return; + } + if (variables.containsKey(name)) { + variables.remove(name); + } + variables.put(name, o); + owner.flagAsChanged(); + } + + /** + * Returns the object inside the var + * @param name + * @return a Object if exists. null if doesn't exists + */ + public Object getVarObject(String name) { + return variables.get(name); + } + + /** + * Get the String value for the given var name + * @param name the var key name + * @return "" if null. or the toString() value of object + */ + public String getVarString(String name) { + Object o = variables.get(name); + try { + return o == null ? "" : o.toString(); + } catch (Exception e) { + return ""; + } + } + + /** + * + * @param name + * @return false if null. or a Boolean.parseBoolean of the string + */ + public Boolean getVarBoolean(String name) { + Object o = variables.get(name); + try { + return o == null ? false : Boolean.parseBoolean(o.toString()); + } catch (Exception e) { + return false; + } + } + + /** + * + * @param name + * @return -1 if null. or a parseInt of the string + */ + public Integer getVarInteger(String name) { + Object o = variables.get(name); + try { + return o == null ? -1 : Integer.parseInt(o.toString()); + } catch (Exception e) { + return -1; + } + } + + /** + * + * @param name + * @return -1 if null. or a parseDouble of the string + */ + public Double getVarDouble(String name) { + Object o = variables.get(name); + try { + return o == null ? -1.0D : Double.parseDouble(o.toString()); + } catch (Exception e) { + return -1.0D; + + + } + } + + /** + * All variable keys this is holding + * @return + */ + public Set<String> getVarKeyList() { + return variables.keySet(); + + + } + + /** + * verify is a var exists + * @param name the key name of the var + * @return true if that var exists + */ + public boolean hasVar(String name) { + return variables.containsKey(name); + + + } + + /** + * Returns the quantity of vars this is holding + * @return the number of vars + */ + public int getSize() { + return variables.size(); + + + } + + /** + * Remove a var from the list + * @param name + */ + public void removeVar(String name) { + try { + variables.remove(name); + } catch (Exception e) { + } + owner.flagAsChanged(); + } + + public static Object parseVariableValue(String value) { + try { + Integer i = Integer.parseInt(value); + return i; + } catch (NumberFormatException e) { + } + try { + Double d = Double.parseDouble(value); + return d; + } catch (NumberFormatException e) { + } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { + return true; + } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { + return false; + } + return value; + + } + + public void clearVars(){ + variables.clear(); + owner.flagAsChanged(); + } + + /** + * @return the owner + */ + public DataUnit getOwner() { + return owner; + } + + public boolean isEmpty(){ + return variables.isEmpty(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java new file mode 100644 index 000000000..f735ff5e6 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java @@ -0,0 +1,204 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import org.anjocaido.groupmanager.data.User; + +/** + * + * @author gabrielcouto + */ +public class OverloadedWorldHolder extends WorldDataHolder { + + /** + * + */ + protected Map<String, User> overloadedUsers = new HashMap<String, User>(); + + /** + * + * @param ph + */ + public OverloadedWorldHolder(WorldDataHolder ph) { + super(ph.getName()); + this.f = ph.f; + this.groupsFile = ph.groupsFile; + this.usersFile = ph.usersFile; + this.defaultGroup = ph.defaultGroup; + this.groups = ph.groups; + this.users = ph.users; + } + + /** + * + * @param userName + * @return + */ + @Override + public User getUser(String userName) { + //OVERLOADED CODE + if (overloadedUsers.containsKey(userName.toLowerCase())) { + return overloadedUsers.get(userName.toLowerCase()); + } + //END CODE + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + haveUsersChanged = true; + return newUser; + } + + /** + * + * @param theUser + */ + @Override + public void addUser(User theUser) { + if (theUser.getDataSource() != this) { + theUser = theUser.clone(this); + } + if (theUser == null) { + return; + } + if ((theUser.getGroup() == null) || (!groups.containsKey(theUser.getGroupName().toLowerCase()))) { + theUser.setGroup(defaultGroup); + } + //OVERLOADED CODE + if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) { + overloadedUsers.remove(theUser.getName().toLowerCase()); + overloadedUsers.put(theUser.getName().toLowerCase(), theUser); + return; + } + //END CODE + removeUser(theUser.getName()); + users.put(theUser.getName().toLowerCase(), theUser); + haveUsersChanged = true; + } + + /** + * + * @param userName + * @return + */ + @Override + public boolean removeUser(String userName) { + //OVERLOADED CODE + if (overloadedUsers.containsKey(userName.toLowerCase())) { + overloadedUsers.remove(userName.toLowerCase()); + return true; + } + //END CODE + if (users.containsKey(userName.toLowerCase())) { + users.remove(userName.toLowerCase()); + haveUsersChanged = true; + return true; + } + return false; + } + + @Override + public boolean removeGroup(String groupName) { + if (groupName.equals(defaultGroup)) { + return false; + } + for (String key : groups.keySet()) { + if (groupName.equalsIgnoreCase(key)) { + groups.remove(key); + for (String userKey : users.keySet()) { + User user = users.get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(defaultGroup); + } + + } + //OVERLOADED CODE + for (String userKey : overloadedUsers.keySet()) { + User user = overloadedUsers.get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(defaultGroup); + } + + } + //END OVERLOAD + haveGroupsChanged = true; + return true; + } + } + return false; + } + + /** + * + * @return + */ + @Override + public Collection<User> getUserList() { + Collection<User> overloadedList = new ArrayList<User>(); + Collection<User> normalList = users.values(); + for (User u : normalList) { + if (overloadedUsers.containsKey(u.getName().toLowerCase())) { + overloadedList.add(overloadedUsers.get(u.getName().toLowerCase())); + } else { + overloadedList.add(u); + } + } + return overloadedList; + } + + /** + * + * @param userName + * @return + */ + public boolean isOverloaded(String userName) { + return overloadedUsers.containsKey(userName.toLowerCase()); + } + + /** + * + * @param userName + */ + public void overloadUser(String userName) { + if (!isOverloaded(userName)) { + User theUser = getUser(userName); + theUser = theUser.clone(); + if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) { + overloadedUsers.remove(theUser.getName().toLowerCase()); + } + overloadedUsers.put(theUser.getName().toLowerCase(), theUser); + } + } + + /** + * + * @param userName + */ + public void removeOverload(String userName) { + overloadedUsers.remove(userName.toLowerCase()); + } + + /** + * Gets the user in normal state. Surpassing the overload state. + * It doesn't affect permissions. But it enables plugins change the + * actual user permissions even in overload mode. + * @param userName + * @return + */ + public User surpassOverload(String userName) { + if (!isOverloaded(userName)) { + return getUser(userName); + } + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + return newUser; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java new file mode 100644 index 000000000..96e517abd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java @@ -0,0 +1,939 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.bukkit.Server; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + +/** + * + * @author gabrielcouto + */ +public class WorldDataHolder { + + /** + * + */ + protected String name; + /** + * The actual groups holder + */ + protected Map<String, Group> groups = new HashMap<String, Group>(); + /** + * The actual users holder + */ + protected Map<String, User> users = new HashMap<String, User>(); + /** + * Points to the default group + */ + protected Group defaultGroup = null; + /** + * The file, which this class loads/save data from/to + * @deprecated + */ + @Deprecated + protected File f; + /** + * + */ + protected AnjoPermissionsHandler permissionsHandler; + /** + * + */ + protected File usersFile; + /** + * + */ + protected File groupsFile; + /** + * + */ + protected boolean haveUsersChanged = false; + /** + * + */ + protected boolean haveGroupsChanged = false; + + /** + * Prevent direct instantiation + * @param worldName + */ + protected WorldDataHolder(String worldName) { + name = worldName; + } + + /** + * The main constructor for a new WorldDataHolder + * Please don't set the default group as null + * @param worldName + * @param defaultGroup the default group. its good to start with one + */ + public WorldDataHolder(String worldName, Group defaultGroup) { + this.name = worldName; + groups.put(defaultGroup.getName().toLowerCase(), defaultGroup); + this.defaultGroup = defaultGroup; + } + + /** + * Search for a user. If it doesn't exist, create a new one with + * default group. + * + * @param userName the name of the user + * @return class that manage that user permission + */ + public User getUser(String userName) { + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + return newUser; + } + + /** + * Add a user to the list. If it already exists, overwrite the old. + * @param theUser the user you want to add to the permission list + */ + public void addUser(User theUser) { + if (theUser.getDataSource() != this) { + theUser = theUser.clone(this); + } + if (theUser == null) { + return; + } + if ((theUser.getGroup() == null)) { + theUser.setGroup(defaultGroup); + } + removeUser(theUser.getName()); + users.put(theUser.getName().toLowerCase(), theUser); + haveUsersChanged = true; + } + + /** + * Removes the user from the list. (he might become a default user) + * @param userName the username from the user to remove + * @return true if it had something to remove + */ + public boolean removeUser(String userName) { + if (users.containsKey(userName.toLowerCase())) { + users.remove(userName.toLowerCase()); + haveUsersChanged = true; + return true; + } + return false; + } + + /** + * + * @param userName + * @return + */ + public boolean isUserDeclared(String userName) { + return users.containsKey(userName.toLowerCase()); + } + + /** + * Change the default group of the file. + * @param group the group you want make default. + */ + public void setDefaultGroup(Group group) { + if (!groups.containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) { + addGroup(group); + } + defaultGroup = this.getGroup(group.getName()); + haveGroupsChanged = true; + } + + /** + * Returns the default group of the file + * @return the default group + */ + public Group getDefaultGroup() { + return defaultGroup; + } + + /** + * Returns a group of the given name + * @param groupName the name of the group + * @return a group if it is found. null if not found. + */ + public Group getGroup(String groupName) { + return groups.get(groupName.toLowerCase()); + } + + /** + * Check if a group exists. + * Its the same of getGroup, but check if it is null. + * @param groupName the name of the group + * @return true if exists. false if not. + */ + public boolean groupExists(String groupName) { + return groups.containsKey(groupName.toLowerCase()); + } + + /** + * Add a group to the list + * @param groupToAdd + */ + public void addGroup(Group groupToAdd) { + if (groupToAdd.getDataSource() != this) { + groupToAdd = groupToAdd.clone(this); + } + removeGroup(groupToAdd.getName()); + groups.put(groupToAdd.getName().toLowerCase(), groupToAdd); + haveGroupsChanged = true; + } + + /** + * Remove the group to the list + * @param groupName + * @return true if had something to remove. false the group was default or non-existant + */ + public boolean removeGroup(String groupName) { + if (defaultGroup != null && groupName.equalsIgnoreCase(defaultGroup.getName())) { + return false; + } + if (groups.containsKey(groupName.toLowerCase())) { + groups.remove(groupName.toLowerCase()); + haveGroupsChanged = true; + return true; + } + return false; + + } + + /** + * Creates a new User with the given name + * and adds it to this holder. + * @param userName the username you want + * @return null if user already exists. or new User + */ + public User createUser(String userName) { + if (this.users.containsKey(userName.toLowerCase())) { + return null; + } + User newUser = new User(this, userName); + newUser.setGroup(defaultGroup); + this.addUser(newUser); + haveUsersChanged = true; + return newUser; + } + + /** + * Creates a new Group with the given name + * and adds it to this holder + * @param groupName the groupname you want + * @return null if group already exists. or new Group + */ + public Group createGroup(String groupName) { + if (this.groups.containsKey(groupName.toLowerCase())) { + return null; + } + Group newGroup = new Group(this, groupName); + this.addGroup(newGroup); + haveGroupsChanged = true; + return newGroup; + } + + /** + * + * @return a collection of the groups + */ + public Collection<Group> getGroupList() { + return groups.values(); + } + + /** + * + * @return a collection of the users + */ + public Collection<User> getUserList() { + return users.values(); + } + + /** + * reads the file again + */ + public void reload() { + try { + WorldDataHolder ph = load(this.getName(), getGroupsFile(), getUsersFile()); + this.defaultGroup = ph.defaultGroup; + this.groups = ph.groups; + this.users = ph.users; + } catch (Exception ex) { + Logger.getLogger(WorldDataHolder.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * Save by yourself! + * @deprecated + */ + @Deprecated + public void commit() { + writeGroups(this, getGroupsFile()); + writeUsers(this, getUsersFile()); + } + + /** + * Returns a data holder for the given file + * @param worldName + * @param file + * @return + * @throws Exception + * @deprecated + */ + @Deprecated + public static WorldDataHolder load(String worldName, File file) throws Exception { + WorldDataHolder ph = new WorldDataHolder(worldName); + ph.f = file; + final Yaml yaml = new Yaml(new SafeConstructor()); + Map<String, Object> rootDataNode; + if (!file.exists()) { + throw new Exception("The file which should contain permissions does not exist!\n" + file.getPath()); + } + FileInputStream rx = new FileInputStream(file); + try { + rootDataNode = (Map<String, Object>) yaml.load(new UnicodeReader(rx)); + if (rootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new Exception("The following file couldn't pass on Parser.\n" + file.getPath(), ex); + } finally { + rx.close(); + } + Map<String, List<String>> inheritance = new HashMap<String, List<String>>(); + try { + Map<String, Object> allGroupsNode = (Map<String, Object>) rootDataNode.get("groups"); + for (String groupKey : allGroupsNode.keySet()) { + Map<String, Object> thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey); + Group thisGrp = ph.createGroup(groupKey); + if (thisGrp == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey); + } + if (thisGroupNode.get("default") == null) { + thisGroupNode.put("default", false); + } + if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) { + if (ph.getDefaultGroup() != null) { + GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was."); + GroupManager.logger.warning("Overriding first request."); + } + ph.setDefaultGroup(thisGrp); + } + + //PERMISSIONS NODE + if (thisGroupNode.get("permissions") == null) { + thisGroupNode.put("permissions", new ArrayList<String>()); + } + if (thisGroupNode.get("permissions") instanceof List) { + for (Object o : ((List) thisGroupNode.get("permissions"))) { + thisGrp.addPermission(o.toString()); + } + } else if (thisGroupNode.get("permissions") instanceof String) { + thisGrp.addPermission((String) thisGroupNode.get("permissions")); + } else { + throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List<String>): " + thisGroupNode.get("permissions").getClass().getName()); + } + + //INFO NODE + Map<String, Object> infoNode = (Map<String, Object>) thisGroupNode.get("info"); + if (infoNode != null) { + thisGrp.setVariables(infoNode); + } + + //END INFO NODE + + Object inheritNode = thisGroupNode.get("inheritance"); + if (inheritNode == null) { + thisGroupNode.put("inheritance", new ArrayList<String>()); + } else if (inheritNode instanceof List) { + List<String> groupsInh = (List<String>) inheritNode; + for (String grp : groupsInh) { + if (inheritance.get(groupKey) == null) { + List<String> thisInherits = new ArrayList<String>(); + inheritance.put(groupKey, thisInherits); + } + inheritance.get(groupKey).add(grp); + + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Exception("Your Permissions config file is invalid. See console for details."); + } + if (ph.defaultGroup == null) { + throw new IllegalArgumentException("There was no Default Group declared."); + } + for (String groupKey : inheritance.keySet()) { + List<String> inheritedList = inheritance.get(groupKey); + Group thisGroup = ph.getGroup(groupKey); + for (String inheritedKey : inheritedList) { + Group inheritedGroup = ph.getGroup(inheritedKey); + if (thisGroup != null && inheritedGroup != null) { + thisGroup.addInherits(inheritedGroup); + } + } + } + // Process USERS + Map<String, Object> allUsersNode = (Map<String, Object>) rootDataNode.get("users"); + for (String usersKey : allUsersNode.keySet()) { + Map<String, Object> thisUserNode = (Map<String, Object>) allUsersNode.get(usersKey); + User thisUser = ph.createUser(usersKey); + if (thisUser == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey); + } + if (thisUserNode.get("permissions") == null) { + thisUserNode.put("permissions", new ArrayList<String>()); + } + if (thisUserNode.get("permissions") instanceof List) { + for (Object o : ((List) thisUserNode.get("permissions"))) { + thisUser.addPermission(o.toString()); + } + } else if (thisUserNode.get("permissions") instanceof String) { + thisUser.addPermission(thisUserNode.get("permissions").toString()); + } + + + //USER INFO NODE - BETA + + //INFO NODE + Map<String, Object> infoNode = (Map<String, Object>) thisUserNode.get("info"); + if (infoNode != null) { + thisUser.setVariables(infoNode); + } + //END INFO NODE - BETA + + if (thisUserNode.get("group") != null) { + Group hisGroup = ph.getGroup(thisUserNode.get("group").toString()); + if (hisGroup == null) { + throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName()); + } + thisUser.setGroup(hisGroup); + } else { + thisUser.setGroup(ph.defaultGroup); + } + } + return ph; + } + + /** + * Returns a data holder for the given file + * @param worldName + * @param groupsFile + * @param usersFile + * @return + * @throws FileNotFoundException + * @throws IOException + */ + public static WorldDataHolder load(String worldName, File groupsFile, File usersFile) throws FileNotFoundException, IOException { + WorldDataHolder ph = new WorldDataHolder(worldName); + ph.groupsFile = groupsFile; + ph.usersFile = usersFile; + + + //READ GROUPS FILE + Yaml yamlGroups = new Yaml(new SafeConstructor()); + Map<String, Object> groupsRootDataNode; + if (!groupsFile.exists()) { + throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath()); + } + FileInputStream groupsInputStream = new FileInputStream(groupsFile); + try { + groupsRootDataNode = (Map<String, Object>) yamlGroups.load(new UnicodeReader(groupsInputStream)); + if (groupsRootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex); + } finally { + groupsInputStream.close(); + } + + //PROCESS GROUPS FILE + Map<String, List<String>> inheritance = new HashMap<String, List<String>>(); + try { + Map<String, Object> allGroupsNode = (Map<String, Object>) groupsRootDataNode.get("groups"); + for (String groupKey : allGroupsNode.keySet()) { + Map<String, Object> thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey); + Group thisGrp = ph.createGroup(groupKey); + if (thisGrp == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey); + } + if (thisGroupNode.get("default") == null) { + thisGroupNode.put("default", false); + } + if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) { + if (ph.getDefaultGroup() != null) { + GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was."); + GroupManager.logger.warning("Overriding first request."); + } + ph.setDefaultGroup(thisGrp); + } + + //PERMISSIONS NODE + if (thisGroupNode.get("permissions") == null) { + thisGroupNode.put("permissions", new ArrayList<String>()); + } + if (thisGroupNode.get("permissions") instanceof List) { + for (Object o : ((List) thisGroupNode.get("permissions"))) { + thisGrp.addPermission(o.toString()); + } + } else if (thisGroupNode.get("permissions") instanceof String) { + thisGrp.addPermission((String) thisGroupNode.get("permissions")); + } else { + throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List<String>): " + thisGroupNode.get("permissions").getClass().getName()); + } + + //INFO NODE + Map<String, Object> infoNode = (Map<String, Object>) thisGroupNode.get("info"); + if (infoNode != null) { + thisGrp.setVariables(infoNode); + } + + //END INFO NODE + + Object inheritNode = thisGroupNode.get("inheritance"); + if (inheritNode == null) { + thisGroupNode.put("inheritance", new ArrayList<String>()); + } else if (inheritNode instanceof List) { + List<String> groupsInh = (List<String>) inheritNode; + for (String grp : groupsInh) { + if (inheritance.get(groupKey) == null) { + List<String> thisInherits = new ArrayList<String>(); + inheritance.put(groupKey, thisInherits); + } + inheritance.get(groupKey).add(grp); + + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new IllegalArgumentException("Your Permissions config file is invalid. See console for details."); + } + if (ph.defaultGroup == null) { + throw new IllegalArgumentException("There was no Default Group declared."); + } + for (String groupKey : inheritance.keySet()) { + List<String> inheritedList = inheritance.get(groupKey); + Group thisGroup = ph.getGroup(groupKey); + for (String inheritedKey : inheritedList) { + Group inheritedGroup = ph.getGroup(inheritedKey); + if (thisGroup != null && inheritedGroup != null) { + thisGroup.addInherits(inheritedGroup); + } + } + } + + + //READ USERS FILE + Yaml yamlUsers = new Yaml(new SafeConstructor()); + Map<String, Object> usersRootDataNode; + if (!groupsFile.exists()) { + throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath()); + } + FileInputStream usersInputStream = new FileInputStream(usersFile); + try { + usersRootDataNode = (Map<String, Object>) yamlUsers.load(new UnicodeReader(usersInputStream)); + if (usersRootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex); + } finally { + usersInputStream.close(); + } + + // PROCESS USERS FILE + Map<String, Object> allUsersNode = (Map<String, Object>) usersRootDataNode.get("users"); + for (String usersKey : allUsersNode.keySet()) { + Map<String, Object> thisUserNode = (Map<String, Object>) allUsersNode.get(usersKey); + User thisUser = ph.createUser(usersKey); + if (thisUser == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey); + } + if (thisUserNode.get("permissions") == null) { + thisUserNode.put("permissions", new ArrayList<String>()); + } + if (thisUserNode.get("permissions") instanceof List) { + for (Object o : ((List) thisUserNode.get("permissions"))) { + thisUser.addPermission(o.toString()); + } + } else if (thisUserNode.get("permissions") instanceof String) { + thisUser.addPermission(thisUserNode.get("permissions").toString()); + } + + //SUBGROUPS LOADING + if (thisUserNode.get("subgroups") == null) { + thisUserNode.put("subgroups", new ArrayList<String>()); + } + if (thisUserNode.get("subgroups") instanceof List) { + for (Object o : ((List) thisUserNode.get("subgroups"))) { + Group subGrp = ph.getGroup(o.toString()); + if (subGrp != null) { + thisUser.addSubGroup(subGrp); + } else { + GroupManager.logger.warning("Subgroup " + o.toString() + " not found for user " + thisUser.getName() + ". Ignoring entry."); + } + } + } else if (thisUserNode.get("subgroups") instanceof String) { + Group subGrp = ph.getGroup(thisUserNode.get("subgroups").toString()); + if (subGrp != null) { + thisUser.addSubGroup(subGrp); + } else { + GroupManager.logger.warning("Subgroup " + thisUserNode.get("subgroups").toString() + " not found for user " + thisUser.getName() + ". Ignoring entry."); + } + } + + + //USER INFO NODE - BETA + + //INFO NODE + Map<String, Object> infoNode = (Map<String, Object>) thisUserNode.get("info"); + if (infoNode != null) { + thisUser.setVariables(infoNode); + } + //END INFO NODE - BETA + + if (thisUserNode.get("group") != null) { + Group hisGroup = ph.getGroup(thisUserNode.get("group").toString()); + if (hisGroup == null) { + throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName()); + } + thisUser.setGroup(hisGroup); + } else { + thisUser.setGroup(ph.defaultGroup); + } + } + return ph; + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param file + * @deprecated + */ + @Deprecated + public static void write(WorldDataHolder ph, File file) { + Map<String, Object> root = new HashMap<String, Object>(); + + Map<String, Object> pluginMap = new HashMap<String, Object>(); + root.put("plugin", pluginMap); + + Map<String, Object> permissionsMap = new HashMap<String, Object>(); + pluginMap.put("permissions", permissionsMap); + + permissionsMap.put("system", "default"); + + Map<String, Object> groupsMap = new HashMap<String, Object>(); + root.put("groups", groupsMap); + for (String groupKey : ph.groups.keySet()) { + Group group = ph.groups.get(groupKey); + + Map<String, Object> aGroupMap = new HashMap<String, Object>(); + groupsMap.put(group.getName(), aGroupMap); + + aGroupMap.put("default", group.equals(ph.defaultGroup)); + + Map<String, Object> infoMap = new HashMap<String, Object>(); + aGroupMap.put("info", infoMap); + + for (String infoKey : group.getVariables().getVarKeyList()) { + infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); + } + + aGroupMap.put("inheritance", group.getInherits()); + + aGroupMap.put("permissions", group.getPermissionList()); + } + + Map<String, Object> usersMap = new HashMap<String, Object>(); + root.put("users", usersMap); + for (String userKey : ph.users.keySet()) { + User user = ph.users.get(userKey); + if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty()) { + continue; + } + + Map<String, Object> aUserMap = new HashMap<String, Object>(); + usersMap.put(user.getName(), aUserMap); + + if (user.getGroup() == null) { + aUserMap.put("group", ph.defaultGroup.getName()); + } else { + aUserMap.put("group", user.getGroup().getName()); + } + //USER INFO NODE - BETA + if (user.getVariables().getSize() > 0) { + Map<String, Object> infoMap = new HashMap<String, Object>(); + aUserMap.put("info", infoMap); + + for (String infoKey : user.getVariables().getVarKeyList()) { + infoMap.put(infoKey, user.getVariables().getVarObject(infoKey)); + } + } + //END USER INFO NODE - BETA + + aUserMap.put("permissions", user.getPermissionList()); + } + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(file, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param groupsFile + */ + public static void writeGroups(WorldDataHolder ph, File groupsFile) { + Map<String, Object> root = new HashMap<String, Object>(); + + Map<String, Object> groupsMap = new HashMap<String, Object>(); + root.put("groups", groupsMap); + for (String groupKey : ph.groups.keySet()) { + Group group = ph.groups.get(groupKey); + + Map<String, Object> aGroupMap = new HashMap<String, Object>(); + groupsMap.put(group.getName(), aGroupMap); + + if (ph.defaultGroup == null) { + GroupManager.logger.severe("There is no default group for world: " + ph.getName()); + } + aGroupMap.put("default", group.equals(ph.defaultGroup)); + + Map<String, Object> infoMap = new HashMap<String, Object>(); + aGroupMap.put("info", infoMap); + + for (String infoKey : group.getVariables().getVarKeyList()) { + infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); + } + + aGroupMap.put("inheritance", group.getInherits()); + + aGroupMap.put("permissions", group.getPermissionList()); + } + + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(groupsFile, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param usersFile + */ + public static void writeUsers(WorldDataHolder ph, File usersFile) { + Map<String, Object> root = new HashMap<String, Object>(); + + Map<String, Object> usersMap = new HashMap<String, Object>(); + root.put("users", usersMap); + for (String userKey : ph.users.keySet()) { + User user = ph.users.get(userKey); + if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) { + continue; + } + + Map<String, Object> aUserMap = new HashMap<String, Object>(); + usersMap.put(user.getName(), aUserMap); + + if (user.getGroup() == null) { + aUserMap.put("group", ph.defaultGroup.getName()); + } else { + aUserMap.put("group", user.getGroup().getName()); + } + //USER INFO NODE - BETA + if (user.getVariables().getSize() > 0) { + Map<String, Object> infoMap = new HashMap<String, Object>(); + aUserMap.put("info", infoMap); + for (String infoKey : user.getVariables().getVarKeyList()) { + infoMap.put(infoKey, user.getVariables().getVarObject(infoKey)); + } + } + //END USER INFO NODE - BETA + aUserMap.put("permissions", user.getPermissionList()); + + //SUBGROUPS NODE - BETA + aUserMap.put("subgroups", user.subGroupListStringCopy()); + //END SUBGROUPS NODE - BETA + } + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(usersFile, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Don't use this. Unless you want to make this plugin to interact with original Nijikokun Permissions + * This method is supposed to make the original one reload the file, and propagate the changes made here. + * + * Prefer to use the AnjoCaido's fake version of Nijikokun's Permission plugin. + * The AnjoCaido's Permission can propagate the changes made on this plugin instantly, + * without need to save the file. + * + * @param server the server that holds the plugin + * @deprecated it is not used anymore... unless if you use original Permissions + */ + @Deprecated + public static void reloadOldPlugins(Server server) { + // Only reload permissions + PluginManager pm = server.getPluginManager(); + Plugin[] plugins = pm.getPlugins(); + for (int i = 0; i < plugins.length; i++) { + plugins[i].getConfiguration().load(); + try { + plugins[i].getClass().getMethod("setupPermissions").invoke(plugins[i]); + } catch (Exception ex) { + continue; + } + } + } + + /** + * @return the permissionsHandler + */ + public AnjoPermissionsHandler getPermissionsHandler() { + if (permissionsHandler == null) { + permissionsHandler = new AnjoPermissionsHandler(this); + } + return permissionsHandler; + } + + /** + * + * @return + */ + public boolean haveUsersChanged() { + if (haveUsersChanged) { + return true; + } + for (User u : users.values()) { + if (u.isChanged()) { + return true; + } + } + return false; + } + + /** + * + * @return + */ + public boolean haveGroupsChanged() { + if (haveGroupsChanged) { + return true; + } + for (Group g : groups.values()) { + if (g.isChanged()) { + return true; + } + } + return false; + } + + /** + * + */ + public void removeUsersChangedFlag() { + haveUsersChanged = false; + for (User u : users.values()) { + u.flagAsSaved(); + } + } + + /** + * + */ + public void removeGroupsChangedFlag() { + haveGroupsChanged = false; + for (Group g : groups.values()) { + g.flagAsSaved(); + } + } + + /** + * @return the usersFile + */ + public File getUsersFile() { + return usersFile; + } + + /** + * @return the groupsFile + */ + public File getGroupsFile() { + return groupsFile; + } + + /** + * @return the name + */ + public String getName() { + return name; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java new file mode 100644 index 000000000..83073c10b --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java @@ -0,0 +1,423 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder.worlds; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.anjocaido.groupmanager.utils.Tasks; +import org.bukkit.entity.Player; + +/** + * + * @author gabrielcouto + */ +public class WorldsHolder { + + /** + * Map with instances of loaded worlds. + */ + private Map<String, OverloadedWorldHolder> worldsData = new HashMap<String, OverloadedWorldHolder>(); + /** + * Map of mirrors: <nonExistingWorldName, existingAndLoadedWorldName> + * The key is the mirror. + * The object is the mirrored. + * + * Mirror shows the same data of mirrored. + */ + private Map<String, String> mirrors = new HashMap<String, String>(); + private OverloadedWorldHolder defaultWorld; + private String serverDefaultWorldName; + private GroupManager plugin; + private File worldsFolder; + + /** + * + * @param plugin + */ + public WorldsHolder(GroupManager plugin) { + this.plugin = plugin; + verifyFirstRun(); + initialLoad(); + if (defaultWorld == null) { + throw new IllegalStateException("There is no default group! OMG!"); + } + } + + private void initialLoad() { + initialWorldLoading(); + mirrorSetUp(); + } + private void initialWorldLoading(){ + //LOAD EVERY WORLD POSSIBLE + loadWorld(serverDefaultWorldName); + defaultWorld = worldsData.get(serverDefaultWorldName); + + for (File folder : worldsFolder.listFiles()) { + if (folder.getName().equalsIgnoreCase(serverDefaultWorldName)) { + continue; + } + if (folder.isDirectory()) { + loadWorld(folder.getName()); + } + } + } + public void mirrorSetUp(){ + mirrors.clear(); + Map<String, Object> mirrorsMap = plugin.getConfig().getMirrorsMap(); + if (mirrorsMap != null) { + for (String source : mirrorsMap.keySet()) { + if (mirrorsMap.get(source) instanceof ArrayList) { + ArrayList mirrorList = (ArrayList) mirrorsMap.get(source); + for (Object o : mirrorList) { + try { + mirrors.remove(o.toString().toLowerCase()); + } catch (Exception e) { + } + mirrors.put(o.toString().toLowerCase(), getWorldData(source).getName()); + } + } else if (mirrorsMap.get(source) instanceof Object) { + String aMirror = mirrorsMap.get(source).toString(); + mirrors.put(aMirror.toLowerCase(), getWorldData(source).getName()); + } + } + } + } + + /** + * + */ + public void reloadAll() { + ArrayList<WorldDataHolder> alreadyDone = new ArrayList<WorldDataHolder>(); + for (WorldDataHolder w : worldsData.values()) { + if (alreadyDone.contains(w)) { + continue; + } + w.reload(); + alreadyDone.add(w); + } + } + + /** + * + * @param worldName + */ + public void reloadWorld(String worldName) { + getWorldData(worldName).reload(); + } + + /** + * + */ + public void saveChanges() { + ArrayList<WorldDataHolder> alreadyDone = new ArrayList<WorldDataHolder>(); + for (OverloadedWorldHolder w : worldsData.values()) { + if (alreadyDone.contains(w)) { + continue; + } + Tasks.removeOldFiles(plugin.getBackupFolder()); + if (w == null) { + GroupManager.logger.severe("WHAT HAPPENED?"); + continue; + } + if (w.haveGroupsChanged()) { + String groupsFolderName = w.getGroupsFile().getParentFile().getName(); + File backupGroups = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_g_" + Tasks.getDateString() + ".yml"); + try { + Tasks.copy(w.getGroupsFile(), backupGroups); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + WorldDataHolder.writeGroups(w, w.getGroupsFile()); + w.removeGroupsChangedFlag(); + } + if (w.haveUsersChanged()) { + File backupUsers = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_u_" + Tasks.getDateString() + ".yml"); + try { + Tasks.copy(w.getUsersFile(), backupUsers); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + WorldDataHolder.writeUsers(w, w.getUsersFile()); + w.removeUsersChangedFlag(); + } + alreadyDone.add(w); + } + } + + /** + * Returns the dataHolder for the given world. + * If the world is not on the worlds list, returns the default world + * holder. + * + * (WHEN A WORLD IS CONFIGURED TO MIRROR, IT WILL BE ON THE LIST, BUT + * POINTING TO ANOTHER WORLD HOLDER) + * + * Mirrors prevails original data. + * + * @param worldName + * @return + */ + public OverloadedWorldHolder getWorldData(String worldName) { + OverloadedWorldHolder data = worldsData.get(worldName.toLowerCase()); + if (mirrors.containsKey(worldName.toLowerCase())) { + String realOne = mirrors.get(worldName.toLowerCase()); + data = worldsData.get(realOne.toLowerCase()); + } + if (data == null) { + GroupManager.logger.finest("Requested world " + worldName + " not found or badly mirrored. Returning default world..."); + data = getDefaultWorld(); + } + return data; + } + + /** + * Do a matching of playerName, if it s found only one player, do + * getWorldData(player) + * @param playerName + * @return null if matching returned no player, or more than one. + */ + public OverloadedWorldHolder getWorldDataByPlayerName(String playerName) { + List<Player> matchPlayer = plugin.getServer().matchPlayer(playerName); + if (matchPlayer.size() == 1) { + return getWorldData(matchPlayer.get(0)); + } + return null; + } + + /** + * Retrieves the field p.getWorld().getName() and do + * getWorld(worldName) + * @param p + * @return + */ + public OverloadedWorldHolder getWorldData(Player p) { + return getWorldData(p.getWorld().getName()); + } + + /** + * It does getWorld(worldName).getPermissionsHandler() + * @param worldName + * @return + */ + public AnjoPermissionsHandler getWorldPermissions(String worldName) { + return getWorldData(worldName).getPermissionsHandler(); + } + + /** + *It does getWorldData(p).getPermission + * @param p + * @return + */ + public AnjoPermissionsHandler getWorldPermissions(Player p) { + return getWorldData(p).getPermissionsHandler(); + } + + /** + * Id does getWorldDataByPlayerName(playerName). + * If it doesnt return null, it will return result.getPermissionsHandler() + * @param playerName + * @return null if the player matching gone wrong. + */ + public AnjoPermissionsHandler getWorldPermissionsByPlayerName(String playerName) { + WorldDataHolder dh = getWorldDataByPlayerName(playerName); + if (dh != null) { + return dh.getPermissionsHandler(); + } + return null; + } + + private void verifyFirstRun() { + worldsFolder = new File(plugin.getDataFolder(), "worlds"); + if (!worldsFolder.exists()) { + worldsFolder.mkdirs(); + } + Properties server = new Properties(); + try { + server.load(new FileInputStream(new File("server.properties"))); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + serverDefaultWorldName = server.getProperty("level-name").toLowerCase(); + File defaultWorldFolder = new File(worldsFolder, serverDefaultWorldName); + if (!defaultWorldFolder.exists()) { + defaultWorldFolder.mkdirs(); + } + if (defaultWorldFolder.exists()) { + File groupsFile = new File(defaultWorldFolder, "groups.yml"); + File usersFile = new File(defaultWorldFolder, "users.yml"); + File oldDataFile = new File(plugin.getDataFolder(), "data.yml"); + if (!groupsFile.exists()) { + if (oldDataFile.exists()) { + try { + Tasks.copy(oldDataFile, groupsFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } else { + InputStream template = plugin.getResourceAsStream("groups.yml"); + try { + Tasks.copy(template, groupsFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + } + if (!usersFile.exists()) { + if (oldDataFile.exists()) { + try { + Tasks.copy(oldDataFile, usersFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } else { + InputStream template = plugin.getResourceAsStream("users.yml"); + try { + Tasks.copy(template, usersFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + } + try { + if (oldDataFile.exists()) { + oldDataFile.renameTo(new File(plugin.getDataFolder(), "NOT_USED_ANYMORE_data.yml")); + } + } catch (Exception ex) { + } + } + } + + /** + * Copies the specified world data to another world + * @param fromWorld + * @param toWorld + * @return + */ + public boolean cloneWorld(String fromWorld, String toWorld) { + File fromWorldFolder = new File(worldsFolder, fromWorld); + File toWorldFolder = new File(worldsFolder, toWorld); + if (toWorldFolder.exists() || !fromWorldFolder.exists()) { + return false; + } + File fromWorldGroups = new File(fromWorldFolder, "groups.yml"); + File fromWorldUsers = new File(fromWorldFolder, "users.yml"); + if (!fromWorldGroups.exists() || !fromWorldUsers.exists()) { + return false; + } + File toWorldGroups = new File(toWorldFolder, "groups.yml"); + File toWorldUsers = new File(toWorldFolder, "users.yml"); + toWorldFolder.mkdirs(); + try { + Tasks.copy(fromWorldGroups, toWorldGroups); + Tasks.copy(fromWorldUsers, toWorldUsers); + } catch (IOException ex) { + Logger.getLogger(WorldsHolder.class.getName()).log(Level.SEVERE, null, ex); + return false; + } + return true; + } + + /** + * Load a world from file. + * If it already been loaded, summon reload method from dataHolder. + * @param worldName + */ + public void loadWorld(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase())) { + worldsData.get(worldName.toLowerCase()).reload(); + return; + } + GroupManager.logger.finest("Trying to load world " + worldName + "..."); + File thisWorldFolder = new File(worldsFolder, worldName); + if (thisWorldFolder.exists() && thisWorldFolder.isDirectory()) { + File groupsFile = new File(thisWorldFolder, "groups.yml"); + File usersFile = new File(thisWorldFolder, "users.yml"); + if (!groupsFile.exists()) { + throw new IllegalArgumentException("Groups file for world '" + worldName + "' doesnt exist: " + groupsFile.getPath()); + } + if (!usersFile.exists()) { + throw new IllegalArgumentException("Users file for world '" + worldName + "' doesnt exist: " + usersFile.getPath()); + } + try { + OverloadedWorldHolder thisWorldData = new OverloadedWorldHolder(WorldDataHolder.load(worldName, groupsFile, usersFile)); + if (thisWorldData != null) { + GroupManager.logger.finest("Successful load of world " + worldName + "..."); + worldsData.put(worldName.toLowerCase(), thisWorldData); + return; + } + } catch (FileNotFoundException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + return; + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + return; + } + GroupManager.logger.severe("Failed to load world " + worldName + "..."); + } + } + + /** + * Tells if the such world has been mapped. + * + * It will return true if world is a mirror. + * + * @param worldName + * @return true if world is loaded or mirrored. false if not listed + */ + public boolean isInList(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase()) || mirrors.containsKey(worldName.toLowerCase())) { + return true; + } + return false; + } + + /** + * Verify if world has it's own file permissions. + * + * @param worldName + * @return true if it has its own holder. false if not. + */ + public boolean hasOwnData(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase())) { + return true; + } + return false; + } + + /** + * @return the defaultWorld + */ + public OverloadedWorldHolder getDefaultWorld() { + return defaultWorld; + } + + /** + * Returns all physically loaded worlds. + * @return + */ + public ArrayList<OverloadedWorldHolder> allWorldsDataList() { + ArrayList<OverloadedWorldHolder> list = new ArrayList<OverloadedWorldHolder>(); + for (OverloadedWorldHolder data : worldsData.values()) { + if (!list.contains(data)) { + list.add(data); + } + } + return list; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java new file mode 100644 index 000000000..ca223da81 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java @@ -0,0 +1,856 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.permissions; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.StringTokenizer; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.utils.PermissionCheckResult; +import org.bukkit.entity.Player; + +/** + * Everything here maintains the model created by Nijikokun + * + * But implemented to use GroupManager system. Which provides instant changes, + * without file access. + * + * It holds permissions only for one single world. + * + * @author gabrielcouto + */ +public class AnjoPermissionsHandler extends PermissionsReaderInterface { + + WorldDataHolder ph = null; + + /** + * It needs a WorldDataHolder to work with. + * @param holder + */ + public AnjoPermissionsHandler(WorldDataHolder holder) { + ph = holder; + } + + /** + * A short name method, for permission method. + * @param player + * @param permission + * @return + */ + @Override + public boolean has(Player player, String permission) { + return permission(player, permission); + } + + /** + * Checks if a player can use that permission node. + * @param player + * @param permission + * @return + */ + @Override + public boolean permission(Player player, String permission) { + return checkUserPermission(ph.getUser(player.getName()), permission); + } + + /** + * Returns the name of the group of that player name. + * @param userName + * @return + */ + @Override + public String getGroup(String userName) { + return ph.getUser(userName).getGroup().getName(); + } + + /** + * Verify if player is in suck group. + * It will check it's groups inheritance. + * + * So if you have a group Admin > Moderator + * + * And verify the player 'MyAdmin', which is Admin, it will return true for both + * Admin or Moderator groups. + * + * Mas if you haave a player 'MyModerator', which is Moderator, + * it will give false if you pass Admin in group parameter. + * + * @param name + * @param group + * @return + */ + @Override + public boolean inGroup(String name, String group) { + if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) { + return true; + } + for (Group subGroup : ph.getUser(name).subGroupListCopy()) { + if (hasGroupInInheritance(subGroup, group)) { + return true; + } + } + return false; + } + + /** + * Returns the String prefix for the given group + * @param groupName + * @return empty string if found none. + */ + @Override + public String getGroupPrefix(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return null; + } + return g.getVariables().getVarString("prefix"); + } + + /** + * Return the suffix for the given group name + * @param groupName + * @return + */ + @Override + public String getGroupSuffix(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return null; + } + return g.getVariables().getVarString("suffix"); + } + + /** + * + * @param groupName + * @return + */ + @Override + public boolean canGroupBuild(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return false; + } + return g.getVariables().getVarBoolean("build"); + } + + /** + * It returns a string variable value, set in the INFO node of the group. + * It will harvest inheritance for value. + * @param groupName + * @param variable + * @return null if no group with that variable is found. + */ + @Override + public String getGroupPermissionString(String groupName, String variable) { + Group start = ph.getGroup(groupName); + if (start == null) { + return null; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return null; + } + return result.getVariables().getVarString(variable); + } + + /** + * It returns a Integer variable value + * It will harvest inheritance for value. + * @param groupName + * @param variable + * @return -1 if none found or not parseable. + */ + @Override + public int getGroupPermissionInteger(String groupName, String variable) { + Group start = ph.getGroup(groupName); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarInteger(variable); + } + + /** + * Returns a boolean for given variable in INFO node. + * It will harvest inheritance for value. + * @param group + * @param variable + * @return false if not found/not parseable. + */ + @Override + public boolean getGroupPermissionBoolean(String group, String variable) { + Group start = ph.getGroup(group); + if (start == null) { + return false; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return false; + } + return result.getVariables().getVarBoolean(variable); + } + + /** + * Returns a double value for the given variable name in INFO node. + * It will harvest inheritance for value. + * @param group + * @param variable + * @return -1 if not found / not parseable. + */ + @Override + public double getGroupPermissionDouble(String group, String variable) { + Group start = ph.getGroup(group); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarDouble(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public String getUserPermissionString(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return ""; + } + return auser.getVariables().getVarString(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public int getUserPermissionInteger(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + return auser.getVariables().getVarInteger(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public boolean getUserPermissionBoolean(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return false; + } + return auser.getVariables().getVarBoolean(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public double getUserPermissionDouble(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + return auser.getVariables().getVarDouble(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return empty string if not found + */ + @Override + public String getPermissionString(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return ""; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarString(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return ""; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return ""; + } + return result.getVariables().getVarString(variable); + //return getUserPermissionString(user, variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return -1 if not found + */ + @Override + public int getPermissionInteger(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarInteger(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarInteger(variable); + //return getUserPermissionInteger(string, string1); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return false if not found or not parseable to true. + */ + @Override + public boolean getPermissionBoolean(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return false; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarBoolean(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return false; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return false; + } + return result.getVariables().getVarBoolean(variable); + //return getUserPermissionBoolean(user, string1); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return -1 if not found. + */ + @Override + public double getPermissionDouble(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1.0D; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarDouble(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return -1.0D; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1.0D; + } + return result.getVariables().getVarDouble(variable); + //return getUserPermissionDouble(string, string1); + } + + /** + * Does not include User's group permission + * @param user + * @param permission + * @return + */ + public PermissionCheckResult checkUserOnlyPermission(User user, String permission) { + user.sortPermissions(); + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = permission; + result.owner = user; + for (String access : user.getPermissionList()) { + if (comparePermissionString(access, permission)) { + result.accessLevel = access; + if (access.startsWith("-")) { + result.resultType = PermissionCheckResult.Type.NEGATION; + } else if (access.startsWith("+")) { + result.resultType = PermissionCheckResult.Type.EXCEPTION; + } else { + result.resultType = PermissionCheckResult.Type.FOUND; + } + return result; + } + } + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * Returns the node responsible for that permission. + * Does not include User's group permission. + * @param group + * @param permission + * @return the node if permission is found. if not found, return null + */ + public PermissionCheckResult checkGroupOnlyPermission(Group group, String permission) { + group.sortPermissions(); + PermissionCheckResult result = new PermissionCheckResult(); + result.owner = group; + result.askedPermission = permission; + for (String access : group.getPermissionList()) { + if (comparePermissionString(access, permission)) { + result.accessLevel = access; + if (access.startsWith("-")) { + result.resultType = PermissionCheckResult.Type.NEGATION; + } else if (access.startsWith("+")) { + result.resultType = PermissionCheckResult.Type.EXCEPTION; + } else { + result.resultType = PermissionCheckResult.Type.FOUND; + } + return result; + } + } + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * Check permissions, including it's group and inheritance. + * @param user + * @param permission + * @return true if permission was found. false if not, or was negated. + */ + public boolean checkUserPermission(User user, String permission) { + PermissionCheckResult result = checkFullUserPermission(user, permission); + if (result.resultType.equals(PermissionCheckResult.Type.EXCEPTION) + || result.resultType.equals(PermissionCheckResult.Type.FOUND)) { + return true; + } + return false; + } + + /** + * Do what checkUserPermission did before. But now returning a PermissionCheckResult. + * @param user + * @param targetPermission + * @return + */ + public PermissionCheckResult checkFullUserPermission(User user, String targetPermission) { + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = targetPermission; + result.resultType = PermissionCheckResult.Type.NOTFOUND; + + if (user == null || targetPermission == null) { + return result; + } + + PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission); + if (!resultUser.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultUser; + + } + + //IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT FOUND + PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission); + if (!resultGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultGroup; + } + + //SUBGROUPS CHECK + for (Group subGroup : user.subGroupListCopy()) { + PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission); + if (!resultSubGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultSubGroup; + } + } + + //THEN IT RETURNS A NOT FOUND + return result; + } + + /** + * Verifies if a given group has a variable. Including it's inheritance. + * + * it redirects to the other method now. This one was deprecated, and will + * be gone in a future release. + * + * @param start + * @param variable + * @param alreadyChecked + * @return returns the closest inherited group with the variable. + * @deprecated use now nextGroupWithVariable(Group start, String targetVariable) + */ + @Deprecated + public Group nextGroupWithVariable(Group start, String variable, List<Group> alreadyChecked) { + return nextGroupWithVariable(start, variable); + } + + /** + * Returns the next group, including inheritance, which contains that + * variable name. + * + * It does Breadth-first search + * + * @param start the starting group to look for + * @param targetVariable the variable name + * @return The group if found. Null if not. + */ + public Group nextGroupWithVariable(Group start, String targetVariable) { + if (start == null || targetVariable == null) { + return null; + } + LinkedList<Group> stack = new LinkedList<Group>(); + ArrayList<Group> alreadyVisited = new ArrayList<Group>(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + if (now.getVariables().hasVar(targetVariable)) { + return now; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return null; + } + + /** + * Check if given group inherits another group. + * + * redirected to the other method. this is deprecated now. and will be gone + * in the future releases. + * + * @param start The group to start the search. + * @param askedGroup Name of the group you're looking for + * @param alreadyChecked groups to ignore(pass null on it, please) + * @return true if it inherits the group. + * @deprecated prefer using hasGroupInInheritance(Group start, String askedGroup) + */ + @Deprecated + public boolean searchGroupInInheritance(Group start, String askedGroup, List<Group> alreadyChecked) { + return hasGroupInInheritance(start, askedGroup); + } + + /** + * Check if given group inherits another group. + * + * It does Breadth-first search + * + * @param start The group to start the search. + * @param askedGroup Name of the group you're looking for + * @return true if it inherits the group. + */ + public boolean hasGroupInInheritance(Group start, String askedGroup) { + if (start == null || askedGroup == null) { + return false; + } + LinkedList<Group> stack = new LinkedList<Group>(); + ArrayList<Group> alreadyVisited = new ArrayList<Group>(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + if (now.getName().equalsIgnoreCase(askedGroup)) { + return true; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return false; + } + + /** + * Check if the group has given permission. Including it's inheritance + * @param start + * @param permission + * @param alreadyChecked + * @return true if PermissionCheckResult is EXCEPTION or FOUND + * @deprecated use the other checkGroupPermissionWithInheritance for everything + */ + @Deprecated + public boolean checkGroupPermissionWithInheritance(Group start, String permission, List<Group> alreadyChecked) { + PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission); + if (result.resultType.equals(result.resultType.EXCEPTION) + || result.resultType.equals(result.resultType.FOUND)) { + return true; + } + return false; + } + + /** + * Returns the result of permission check. Including inheritance. + * If found anything, the PermissionCheckResult that retuns will + * include the Group name, and the result type. + * Result types will be EXCEPTION, NEGATION, FOUND. + * + * If returned type NOTFOUND, the owner will be null, + * and ownerType too. + * + * It does Breadth-first search + * + * @param start + * @param targetPermission + * @return + */ + public PermissionCheckResult checkGroupPermissionWithInheritance(Group start, String targetPermission) { + if (start == null || targetPermission == null) { + return null; + } + LinkedList<Group> stack = new LinkedList<Group>(); + List<Group> alreadyVisited = new ArrayList<Group>(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission); + if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultNow; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = targetPermission; + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * It uses checkGroupPermissionWithInheritance + * and cast the owner to Group type if result type was EXCEPTION or FOUND. + * + * @param start + * @param permission + * @param alreadyChecked + * @return the group that passed on test. null if no group passed. + * @deprecated use checkGroupPermissionWithInheritance for everything now. + */ + @Deprecated + public Group nextGroupWithPermission(Group start, String permission, List<Group> alreadyChecked) { + PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission); + if (result.resultType.equals(result.resultType.EXCEPTION) + || result.resultType.equals(result.resultType.FOUND)) { + return (Group) checkGroupPermissionWithInheritance(start, permission).owner; + } + return null; + } + + /** + * Return whole list of names of groups in a inheritance chain. Including a + * starting group. + * + * it now redirects to the other method. but get away from this one, + * it will disappear in a future release. + * + * @param start + * @param alreadyChecked + * @return the group that passed on test. null if no group passed. + * @deprecated use the other method with same name, instead + */ + @Deprecated + public ArrayList<String> listAllGroupsInherited(Group start, ArrayList<String> alreadyChecked) { + return listAllGroupsInherited(start); + } + + /** + * Return whole list of names of groups in a inheritance chain. Including a + * starting group. + * + * It does Breadth-first search. So closer groups will appear first in list. + * + * @param start + * @return the group that passed on test. null if no group passed. + */ + public ArrayList<String> listAllGroupsInherited(Group start) { + if (start == null) { + return null; + } + LinkedList<Group> stack = new LinkedList<Group>(); + ArrayList<String> alreadyVisited = new ArrayList<String>(); + stack.push(start); + alreadyVisited.add(start.getName()); + while (!stack.isEmpty()) { + Group now = stack.pop(); + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son.getName())) { + stack.push(son); + alreadyVisited.add(son.getName()); + } + } + } + return alreadyVisited; + } + + /** + * Compare a user permission like 'myplugin.*' against a full plugin + * permission name, like 'myplugin.dosomething'. + * As the example above, will return true. + * + * Please sort permissions before sending them here. So negative tokens + * get priority. + * + * You must test if it start with negative outside this method. It will + * only tell if the nodes are matching or not. + * + * Every '-' or '+' in the beginning is ignored. It will match only + * node names. + * + * @param userAcessLevel + * @param fullPermissionName + * @return true if found a matching token. false if not. + */ + public boolean comparePermissionString(String userAcessLevel, String fullPermissionName) { + if (userAcessLevel == null || fullPermissionName == null) { + return false; + } + GroupManager.logger.finest("COMPARING " + userAcessLevel + " WITH " + fullPermissionName); + + if (userAcessLevel.startsWith("+")) { + userAcessLevel = userAcessLevel.substring(1); + } else if (userAcessLevel.startsWith("-")) { + userAcessLevel = userAcessLevel.substring(1); + } + + if (fullPermissionName.startsWith("+")) { + fullPermissionName = fullPermissionName.substring(1); + } else if (fullPermissionName.startsWith("-")) { + fullPermissionName = fullPermissionName.substring(1); + } + + + StringTokenizer levelATokenizer = new StringTokenizer(userAcessLevel, "."); + StringTokenizer levelBTokenizer = new StringTokenizer(fullPermissionName, "."); + while (levelATokenizer.hasMoreTokens() && levelBTokenizer.hasMoreTokens()) { + String levelA = levelATokenizer.nextToken(); + String levelB = levelBTokenizer.nextToken(); + GroupManager.logger.finest("ROUND " + levelA + " AGAINST " + levelB); + if (levelA.contains("*")) { + GroupManager.logger.finest("WIN"); + return true; + } + if (levelA.equalsIgnoreCase(levelB)) { + if (!levelATokenizer.hasMoreTokens() && !levelBTokenizer.hasMoreTokens()) { + GroupManager.logger.finest("WIN"); + return true; + } + GroupManager.logger.finest("NEXT"); + continue; + } else { + GroupManager.logger.finest("FAIL"); + return false; + } + + } + GroupManager.logger.finest("FAIL"); + return false; + } + + /** + * Returns a list of all groups. + * + * Including subgroups. + * @param userName + * @return + */ + public String[] getGroups(String userName) { + ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup()); + for(Group subg: ph.getUser(userName).subGroupListCopy()){ + allGroups.addAll(listAllGroupsInherited(subg)); + } + String[] arr = new String[allGroups.size()]; + return allGroups.toArray(arr); + } + + /** + * A Breadth-first search thru inheritance model. + * + * Just a model to copy and paste. + * This will guarantee the closer groups will be checked first. + * @param start + * @param targerPermission + * @return + */ + private Group breadthFirstSearch(Group start, String targerPermission) { + if (start == null || targerPermission == null) { + return null; + } + LinkedList<Group> stack = new LinkedList<Group>(); + ArrayList<Group> alreadyVisited = new ArrayList<Group>(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targerPermission); + if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION) + || resultNow.resultType.equals(PermissionCheckResult.Type.FOUND)) { + return now; + } + if (resultNow.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + return null; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return null; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java new file mode 100644 index 000000000..90194cddd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java @@ -0,0 +1,163 @@ +package org.anjocaido.groupmanager.permissions; + +import org.bukkit.entity.Player; + +/** + * Made by Nijikokun. Changed by Gabriel Couto + * + * This class is intended to *read* permissions from a single world. + * + * @author Nijikokun + * @author Gabriel Couto + */ +public abstract class PermissionsReaderInterface { + + + /** + * + * @param player + * @param string + * @return + */ + public abstract boolean has(Player player, String string); + + /** + * + * @param player + * @param string + * @return + */ + public abstract boolean permission(Player player, String string); + + /** + * + * @param string + * @return + */ + public abstract String getGroup(String string); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean inGroup(String string, String string1); + + /** + * + * @param string + * @return + */ + public abstract String getGroupPrefix(String string); + + /** + * + * @param string + * @return + */ + public abstract String getGroupSuffix(String string); + + /** + * + * @param string + * @return + */ + public abstract boolean canGroupBuild(String string); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getGroupPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getGroupPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getGroupPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getGroupPermissionDouble(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getUserPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getUserPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getUserPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getUserPermissionDouble(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getPermissionDouble(String string, String string1); +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java new file mode 100644 index 000000000..87b6806ab --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java @@ -0,0 +1,26 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +/** + * + * @author gabrielcouto + */ +public class GMLoggerHandler extends ConsoleHandler { + + @Override + public void publish(LogRecord record) { + String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage(); + if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) { + System.err.println(message); + } else { + System.out.println(message); + } + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java new file mode 100644 index 000000000..781f2753c --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java @@ -0,0 +1,51 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +/** + * Just a list of commands for this plugin + * @author gabrielcouto + */ +public enum GroupManagerPermissions { + manuadd, + manudel, + manuaddsub, + manudelsub, + mangadd, + mangdel, + manuaddp, + manudelp, + manulistp, + manucheckp, + mangaddp, + mangdelp, + manglistp, + mangcheckp, + mangaddi, + mangdeli, + manuaddv, + manudelv, + manulistv, + manucheckv, + mangaddv, + mangdelv, + manglistv, + mangcheckv, + manwhois, + tempadd, + tempdel, + templist, + tempdelall, + mansave, + manload, + listgroups, + manpromote, + mandemote, + mantogglevalidate, + mantogglesave, + manworld, + manselect, + manclear +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java new file mode 100644 index 000000000..3ee6fdf30 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java @@ -0,0 +1,66 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import org.anjocaido.groupmanager.data.DataUnit; + +/** + * + * @author gabrielcouto + */ +public class PermissionCheckResult { + /** + * It should be the owner of the access level found. + * + * Use instanceof to find the owner type + */ + public DataUnit owner; + /** + * The permission node found in the DataUnit. + */ + public String accessLevel; + /** + * The full name of the permission you are looking for + */ + public String askedPermission; + /** + * The result conclusion of the search. + * It determines if the owner can do, or not. + * + * It even determines if it has an owner. + */ + public Type resultType = Type.NOTFOUND; + + /** + * The type of result the search can give. + */ + public enum Type { + + /** + * If found a matching node starting with '+'. + * It means the user CAN do the permission. + */ + EXCEPTION, + /** + * If found a matching node starting with '-'. + * It means the user CANNOT do the permission. + */ + NEGATION, + /** + * If just found a common matching node. + * IT means the user CAN do the permission. + */ + FOUND, + /** + * If no matchin node was found. + * It means the user CANNOT do the permission. + * + * owner field and accessLevel field should not be considered, + * when type is + * NOTFOUND + */ + NOTFOUND + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java new file mode 100644 index 000000000..2e192118d --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java @@ -0,0 +1,50 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.anjocaido.groupmanager.utils; + +import java.util.Comparator; + +/** + * + * @author gabrielcouto + */ +public class StringPermissionComparator implements Comparator<String> { + + @Override + public int compare(String permA, String permB) { + boolean ap = permA.startsWith("+"); + boolean bp = permB.startsWith("+"); + boolean am = permA.startsWith("-"); + boolean bm = permB.startsWith("-"); + if(ap&&bp){ + return 0; + } + if(ap&&!bp){ + return -1; + } + if(!ap&&bp){ + return 1; + } + if(am&&bm){ + return 0; + } + if(am&&!bm){ + return -1; + } + if(!am&&bm){ + return 1; + } + return permA.compareToIgnoreCase(permB); + } + private static StringPermissionComparator instance; + public static StringPermissionComparator getInstance(){ + if(instance==null){ + instance = new StringPermissionComparator(); + } + return instance; + } + +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java new file mode 100644 index 000000000..64bdb6209 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java @@ -0,0 +1,111 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.List; +import org.anjocaido.groupmanager.data.Group; + +/** + * + * @author gabrielcouto + */ +public abstract class Tasks { + + public static void copy(InputStream src, File dst) throws IOException { + InputStream in = src; + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + try { + in.close(); + } catch (Exception e) { + } + } + + public static void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + copy(in, dst); + } + + public static void removeOldFiles(File folder) { + if (folder.isDirectory()) { + long oldTime = System.currentTimeMillis() - 86400000L; + for (File olds : folder.listFiles()) { + if (olds.isFile()) { + if (olds.lastModified() < oldTime) { + try { + olds.delete(); + } catch (Exception e) { + } + } + } + } + } + } + + public static String getDateString() { + GregorianCalendar now = new GregorianCalendar(); + String date = ""; + date += now.get(GregorianCalendar.DAY_OF_MONTH); + date += "-"; + date += now.get(GregorianCalendar.HOUR); + date += "-"; + date += now.get(GregorianCalendar.MINUTE); + return date; + } + public static String getStringListInString(List<String> list){ + if(list==null){ + return ""; + } + String result=""; + for(int i=0;i<list.size();i++){ + result+=list.get(i); + if(i<list.size()-1){ + result+=", "; + } + } + return result; + } + public static String getStringArrayInString(String[] list){ + if(list==null){ + return ""; + } + String result=""; + for(int i=0;i<list.length;i++){ + result+=list[i]; + if(i<((list.length)-1)){ + result+=", "; + } + } + return result; + } + public static String getGroupListInString(List<Group> list){ + if(list==null){ + return ""; + } + String result=""; + for(int i=0;i<list.size();i++){ + result+=list.get(i).getName(); + if(i<list.size()-1){ + result+=", "; + } + } + return result; + } +} |