Merge pull request #60 from timvisee/master

Added intelligent command manager and help system
This commit is contained in:
Gabriele C 2015-11-01 23:24:53 +01:00
commit 43327e9892
50 changed files with 5206 additions and 46 deletions

View File

@ -502,5 +502,12 @@
<optional>true</optional>
</dependency>
<!-- String comparison library. Used for dynamic help system. -->
<dependency>
<groupId>net.ricecode</groupId>
<artifactId>string-similarity</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -11,11 +11,13 @@ import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import fr.xephi.authme.command.CommandHandler;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
@ -73,10 +75,21 @@ import net.minelink.ctplus.CombatTagPlus;
public class AuthMe extends JavaPlugin {
/** Defines the name of the plugin. */
// TODO: Create a getter method for this constant, and make it private
public static final String PLUGIN_NAME = "AuthMeReloaded";
/** Defines the current AuthMeReloaded version name. */
private static final String PLUGIN_VERSION_NAME = "5.1-SNAPSHOT";
/** Defines the current AuthMeReloaded version code. */
private static final int PLUGIN_VERSION_CODE = 100; // Increase this number by one when an update is released
private static AuthMe authme;
private static Server server;
private Logger authmeLogger;
// TODO: Move this to a better place! -- timvisee
private CommandHandler commandHandler = null;
public Management management;
public NewAPI api;
public SendMailSSL mail;
@ -140,6 +153,10 @@ public class AuthMe extends JavaPlugin {
authmeLogger = Logger.getLogger("AuthMe");
authme = this;
// Set up and initialize the command handler
this.commandHandler = new CommandHandler(false);
this.commandHandler.init();
// TODO: split the plugin in more modules
moduleManager = new ModuleManager(this);
@SuppressWarnings("unused")
@ -327,16 +344,17 @@ public class AuthMe extends JavaPlugin {
pm.registerEvents(new AuthMeEntityListener(this), this);
pm.registerEvents(new AuthMeServerListener(this), this);
// TODO: This is moved to CommandManager.registerCommands() handled by AuthMe.onCommand() -- timvisee
// Register commands
getCommand("authme").setExecutor(new AdminCommand(this));
getCommand("register").setExecutor(new RegisterCommand(this));
getCommand("login").setExecutor(new LoginCommand(this));
getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
getCommand("logout").setExecutor(new LogoutCommand(this));
getCommand("unregister").setExecutor(new UnregisterCommand(this));
getCommand("email").setExecutor(new EmailCommand(this));
getCommand("captcha").setExecutor(new CaptchaCommand(this));
getCommand("converter").setExecutor(new ConverterCommand(this));
//getCommand("authme").setExecutor(new AdminCommand(this));
//getCommand("register").setExecutor(new RegisterCommand(this));
//getCommand("login").setExecutor(new LoginCommand(this));
//getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
//getCommand("logout").setExecutor(new LogoutCommand(this));
//getCommand("unregister").setExecutor(new UnregisterCommand(this));
//getCommand("email").setExecutor(new EmailCommand(this));
//getCommand("captcha").setExecutor(new CaptchaCommand(this));
//getCommand("converter").setExecutor(new ConverterCommand(this));
// Purge on start if enabled
autoPurge();
@ -703,6 +721,10 @@ public class AuthMe extends JavaPlugin {
Settings.switchAntiBotMod(mode);
}
public boolean getAntiBotModMode() {
return this.antibotMod;
}
private void recallEmail() {
if (!Settings.recallEmail)
return;
@ -808,4 +830,52 @@ public class AuthMe extends JavaPlugin {
public String getCountryName(String ip) {
return Utils.getCountryName(ip);
}
/**
* Get the command handler instance.
*
* @return Command handler.
*/
public CommandHandler getCommandHandler() {
return this.commandHandler;
}
/**
* Handle Bukkit commands.
*
* @param sender The command sender (Bukkit).
* @param cmd The command (Bukkit).
* @param commandLabel The command label (Bukkit).
* @param args The command arguments (Bukkit).
*
* @return True if the command was executed, false otherwise.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
// Get the command handler, and make sure it's valid
CommandHandler commandHandler = this.getCommandHandler();
if(commandHandler == null)
return false;
// Handle the command, return the result
return commandHandler.onCommand(sender, cmd, commandLabel, args);
}
/**
* Get the current installed AuthMeReloaded version name.
*
* @return The version name of the currently installed AuthMeReloaded instance.
*/
public static String getVersionName() {
return PLUGIN_VERSION_NAME;
}
/**
* Get the current installed AuthMeReloaded version code.
*
* @return The version code of the currently installed AuthMeReloaded instance.
*/
public static int getVersionCode() {
return PLUGIN_VERSION_CODE;
}
}

View File

@ -112,10 +112,10 @@ public class SendMailSSL {
if (file != null)
file.delete();
} catch (RuntimeException e) {
ConsoleLogger.showError("Some error occured while trying to send a email to " + mail);
} catch (Exception e) {
ConsoleLogger.showError("Some error occured while trying to send a email to " + mail);
} catch(Exception e) {
// Print the stack trace
e.printStackTrace();
ConsoleLogger.showError("Some error occurred while trying to send a email to " + mail);
}
}

View File

@ -0,0 +1,91 @@
package fr.xephi.authme.command;
public class CommandArgumentDescription {
// TODO: Allow argument to consist of infinite parts. <label ...>
/** Argument label. */
private String label;
/** Argument description. */
private String description;
/** Defines whether the argument is optional. */
private boolean optional = false;
/**
* Constructor.
*
* @param label The argument label.
* @param description The argument description.
*/
@SuppressWarnings("UnusedDeclaration")
public CommandArgumentDescription(String label, String description) {
this(label, description, false);
}
/**
* Constructor.
*
* @param label The argument label.
* @param description The argument description.
* @param optional True if the argument is optional, false otherwise.
*/
public CommandArgumentDescription(String label, String description, boolean optional) {
setLabel(label);
setDescription(description);
setOptional(optional);
}
/**
* Get the argument label.
*
* @return Argument label.
*/
public String getLabel() {
return this.label;
}
/**
* Set the argument label.
*
* @param label Argument label.
*/
public void setLabel(String label) {
this.label = label;
}
/**
* Get the argument description.
*
* @return Argument description.
*/
public String getDescription() {
return description;
}
/**
* Set the argument description.
*
* @param description Argument description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Check whether the argument is optional.
*
* @return True if the argument is optional, false otherwise.
*/
public boolean isOptional() {
return optional;
}
/**
* Set whether the argument is optional.
*
* @param optional True if the argument is optional, false otherwise.
*/
public void setOptional(boolean optional) {
this.optional = optional;
}
}

View File

@ -0,0 +1,918 @@
package fr.xephi.authme.command;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
public class CommandDescription {
/** Defines the acceptable labels. */
private List<String> labels = new ArrayList<>();
/** Command description. */
private String description = "";
/** Detailed description. */
private String detailedDescription = "";
/** The executable command instance. */
private ExecutableCommand executableCommand;
/** The parent command. */
private CommandDescription parent = null;
/** The child labels. */
private List<CommandDescription> children = new ArrayList<>();
/** The command arguments. */
private List<CommandArgumentDescription> arguments = new ArrayList<>();
/** Defines whether there is an argument maximum or not. */
private boolean noArgumentMaximum = false;
/** Defines the command permissions. */
private CommandPermissions permissions = new CommandPermissions();
/**
* Constructor.
*
* @param executableCommand The executable command, or null.
* @param label Command label.
* @param description Command description.
* @param detailedDescription Detailed comment description.
* @param parent Parent command.
*/
public CommandDescription(ExecutableCommand executableCommand, String label, String description, String detailedDescription, CommandDescription parent) {
this(executableCommand, label, description, parent, detailedDescription, null);
}
/**
* Constructor.
*
* @param executableCommand The executable command, or null.
* @param labels List of command labels.
* @param description Command description.
* @param detailedDescription Detailed comment description.
* @param parent Parent command.
*/
public CommandDescription(ExecutableCommand executableCommand, List<String> labels, String description, String detailedDescription, CommandDescription parent) {
this(executableCommand, labels, description, detailedDescription, parent, null);
}
/**
* Constructor.
*
* @param executableCommand The executable command, or null.
* @param label Command label.
* @param description Command description.
* @param parent Parent command.
* @param detailedDescription Detailed comment description.
* @param arguments Command arguments.
*/
public CommandDescription(ExecutableCommand executableCommand, String label, String description, CommandDescription parent, String detailedDescription, List<CommandArgumentDescription> arguments) {
setExecutableCommand(executableCommand);
setLabel(label);
setDescription(description);
setDetailedDescription(detailedDescription);
setParent(parent);
setArguments(arguments);
}
/**
* Constructor.
*
* @param executableCommand The executable command, or null.
* @param labels List of command labels.
* @param description Command description.
* @param detailedDescription Detailed comment description.
* @param parent Parent command.
* @param arguments Command arguments.
*/
public CommandDescription(ExecutableCommand executableCommand, List<String> labels, String description, String detailedDescription, CommandDescription parent, List<CommandArgumentDescription> arguments) {
setExecutableCommand(executableCommand);
setLabels(labels);
setDescription(description);
setDetailedDescription(detailedDescription);
setParent(parent);
setArguments(arguments);
}
/**
* Get the first relative command label.
*
* @return First relative command label.
*/
public String getLabel() {
// Ensure there's any item in the command list
if(this.labels.size() == 0)
return "";
// Return the first command on the list
return this.labels.get(0);
}
/**
* Get the label most similar to the reference. The first label will be returned if no reference was supplied.
*
* @param reference The command reference.
*
* @return The most similar label, or the first label. An empty label will be returned if no label was set.
*/
public String getLabel(CommandParts reference) {
// Ensure there's any item in the command list
if(this.labels.size() == 0)
return "";
// Return the first label if we can't use the reference
if(reference == null)
return this.labels.get(0);
// Get the correct label from the reference
String preferred = reference.get(getParentCount());
// Check whether the preferred label is in the label list
double currentDifference = -1;
String currentLabel = this.labels.get(0);
for(String entry : this.labels) {
double entryDifference = StringUtils.getDifference(entry, preferred);
if(entryDifference < currentDifference || currentDifference < 0) {
currentDifference = entryDifference;
currentLabel = entry;
}
}
// Return the most similar label
return currentLabel;
}
/**
* Get all relative command labels.
*
* @return All relative labels labels.
*/
public List<String> getLabels() {
return this.labels;
}
/**
* Set the list of command labels.
*
* @param labels New list of command labels. Null to clear the list of labels.
*/
public void setLabels(List<String> labels) {
// Check whether the command label list should be cleared
if(labels == null)
this.labels.clear();
else
this.labels = labels;
}
/**
* Set the command label, this will append the command label to already existing ones.
*
* @param commandLabel Command label to set or add.
*/
public void setLabel(String commandLabel) {
setLabel(commandLabel, false);
}
/**
* Set the command label.
*
* @param commandLabel Command label to set.
* @param overwrite True to replace all old command labels, false to append this command label to the currently
* existing labels.
*
* @return Trie if the command label is added, or if it was added already. False on failure.
*/
public boolean setLabel(String commandLabel, boolean overwrite) {
// Check whether this new command should overwrite the previous ones
if(!overwrite)
return addLabel(commandLabel);
// Replace all labels with this new one
this.labels.clear();
return this.labels.add(commandLabel);
}
/**
* Add a command label to the list.
*
* @param commandLabel Command label to add.
*
* @return True if the label was added, or if it was added already. False on error.
*/
public boolean addLabel(String commandLabel) {
// Verify the label
if(!isValidLabel(commandLabel))
return false;
// Ensure this command isn't a duplicate
if(hasLabel(commandLabel))
return true;
// Add the command to the list
return this.labels.add(commandLabel);
}
/**
* Add a list of command labels.
*
* @param commandLabels List of command labels to add.
*
* @return True if succeed, false on failure.
*/
public boolean addLabels(List<String> commandLabels) {
// Add each command label separately
for(String cmd : commandLabels)
if(!addLabel(cmd))
return false;
return true;
}
/**
* Check whether this command description has a specific command.
*
* @param commandLabel Command to check for.
*
* @return True if this command label equals to the param command.
*/
public boolean hasLabel(String commandLabel) {
// Check whether any command matches with the argument
for(String entry : this.labels)
if(commandLabelEquals(entry, commandLabel))
return true;
// No match found, return false
return false;
}
/**
* Check whether this command description has a list of labels
* @param commandLabels List of labels
* @return True if all labels match, false otherwise
*/
public boolean hasLabels(List<String> commandLabels) {
// Check if there's a match for every command
for(String cmd : commandLabels)
if(!hasLabel(cmd))
return false;
// There seems to be a match for every command, return true
return true;
}
/**
* Check whether this command label is applicable with a command reference. This doesn't check if the parent
* are suitable too.
*
* @param commandReference The command reference.
*
* @return True if the command reference is suitable to this command label, false otherwise.
*/
public boolean isSuitableLabel(CommandParts commandReference) {
// Make sure the command reference is valid
if(commandReference.getCount() <= 0)
return false;
// Get the parent count
String element = commandReference.get(getParentCount());
// Check whether this command description has this command label
return hasLabel(element);
}
/**
* Check whether a label is valid to use.
*
* @param label The label to test.
*
* @return True if the label is valid to use, false otherwise.
*/
public static boolean isValidLabel(String label) {
// Make sure the label isn't null
if(label == null)
return false;
// Trim the label
label = label.trim();
// Make sure the label is at least one character long
if(label.length() <= 0)
return false;
// Make sure the label doesn't contain any spaces, return the result
return !label.contains(" ");
}
/**
* Get the absolute command label, without a slash.
*/
public String getAbsoluteLabel() {
return getAbsoluteLabel(false);
}
/**
* Get the absolute command label.
*
* @return Absolute command label.
*/
public String getAbsoluteLabel(boolean includeSlash) {
return getAbsoluteLabel(includeSlash, null);
}
/**
* Get the absolute command label.
*
* @return Absolute command label.
*/
public String getAbsoluteLabel(boolean includeSlash, CommandParts reference) {
// Get the command reference, and make sure it is valid
CommandParts out = getCommandReference(reference);
if(out == null)
return "";
// Return the result
return (includeSlash ? "/" : "") + out.toString();
}
/**
* Get the command reference.
*
* @param reference The reference to use as template, which is used to choose the most similar reference.
*
* @return Command reference.
*/
public CommandParts getCommandReference(CommandParts reference) {
// Build the reference
List<String> referenceList = new ArrayList<>();
// Check whether this command has a parent, if so, add the absolute parent command
if(getParent() != null)
referenceList.addAll(getParent().getCommandReference(reference).getList());
// Get the current label
referenceList.add(getLabel(reference));
// Return the reference
return new CommandParts(referenceList);
}
/**
* Get the difference between this command and another command reference.
*
* @param other The other command reference.
*
* @return The command difference. Zero if there's no difference. A negative number on error.
*/
public double getCommandDifference(CommandParts other) {
return getCommandDifference(other, false);
}
/**
* Get the difference between this command and another command reference.
*
* @param other The other command reference.
* @param fullCompare True to fully compare both command references.
*
* @return The command difference. Zero if there's no difference. A negative number on error.
*/
public double getCommandDifference(CommandParts other, boolean fullCompare) {
// Make sure the reference is valid
if(other == null)
return -1;
// Get the command reference
CommandParts reference = getCommandReference(other);
// Compare the two references, return the result
return reference.getDifference(new CommandParts(other.getRange(0, reference.getCount())), fullCompare);
}
/**
* Get the executable command.
*
* @return The executable command.
*/
public ExecutableCommand getExecutableCommand() {
return this.executableCommand;
}
/**
* Set the executable command.
*
* @param executableCommand The executable command.
*/
public void setExecutableCommand(ExecutableCommand executableCommand) {
this.executableCommand = executableCommand;
}
/**
* Check whether this command is executable, based on the assigned executable command.
*
* @return True if this command is executable.
*/
public boolean isExecutable() {
return this.executableCommand != null;
}
/**
* Execute the command, if possible.
*
* @param sender The command sender that triggered the execution of this command.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True on success, false on failure.
*/
public boolean execute(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Make sure the command is executable
if(!isExecutable())
return false;
// Execute the command, return the result
return getExecutableCommand().executeCommand(sender, commandReference, commandArguments);
}
/**
* Get the parent command if this command description has a parent.
*
* @return Parent command, or null
*/
public CommandDescription getParent() {
return this.parent;
}
/**
* Get the number of parent this description has.
*
* @return The number of parents.
*/
public int getParentCount() {
// Check whether the this description has a parent
if(!hasParent())
return 0;
// Get the parent count of the parent, return the result
return getParent().getParentCount() + 1;
}
/**
* Set the parent command.
*
* @param parent Parent command.
*
* @return True on success, false on failure.
*/
public boolean setParent(CommandDescription parent) {
// Make sure the parent is different
if(this.parent == parent)
return true;
// Set the parent
this.parent = parent;
// Make sure the parent isn't null
if(parent == null)
return true;
// Add this description as a child to the parent
return parent.addChild(this);
}
/**
* Check whether the plugin description has a parent command.
*
* @return True if the description has a parent command, false otherwise.
*/
public boolean hasParent() {
return this.parent != null;
}
/**
* Get all command children.
*
* @return Command children.
*/
public List<CommandDescription> getChildren() {
return this.children;
}
/**
* Add a child to the command description.
*
* @param commandDescription The child to add.
*
* @return True on success, false on failure.
*/
public boolean addChild(CommandDescription commandDescription) {
// Make sure the description is valid
if(commandDescription == null)
return false;
if(!commandDescription.isValid())
return false;
// Make sure the child doesn't exist already
if(isChild(commandDescription))
return true;
// The command description to add as a child
if(!this.children.add(commandDescription))
return false;
// Set this description as parent on the child
return commandDescription.setParent(this);
}
/**
* Set the children of this command.
*
* @param children New command children. Null to remove all children.
*/
public void setChildren(List<CommandDescription> children) {
// Check whether the children list should be cleared
if(children == null)
this.children.clear();
else
this.children = children;
}
/**
* Check whether this command has any child labels.
*
* @return True if this command has any child labels.
*/
public boolean hasChilds() {
return (this.children.size() != 0);
}
/**
* Check if this command description has a specific child.
*
* @param commandDescription The command description to check for.
*
* @return True if this command description has the specific child, false otherwise.
*/
public boolean isChild(CommandDescription commandDescription) {
// Make sure the description is valid
if(commandDescription == null)
return false;
if(!commandDescription.isValid())
return false;
// Check whether this child exists, return the result
return this.children.contains(commandDescription);
}
/**
* Add an argument.
*
* @param argument The argument to add.
*
* @return True if succeed, false if failed.
*/
public boolean addArgument(CommandArgumentDescription argument) {
// Make sure the argument is valid
if(argument == null)
return false;
// Make sure the argument isn't added already
if(hasArgument(argument))
return true;
// Add the argument, return the result
return this.arguments.add(argument);
}
/**
* Get all command arguments.
*
* @return Command arguments.
*/
public List<CommandArgumentDescription> getArguments() {
return this.arguments;
}
/**
* Set the arguments of this command.
*
* @param arguments New command arguments. Null to clear the list of arguments.
*/
public void setArguments(List<CommandArgumentDescription> arguments) {
// Convert null into an empty argument list
if(arguments == null)
this.arguments.clear();
else
this.arguments = arguments;
}
/**
* Check whether an argument exists.
*
* @param argument The argument to check for.
*
* @return True if this argument already exists, false otherwise.
*/
public boolean hasArgument(CommandArgumentDescription argument) {
// Make sure the argument is valid
if(argument == null)
return false;
// Check whether the argument exists, return the result
return this.arguments.contains(argument);
}
/**
* Check whether this command has any arguments.
*
* @return True if this command has any arguments.
*/
public boolean hasArguments() {
return (this.arguments.size() != 0);
}
/**
* The minimum number of arguments required for this command.
*
* @return The minimum number of required arguments.
*/
public int getMinimumArguments() {
// Get the number of required and optional arguments
int requiredArguments = 0;
int optionalArgument = 0;
// Loop through each argument
for(CommandArgumentDescription argument : this.arguments) {
// Check whether the command is optional
if(!argument.isOptional()) {
requiredArguments += optionalArgument + 1;
optionalArgument = 0;
} else
optionalArgument++;
}
// Return the number of required arguments
return requiredArguments;
}
/**
* Get the maximum number of arguments.
*
* @return The maximum number of arguments. A negative number will be returned if there's no maximum.
*/
public int getMaximumArguments() {
// Check whether there is a maximum set
if(this.noArgumentMaximum)
return -1;
// Return the maximum based on the registered arguments
return this.arguments.size();
}
/**
* Set whether there is an argument maximum.
*
* @param maximumArguments True if there is an argument maximum, based on the number of registered arguments.
*/
public void setMaximumArguments(boolean maximumArguments) {
this.noArgumentMaximum = !maximumArguments;
}
/**
* Get the command description.
*
* @return Command description.
*/
public String getDescription() {
return hasDescription() ? this.description : this.detailedDescription;
}
/**
* Set the command description.
*
* @param description New command description. Null to reset the description.
*/
public void setDescription(String description) {
if(description == null)
this.description = "";
else
this.description = description;
}
/**
* Check whether this command has any description.
*
* @return True if this command has any description.
*/
public boolean hasDescription() {
return (this.description.trim().length() != 0);
}
/**
* Get the command detailed description.
*
* @return Command detailed description.
*/
public String getDetailedDescription() {
return hasDetailedDescription() ? this.detailedDescription : this.description;
}
/**
* Set the command detailed description.
*
* @param detailedDescription New command description. Null to reset the description.
*/
public void setDetailedDescription(String detailedDescription) {
if(detailedDescription == null)
this.detailedDescription = "";
else
this.detailedDescription = detailedDescription;
}
/**
* Check whether this command has any detailed description.
*
* @return True if this command has any detailed description.
*/
public boolean hasDetailedDescription() {
return (this.detailedDescription.trim().length() != 0);
}
/**
* Find the best suitable command for a query reference.
*
* @param queryReference The query reference to find a command for.
*
* @return The command found, or null.
*/
public FoundCommandResult findCommand(final CommandParts queryReference) {
// Make sure the command reference is valid
if(queryReference.getCount() <= 0)
return null;
// Check whether this description is for the last element in the command reference, if so return the current command
if(queryReference.getCount() <= getParentCount() + 1)
return new FoundCommandResult(
this,
getCommandReference(queryReference),
new CommandParts(),
queryReference);
// Get the new command reference and arguments
CommandParts newReference = new CommandParts(queryReference.getRange(0, getParentCount() + 1));
CommandParts newArguments = new CommandParts(queryReference.getRange(getParentCount() + 1));
// Handle the child's, if this command has any
if(getChildren().size() > 0) {
// Get a new instance of the child's list, and sort them by their difference in comparison to the query reference
List<CommandDescription> commandChildren = new ArrayList<>(getChildren());
Collections.sort(commandChildren, new Comparator<CommandDescription>() {
@Override
public int compare(CommandDescription o1, CommandDescription o2) {
return Double.compare(
o1.getCommandDifference(queryReference),
o2.getCommandDifference(queryReference));
}
});
// Get the difference of the first child in the list
double firstChildDifference = commandChildren.get(0).getCommandDifference(queryReference, true);
// Check if the reference perfectly suits the arguments of the current command if it doesn't perfectly suits a child command
if(firstChildDifference > 0.0)
if(getSuitableArgumentsDifference(queryReference) == 0)
return new FoundCommandResult(this, newReference, newArguments, queryReference);
// Loop through each child
for(CommandDescription child : commandChildren) {
// Get the best suitable command
FoundCommandResult result = child.findCommand(queryReference);
if(result != null)
return result;
}
}
// Check if the remaining command reference elements fit the arguments for this command
if(getSuitableArgumentsDifference(queryReference) >= 0)
return new FoundCommandResult(this, newReference, newArguments, queryReference);
// No command found, return null
return null;
}
/**
* Check whether there's any command description that matches the specified command reference.
*
* @param commandReference The command reference.
*
* @return True if so, false otherwise.
*/
public boolean hasSuitableCommand(CommandParts commandReference) {
return findCommand(commandReference) != null;
}
/**
* Check if the remaining command reference elements are suitable with arguments of the current command description.
*
* @param commandReference The command reference.
*
* @return True if the arguments are suitable, false otherwise.
*/
public boolean hasSuitableArguments(CommandParts commandReference) {
return getSuitableArgumentsDifference(commandReference) == 0;
}
/**
* Check if the remaining command reference elements are suitable with arguments of the current command description,
* and get the difference in argument count.
*
* @param commandReference The command reference.
*
* @return The difference in argument count between the reference and the actual command.
*/
public int getSuitableArgumentsDifference(CommandParts commandReference) {
// Make sure the command reference is valid
if(commandReference.getCount() <= 0)
return -1;
// Get the remaining command reference element count
int remainingElementCount = commandReference.getCount() - getParentCount() - 1;
// Check if there are too less arguments
if(getMinimumArguments() > remainingElementCount)
return Math.abs(getMinimumArguments() - remainingElementCount);
// Check if there are too many arguments
if(getMaximumArguments() < remainingElementCount && getMaximumArguments() >= 0)
return Math.abs(remainingElementCount - getMaximumArguments());
// The arguments seem to be EQUALS, return the result
return 0;
}
/**
* Get the command permissions.
*
* @return The command permissions.
*/
public CommandPermissions getCommandPermissions() {
return this.permissions;
}
/**
* Set the command permissions.
*
* @param commandPermissions The command permissions.
*/
public void setCommandPermissions(CommandPermissions commandPermissions) {
this.permissions = commandPermissions;
}
/**
* Set the command permissions.
*
* @param permissionNode The permission node required.
* @param defaultPermission The default permission.
*/
public void setCommandPermissions(String permissionNode, CommandPermissions.DefaultPermission defaultPermission) {
this.permissions = new CommandPermissions(permissionNode, defaultPermission);
}
/**
* Check whether two labels equal to each other.
*
* @param commandLabel The first command label.
* @param otherCommandLabel The other command label.
*
* @return True if the labels are equal to each other.
*/
private static boolean commandLabelEquals(String commandLabel, String otherCommandLabel) {
// Trim the command labels from unwanted whitespaces
commandLabel = commandLabel.trim();
otherCommandLabel = otherCommandLabel.trim();
// Check whether the the two command labels are equal (case insensitive)
return (commandLabel.equalsIgnoreCase(otherCommandLabel));
}
/**
* Check whether the command description has been set up properly.
*
* @return True if the command description is valid, false otherwise.
*/
public boolean isValid() {
// Make sure any command label is set
if(getLabels().size() == 0)
return false;
// Make sure the permissions are set up properly
if(this.permissions == null)
return false;
// Everything seems to be correct, return the result
return true;
}
}

View File

@ -0,0 +1,207 @@
package fr.xephi.authme.command;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.help.HelpProvider;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CommandHandler {
/** The command manager instance. */
private CommandManager commandManager;
/**
* Constructor.
*
* @param init True to immediately initialize.
*/
public CommandHandler(boolean init) {
// Initialize
if(init)
init();
}
/**
* Initialize the command handler.
*
* @return True if succeed, false on failure. True will also be returned if the command handler was already
* initialized.
*/
public boolean init() {
// Make sure the handler isn't initialized already
if(isInit())
return true;
// Initialize the command manager
this.commandManager = new CommandManager(false);
this.commandManager.registerCommands();
// Return the result
return true;
}
/**
* Check whether the command handler is initialized.
*
* @return True if the command handler is initialized.
*/
public boolean isInit() {
return this.commandManager != null;
}
/**
* Destroy the command handler.
*
* @return True if the command handler was destroyed successfully, false otherwise. True will also be returned if
* the command handler wasn't initialized.
*/
public boolean destroy() {
// Make sure the command handler is initialized
if(!isInit())
return true;
// Unset the command manager
this.commandManager = null;
return true;
}
/**
* Get the command manager.
*
* @return Command manager instance.
*/
public CommandManager getCommandManager() {
return this.commandManager;
}
/**
* Process a command.
*
* @param sender The command sender (Bukkit).
* @param bukkitCommand The command (Bukkit).
* @param bukkitCommandLabel The command label (Bukkit).
* @param bukkitArgs The command arguments (Bukkit).
*
* @return True if the command was executed, false otherwise.
*/
@SuppressWarnings("unused")
public boolean onCommand(CommandSender sender, @SuppressWarnings("UnusedParameters") org.bukkit.command.Command bukkitCommand, String bukkitCommandLabel, String[] bukkitArgs) {
// Process the arguments
List<String> args = processArguments(bukkitArgs);
// Create a command reference, and make sure at least one command part is available
CommandParts commandReference = new CommandParts(bukkitCommandLabel, args);
if(commandReference.getCount() == 0)
return false;
// Get a suitable command for this reference, and make sure it isn't null
FoundCommandResult result = this.commandManager.findCommand(commandReference);
if(result == null) {
sender.sendMessage(ChatColor.DARK_RED + "Failed to parse " + AuthMe.PLUGIN_NAME + " command!");
return false;
}
// Get the base command
String baseCommand = commandReference.get(0);
// Make sure the difference between the command reference and the actual command isn't too big
final double commandDifference = result.getDifference();
if(commandDifference > 0.12) {
// Show the unknown command warning
sender.sendMessage(ChatColor.DARK_RED + "Unknown command!");
// Show a command suggestion if available and the difference isn't too big
if(commandDifference < 0.75)
if(result.getCommandDescription() != null)
sender.sendMessage(ChatColor.YELLOW + "Did you mean " + ChatColor.GOLD + "/" + result.getCommandDescription().getCommandReference(commandReference) + ChatColor.YELLOW + "?");
// Show the help command
sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help" + ChatColor.YELLOW + " to view help.");
return true;
}
// Show a message when the command handler is assuming a command
if(commandDifference > 0) {
// Get the suggested command
CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference));
// Show the suggested command
sender.sendMessage(ChatColor.DARK_RED + "Unknown command, assuming " + ChatColor.GOLD + "/" + suggestedCommandParts +
ChatColor.DARK_RED + "!");
}
// Make sure the command is executable
if(!result.isExecutable()) {
// Get the command reference
CommandParts helpCommandReference = new CommandParts(result.getCommandReference().getRange(1));
// Show the unknown command warning
sender.sendMessage(ChatColor.DARK_RED + "Invalid command!");
// Show the help command
sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help " + helpCommandReference + ChatColor.YELLOW + " to view help.");
return true;
}
// Make sure the command sender has permission
if(!result.hasPermission(sender)) {
// Show the no permissions warning
sender.sendMessage(ChatColor.DARK_RED + "You don't have permission to use this command!");
return true;
}
// Make sure the command sender has permission
if(!result.hasProperArguments()) {
// Get the command and the suggested command reference
CommandParts suggestedCommandReference = new CommandParts(result.getCommandDescription().getCommandReference(commandReference));
CommandParts helpCommandReference = new CommandParts(suggestedCommandReference.getRange(1));
// Show the invalid arguments warning
sender.sendMessage(ChatColor.DARK_RED + "Incorrect command arguments!");
// Show the command argument help
HelpProvider.showHelp(sender, commandReference, suggestedCommandReference, true, false, true, false, false, false);
// Show the command to use for detailed help
sender.sendMessage(ChatColor.GOLD + "Detailed help: " + ChatColor.WHITE + "/" + baseCommand + " help " + helpCommandReference);
return true;
}
// Execute the command if it's suitable
return result.executeCommand(sender);
}
/**
* Process the command arguments, and return them as an array list.
*
* @param args The command arguments to process.
*
* @return The processed command arguments.
*/
private List<String> processArguments(String[] args) {
// Convert the array into a list of arguments
List<String> arguments = new ArrayList<>(Arrays.asList(args));
/// Remove all empty arguments
for(int i = 0; i < arguments.size(); i++) {
// Get the argument value
final String arg = arguments.get(i);
// Check whether the argument value is empty
if(arg.trim().length() == 0) {
// Remove the current argument
arguments.remove(i);
// Decrease the index by one, continue to the next argument
i--;
}
}
// Return the argument
return arguments;
}
}

View File

@ -0,0 +1,667 @@
package fr.xephi.authme.command;
import fr.xephi.authme.command.executable.*;
import fr.xephi.authme.command.executable.authme.*;
import fr.xephi.authme.command.executable.authme.ChangePasswordCommand;
import fr.xephi.authme.command.executable.authme.RegisterCommand;
import fr.xephi.authme.command.executable.authme.UnregisterCommand;
import fr.xephi.authme.command.executable.captcha.CaptchaCommand;
import fr.xephi.authme.command.executable.converter.ConverterCommand;
import fr.xephi.authme.command.executable.email.AddEmailCommand;
import fr.xephi.authme.command.executable.email.ChangeEmailCommand;
import fr.xephi.authme.command.executable.email.RecoverEmailCommand;
import fr.xephi.authme.command.executable.login.LoginCommand;
import fr.xephi.authme.command.executable.logout.LogoutCommand;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
public class CommandManager {
/** The list of commandDescriptions. */
private List<CommandDescription> commandDescriptions = new ArrayList<>();
/**
* Constructor.
*
* @param registerCommands True to register the commands, false otherwise.
*/
public CommandManager(boolean registerCommands) {
// Register the commands
if(registerCommands)
registerCommands();
}
/**
* Register all commands.
*/
@SuppressWarnings("SpellCheckingInspection")
public void registerCommands() {
// Register the base AuthMe Reloaded command
CommandDescription authMeBaseCommand = new CommandDescription(
new AuthMeCommand(),
new ArrayList<String>() {{
add("authme");
}},
"Main command",
"The main AuthMeReloaded command. The root for all admin commands.", null);
// Register the help command
CommandDescription authMeHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded commands.",
authMeBaseCommand);
authMeHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
authMeHelpCommand.setMaximumArguments(false);
// Register the register command
CommandDescription registerCommand = new CommandDescription(
new RegisterCommand(),
new ArrayList<String>() {{
add("register");
add("reg");
add("r");
}},
"Register a player",
"Register the specified player with the specified password.",
authMeBaseCommand);
registerCommand.setCommandPermissions("authme.admin.register", CommandPermissions.DefaultPermission.OP_ONLY);
registerCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
registerCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
// Register the unregister command
CommandDescription unregisterCommand = new CommandDescription(
new UnregisterCommand(),
new ArrayList<String>() {{
add("unregister");
add("unreg");
add("unr");
add("delete");
add("del");
}},
"Unregister a player",
"Unregister the specified player.",
authMeBaseCommand);
unregisterCommand.setCommandPermissions("authme.admin.unregister", CommandPermissions.DefaultPermission.OP_ONLY);
unregisterCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
// Register the forcelogin command
CommandDescription forceLoginCommand = new CommandDescription(
new ForceLoginCommand(),
new ArrayList<String>() {{
add("forcelogin");
add("login");
}},
"Enforce login player",
"Enforce the specified player to login.",
authMeBaseCommand);
forceLoginCommand.setCommandPermissions("authme.admin.forcelogin", CommandPermissions.DefaultPermission.OP_ONLY);
forceLoginCommand.addArgument(new CommandArgumentDescription("player", "Online player name", true));
// Register the changepassword command
CommandDescription changePasswordCommand = new CommandDescription(
new ChangePasswordCommand(),
new ArrayList<String>() {{
add("password");
add("changepassword");
add("changepass");
add("cp");
}},
"Change player's password",
"Change the password of a player.",
authMeBaseCommand);
changePasswordCommand.setCommandPermissions("authme.admin.changepassword", CommandPermissions.DefaultPermission.OP_ONLY);
changePasswordCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
changePasswordCommand.addArgument(new CommandArgumentDescription("pwd", "New password", false));
// Register the purge command
CommandDescription lastLoginCommand = new CommandDescription(
new LastLoginCommand(),
new ArrayList<String>() {{
add("lastlogin");
add("ll");
}},
"Player's last login",
"View the date of the specified players last login",
authMeBaseCommand);
lastLoginCommand.setCommandPermissions("authme.admin.lastlogin", CommandPermissions.DefaultPermission.OP_ONLY);
lastLoginCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
// Register the accounts command
CommandDescription accountsCommand = new CommandDescription(
new AccountsCommand(),
new ArrayList<String>() {{
add("accounts");
add("account");
}},
"Display player accounts",
"Display all accounts of a player by it's player name or IP.",
authMeBaseCommand);
accountsCommand.setCommandPermissions("authme.admin.accounts", CommandPermissions.DefaultPermission.OP_ONLY);
accountsCommand.addArgument(new CommandArgumentDescription("player", "Player name or IP", true));
// Register the getemail command
CommandDescription getEmailCommand = new CommandDescription(
new GetEmailCommand(),
new ArrayList<String>() {{
add("getemail");
add("getmail");
add("email");
add("mail");
}},
"Display player's email",
"Display the email address of the specified player if set.",
authMeBaseCommand);
getEmailCommand.setCommandPermissions("authme.admin.getemail", CommandPermissions.DefaultPermission.OP_ONLY);
getEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
// Register the setemail command
CommandDescription setEmailCommand = new CommandDescription(
new SetEmailCommand(),
new ArrayList<String>() {{
add("chgemail");
add("chgmail");
add("setemail");
add("setmail");
}},
"Change player's email",
"Change the email address of the specified player.",
authMeBaseCommand);
setEmailCommand.setCommandPermissions("authme.admin.chgemail", CommandPermissions.DefaultPermission.OP_ONLY);
setEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
setEmailCommand.addArgument(new CommandArgumentDescription("email", "Player email", false));
// Register the getip command
CommandDescription getIpCommand = new CommandDescription(
new GetIpCommand(),
new ArrayList<String>() {{
add("getip");
add("ip");
}},
"Get player's IP",
"Get the IP address of the specified online player.",
authMeBaseCommand);
getIpCommand.setCommandPermissions("authme.admin.getip", CommandPermissions.DefaultPermission.OP_ONLY);
getIpCommand.addArgument(new CommandArgumentDescription("player", "Online player name", true));
// Register the spawn command
CommandDescription spawnCommand = new CommandDescription(
new SpawnCommand(),
new ArrayList<String>() {{
add("spawn");
add("home");
}},
"Teleport to spawn",
"Teleport to the spawn.",
authMeBaseCommand);
spawnCommand.setCommandPermissions("authme.admin.spawn", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the setspawn command
CommandDescription setSpawnCommand = new CommandDescription(
new SetSpawnCommand(),
new ArrayList<String>() {{
add("setspawn");
add("chgspawn");
}},
"Change the spawn",
"Change the player's spawn to your current position.",
authMeBaseCommand);
setSpawnCommand.setCommandPermissions("authme.admin.setspawn", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the firstspawn command
CommandDescription firstSpawnCommand = new CommandDescription(
new FirstSpawnCommand(),
new ArrayList<String>() {{
add("firstspawn");
add("firsthome");
}},
"Teleport to first spawn",
"Teleport to the first spawn.",
authMeBaseCommand);
firstSpawnCommand.setCommandPermissions("authme.admin.firstspawn", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the setfirstspawn command
CommandDescription setFirstSpawnCommand = new CommandDescription(
new SetFirstSpawnCommand(),
new ArrayList<String>() {{
add("setfirstspawn");
add("chgfirstspawn");
}},
"Change the first spawn",
"Change the first player's spawn to your current position.",
authMeBaseCommand);
setFirstSpawnCommand.setCommandPermissions("authme.admin.setfirstspawn", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the purge command
CommandDescription purgeCommand = new CommandDescription(
new PurgeCommand(),
new ArrayList<String>() {{
add("purge");
add("delete");
}},
"Purge old data",
"Purge old AuthMeReloaded data longer than the specified amount of days ago.",
authMeBaseCommand);
purgeCommand.setCommandPermissions("authme.admin.purge", CommandPermissions.DefaultPermission.OP_ONLY);
purgeCommand.addArgument(new CommandArgumentDescription("days", "Number of days", false));
// Register the purgelastposition command
CommandDescription purgeLastPositionCommand = new CommandDescription(
new PurgeLastPositionCommand(),
new ArrayList<String>() {{
add("resetpos");
add("purgelastposition");
add("purgelastpos");
add("resetposition");
add("resetlastposition");
add("resetlastpos");
}},
"Purge player's last position",
"Purge the last know position of the specified player.",
authMeBaseCommand);
purgeLastPositionCommand.setCommandPermissions("authme.admin.purgelastpos", CommandPermissions.DefaultPermission.OP_ONLY);
purgeLastPositionCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
// Register the purgebannedplayers command
CommandDescription purgeBannedPlayersCommand = new CommandDescription(
new PurgeBannedPlayersCommand(),
new ArrayList<String>() {{
add("purgebannedplayers");
add("purgebannedplayer");
add("deletebannedplayers");
add("deletebannedplayer");
}},
"Purge banned palyers data",
"Purge all AuthMeReloaded data for banned players.",
authMeBaseCommand);
purgeBannedPlayersCommand.setCommandPermissions("authme.admin.purgebannedplayers", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the switchantibot command
CommandDescription switchAntiBotCommand = new CommandDescription(
new SwitchAntiBotCommand(),
new ArrayList<String>() {{
add("switchantibot");
add("toggleantibot");
add("antibot");
}},
"Switch AntiBot mode",
"Switch or toggle the AntiBot mode to the specified state.",
authMeBaseCommand);
switchAntiBotCommand.setCommandPermissions("authme.admin.switchantibot", CommandPermissions.DefaultPermission.OP_ONLY);
switchAntiBotCommand.addArgument(new CommandArgumentDescription("mode", "ON / OFF", true));
// // Register the resetname command
// CommandDescription resetNameCommand = new CommandDescription(
// new ResetNameCommand(),
// new ArrayList<String>() {{
// add("resetname");
// add("resetnames");
// }},
// "Reset name",
// "Reset name",
// authMeCommand);
// resetNameCommand.setCommandPermissions("authme.admin.resetname", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the reload command
CommandDescription reloadCommand = new CommandDescription(
new ReloadCommand(),
new ArrayList<String>() {{
add("reload");
add("rld");
}},
"Reload plugin",
"Reload the AuthMeReloaded plugin.",
authMeBaseCommand);
reloadCommand.setCommandPermissions("authme.admin.reload", CommandPermissions.DefaultPermission.OP_ONLY);
// Register the version command
CommandDescription versionCommand = new CommandDescription(
new VersionCommand(),
new ArrayList<String>() {{
add("version");
add("ver");
add("v");
add("about");
add("info");
}},
"Version info",
"Show detailed information about the installed AuthMeReloaded version, and shows the developers, contributors, license and other information.",
authMeBaseCommand);
versionCommand.setMaximumArguments(false);
// Register the base Dungeon Maze command
CommandDescription loginBaseCommand = new CommandDescription(
new LoginCommand(),
new ArrayList<String>() {{
add("login");
}},
"Login command",
"Command to login using AuthMeReloaded.", null);
loginBaseCommand.setCommandPermissions("authme.login", CommandPermissions.DefaultPermission.ALLOWED);
loginBaseCommand.addArgument(new CommandArgumentDescription("password", "Login password", false));
// Register the help command
CommandDescription loginHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded login commands.",
loginBaseCommand);
loginHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
loginHelpCommand.setMaximumArguments(false);
// Register the base logout command
CommandDescription logoutBaseCommand = new CommandDescription(
new LogoutCommand(),
new ArrayList<String>() {{
add("logout");
}},
"Logout command",
"Command to logout using AuthMeReloaded.", null);
logoutBaseCommand.setCommandPermissions("authme.logout", CommandPermissions.DefaultPermission.ALLOWED);
// Register the help command
CommandDescription logoutHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded logout commands.",
logoutBaseCommand);
logoutHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
logoutHelpCommand.setMaximumArguments(false);
// Register the base register command
CommandDescription registerBaseCommand = new CommandDescription(
new fr.xephi.authme.command.executable.register.RegisterCommand(),
new ArrayList<String>() {{
add("register");
add("reg");
}},
"Registration command",
"Command to register using AuthMeReloaded.", null);
registerBaseCommand.setCommandPermissions("authme.register", CommandPermissions.DefaultPermission.ALLOWED);
registerBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
registerBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false));
registerBaseCommand.setMaximumArguments(false);
// Register the help command
CommandDescription registerHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded register commands.",
registerBaseCommand);
registerHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
registerHelpCommand.setMaximumArguments(false);
// Register the base unregister command
CommandDescription unregisterBaseCommand = new CommandDescription(
new fr.xephi.authme.command.executable.unregister.UnregisterCommand(),
new ArrayList<String>() {{
add("unregister");
add("unreg");
}},
"Unregistration command",
"Command to unregister using AuthMeReloaded.", null);
unregisterBaseCommand.setCommandPermissions("authme.unregister", CommandPermissions.DefaultPermission.ALLOWED);
unregisterBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
// Register the help command
CommandDescription unregisterHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded unregister commands.",
unregisterBaseCommand);
unregisterHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
unregisterHelpCommand.setMaximumArguments(false);
// Register the base changepassword command
CommandDescription changePasswordBaseCommand = new CommandDescription(
new fr.xephi.authme.command.executable.changepassword.ChangePasswordCommand(),
new ArrayList<String>() {{
add("changepassword");
add("changepass");
}},
"Change password command",
"Command to change your password using AuthMeReloaded.", null);
changePasswordBaseCommand.setCommandPermissions("authme.changepassword", CommandPermissions.DefaultPermission.ALLOWED);
changePasswordBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
changePasswordBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false));
changePasswordBaseCommand.setMaximumArguments(false);
// Register the help command
CommandDescription changePasswordHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded change password commands.",
changePasswordBaseCommand);
changePasswordHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
changePasswordHelpCommand.setMaximumArguments(false);
// Register the base Dungeon Maze command
CommandDescription emailBaseCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("email");
add("mail");
}},
"E-mail command",
"The AuthMe Reloaded E-mail command. The root for all E-mail commands.", null);
// Register the help command
CommandDescription emailHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded help commands.",
emailBaseCommand);
emailHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
emailHelpCommand.setMaximumArguments(false);
// Register the add command
CommandDescription addEmailCommand = new CommandDescription(
new AddEmailCommand(),
new ArrayList<String>() {{
add("add");
add("addemail");
add("addmail");
}},
"Add E-mail",
"Add an new E-Mail address to your account.",
emailBaseCommand);
addEmailCommand.setCommandPermissions("authme.email.add", CommandPermissions.DefaultPermission.ALLOWED);
addEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false));
addEmailCommand.addArgument(new CommandArgumentDescription("verifyEmail", "Email address verification", false));
// Register the change command
CommandDescription changeEmailCommand = new CommandDescription(
new ChangeEmailCommand(),
new ArrayList<String>() {{
add("change");
add("changeemail");
add("changemail");
}},
"Change E-mail",
"Change an E-Mail address of your account.",
emailBaseCommand);
changeEmailCommand.setCommandPermissions("authme.email.change", CommandPermissions.DefaultPermission.ALLOWED);
changeEmailCommand.addArgument(new CommandArgumentDescription("oldEmail", "Old email address", false));
changeEmailCommand.addArgument(new CommandArgumentDescription("newEmail", "New email address", false));
// Register the recover command
CommandDescription recoverEmailCommand = new CommandDescription(
new RecoverEmailCommand(),
new ArrayList<String>() {{
add("recover");
add("recovery");
add("recoveremail");
add("recovermail");
}},
"Recover using E-mail",
"Recover your account using an E-mail address.",
emailBaseCommand);
recoverEmailCommand.setCommandPermissions("authme.email.recover", CommandPermissions.DefaultPermission.ALLOWED);
recoverEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false));
// Register the base captcha command
CommandDescription captchaBaseCommand = new CommandDescription(
new CaptchaCommand(),
new ArrayList<String>() {{
add("captcha");
add("capt");
}},
"Captcha command",
"Captcha command for AuthMeReloaded.", null);
captchaBaseCommand.setCommandPermissions("authme.captcha", CommandPermissions.DefaultPermission.ALLOWED);
captchaBaseCommand.addArgument(new CommandArgumentDescription("captcha", "The captcha", false));
captchaBaseCommand.setMaximumArguments(false);
// Register the help command
CommandDescription captchaHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded change captcha commands.",
captchaBaseCommand);
captchaHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
captchaHelpCommand.setMaximumArguments(false);
// Register the base converter command
CommandDescription converterBaseCommand = new CommandDescription(
new ConverterCommand(),
new ArrayList<String>() {{
add("converter");
add("convert");
add("conv");
}},
"Convert command",
"Convert command for AuthMeReloaded.", null);
converterBaseCommand.setCommandPermissions("authme.converter", CommandPermissions.DefaultPermission.OP_ONLY);
converterBaseCommand.addArgument(new CommandArgumentDescription("job", "Conversion job: flattosql / flattosqlite /| xauth / crazylogin / rakamak / royalauth / vauth / sqltoflat", false));
converterBaseCommand.setMaximumArguments(false);
// Register the help command
CommandDescription converterHelpCommand = new CommandDescription(
new HelpCommand(),
new ArrayList<String>() {{
add("help");
add("hlp");
add("h");
add("sos");
add("?");
}},
"View help",
"View detailed help pages about AuthMeReloaded change captcha commands.",
converterBaseCommand);
converterHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
converterHelpCommand.setMaximumArguments(false);
// Add the base commands to the commands array
this.commandDescriptions.add(authMeBaseCommand);
this.commandDescriptions.add(loginBaseCommand);
this.commandDescriptions.add(logoutBaseCommand);
this.commandDescriptions.add(registerBaseCommand);
this.commandDescriptions.add(unregisterBaseCommand);
this.commandDescriptions.add(changePasswordBaseCommand);
this.commandDescriptions.add(emailBaseCommand);
this.commandDescriptions.add(captchaBaseCommand);
this.commandDescriptions.add(converterBaseCommand);
}
/**
* Get the list of command descriptions
*
* @return List of command descriptions.
*/
public List<CommandDescription> getCommandDescriptions() {
return this.commandDescriptions;
}
/**
* Get the number of command description count.
*
* @return Command description count.
*/
public int getCommandDescriptionCount() {
return this.getCommandDescriptions().size();
}
/**
* Find the best suitable command for the specified reference.
*
* @param queryReference The query reference to find a command for.
*
* @return The command found, or null.
*/
public FoundCommandResult findCommand(CommandParts queryReference) {
// Make sure the command reference is valid
if(queryReference.getCount() <= 0)
return null;
// Get the base command description
for(CommandDescription commandDescription : this.commandDescriptions) {
// Check whether there's a command description available for the current command
if(!commandDescription.isSuitableLabel(queryReference))
continue;
// Find the command reference, return the result
return commandDescription.findCommand(queryReference);
}
// No applicable command description found, return false
return null;
}
}

View File

@ -0,0 +1,204 @@
package fr.xephi.authme.command;
import fr.xephi.authme.util.ListUtils;
import fr.xephi.authme.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class CommandParts {
/** The list of parts for this command. */
private List<String> parts = new ArrayList<>();
/**
* Constructor.
*/
public CommandParts() { }
/**
* Constructor.
*
* @param part The part to add.
*/
public CommandParts(String part) {
this.parts.add(part);
}
/**
* Constructor.
*
* @param commandParts The command parts instance.
*/
public CommandParts(CommandParts commandParts) {
this.parts.addAll(commandParts.getList());
}
/**
* Constructor.
*
* @param parts The list of parts.
*/
public CommandParts(List<String> parts) {
this.parts.addAll(parts);
}
/**
* Constructor.
*
* @param base The base part.
* @param parts The list of additional parts.
*/
public CommandParts(String base, List<String> parts) {
this.parts.add(base);
this.parts.addAll(parts);
}
/**
* Get the command parts.
*
* @return Command parts.
*/
public List<String> getList() {
return this.parts;
}
/**
* Add a part.
*
* @param part The part to add.
*
* @return The result.
*/
public boolean add(String part) {
return this.parts.add(part);
}
/**
* Add some parts.
*
* @param parts The parts to add.
*
* @return The result.
*/
public boolean add(List<String> parts) {
return this.parts.addAll(parts);
}
/**
* Add some parts.
*
* @param parts The parts to add.
*
* @return The result.
*/
public boolean add(String[] parts) {
for(String entry : parts)
add(entry);
return true;
}
/**
* Get the number of parts.
*
* @return Part count.
*/
public int getCount() {
return this.parts.size();
}
/**
* Get a part by it's index.
*
* @param i Part index.
*
* @return The part.
*/
public String get(int i) {
// Make sure the index is in-bound
if(i < 0 || i >= getCount())
return null;
// Get and return the argument
return this.parts.get(i);
}
/**
* Get a range of the parts starting at the specified index up to the end of the range.
*
* @param start The starting index.
*
* @return The parts range. Arguments that were out of bound are not included.
*/
public List<String> getRange(int start) {
return getRange(start, getCount() - start);
}
/**
* Get a range of the parts.
*
* @param start The starting index.
* @param count The number of parts to get.
*
* @return The parts range. Parts that were out of bound are not included.
*/
public List<String> getRange(int start, int count) {
// Create a new list to put the range into
List<String> elements = new ArrayList<>();
// Get the range
for(int i = start; i < start + count; i++) {
// Get the part and add it if it's valid
String element = get(i);
if(element != null)
elements.add(element);
}
// Return the list of parts
return elements;
}
/**
* Get the difference value between two references. This won't do a full compare, just the last reference parts instead.
*
* @param other The other reference.
*
* @return The result from zero to above. A negative number will be returned on error.
*/
@SuppressWarnings("UnusedDeclaration")
public double getDifference(CommandParts other) {
return getDifference(other, false);
}
/**
* Get the difference value between two references.
*
* @param other The other reference.
* @param fullCompare True to compare the full references as far as the range reaches.
*
* @return The result from zero to above. A negative number will be returned on error.
*/
public double getDifference(CommandParts other, boolean fullCompare) {
// Make sure the other reference is correct
if(other == null)
return -1;
// Get the range to use
int range = Math.min(this.getCount(), other.getCount());
// Get and the difference
if(fullCompare)
return StringUtils.getDifference(this.toString(), other.toString());
return StringUtils.getDifference(this.getRange(range - 1, 1).toString(), other.getRange(range - 1, 1).toString());
}
/**
* Convert the parts to a string.
*
* @return The part as a string.
*/
@Override
public String toString() {
return ListUtils.implode(this.parts, " ");
}
}

View File

@ -0,0 +1,183 @@
package fr.xephi.authme.command;
//import com.timvisee.dungeonmaze.Core;
//import com.timvisee.dungeonmaze.permission.PermissionsManager;
import fr.xephi.authme.AuthMe;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
public class CommandPermissions {
/** Defines the permission nodes required to have permission to execute this command. */
private List<String> permissionNodes = new ArrayList<>();
/** Defines the default permission if the permission nodes couldn't be used. */
private DefaultPermission defaultPermission = DefaultPermission.NOT_ALLOWED;
/**
* Constructor.
*/
public CommandPermissions() { }
/**
* Constructor.
*
* @param permissionNode The permission node required to execute a command.
* @param defaultPermission The default permission if the permission nodes couldn't be used.
*/
public CommandPermissions(String permissionNode, DefaultPermission defaultPermission) {
this.permissionNodes.add(permissionNode);
this.defaultPermission = defaultPermission;
}
/**
* Constructor.
*
* @param permissionNodes The permission nodes required to execute a command.
* @param defaultPermission The default permission if the permission nodes couldn't be used.
*/
public CommandPermissions(List<String> permissionNodes, DefaultPermission defaultPermission) {
this.permissionNodes.addAll(permissionNodes);
}
/**
* Add a permission node required to execute this command.
*
* @param permissionNode The permission node to add.
*
* @return True on success, false on failure.
*/
public boolean addPermissionNode(String permissionNode) {
// Trim the permission node
permissionNode = permissionNode.trim();
// Make sure the permission node is valid
if(permissionNode.length() == 0)
return false;
// Make sure this permission node hasn't been added already
if(hasPermissionNode(permissionNode))
return true;
// Add the permission node, return the result
return this.permissionNodes.add(permissionNode);
}
/**
* Check whether this command requires a specified permission node to execute.
*
* @param permissionNode The permission node to check for.
*
* @return True if this permission node is required, false if not.
*/
public boolean hasPermissionNode(String permissionNode) {
return this.permissionNodes.contains(permissionNode);
}
/**
* Get the permission nodes required to execute this command.
*
* @return The permission nodes required to execute this command.
*/
public List<String> getPermissionNodes() {
return this.permissionNodes;
}
/**
* Get the number of permission nodes set.
*
* @return Permission node count.
*/
public int getPermissionNodeCount() {
return this.permissionNodes.size();
}
/**
* Set the permission nodes required to execute this command.
*
* @param permissionNodes The permission nodes required to execute this command.
*/
public void setPermissionNodes(List<String> permissionNodes) {
this.permissionNodes = permissionNodes;
}
/**
* Check whether this command requires any permission to be executed. This is based on the getPermission() method.
*
* @return True if this command requires any permission to be executed by a player.
*/
public boolean hasPermission(CommandSender sender) {
// Make sure any permission node is set
if(getPermissionNodeCount() == 0)
return true;
// Get the default permission
final boolean defaultPermission = getDefaultPermissionCommandSender(sender);
// Make sure the command sender is a player, if not use the default
if(!(sender instanceof Player))
return defaultPermission;
// Get the player instance
Player player = (Player) sender;
// // Get the permissions manager, and make sure it's instance is valid
// PermissionsManager permissionsManager = Core.getPermissionsManager();
// if(permissionsManager == null)
// return false;
// Check whether the player has permission, return the result
for(String node : this.permissionNodes)
if(!AuthMe.getInstance().authmePermissible(player, node))
return false;
return true;
}
/**
* Get the default permission if the permission nodes couldn't be used.
*
* @return The default permission.
*/
public DefaultPermission getDefaultPermission() {
return this.defaultPermission;
}
/**
* Set the default permission used if the permission nodes couldn't be used.
*
* @param defaultPermission The default permission.
*/
public void setDefaultPermission(DefaultPermission defaultPermission) {
this.defaultPermission = defaultPermission;
}
/**
* Get the default permission for a specified command sender.
*
* @param sender The command sender to get the default permission for.
*
* @return True if the command sender has permission by default, false otherwise.
*/
public boolean getDefaultPermissionCommandSender(CommandSender sender) {
switch(getDefaultPermission()) {
case ALLOWED:
return true;
case OP_ONLY:
return sender.isOp();
case NOT_ALLOWED:
default:
return false;
}
}
public enum DefaultPermission {
NOT_ALLOWED,
OP_ONLY,
ALLOWED
}
}

View File

@ -0,0 +1,17 @@
package fr.xephi.authme.command;
import org.bukkit.command.CommandSender;
public abstract class ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
public abstract boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments);
}

View File

@ -0,0 +1,151 @@
package fr.xephi.authme.command;
import org.bukkit.command.CommandSender;
public class FoundCommandResult {
/** The command description instance. */
private CommandDescription commandDescription;
/** The command reference. */
private CommandParts commandReference;
/** The command arguments. */
private CommandParts commandArguments;
/** The original search query reference. */
private CommandParts queryReference;
/**
* Constructor.
*
* @param commandDescription The command description.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
* @param queryReference The original query reference.
*/
public FoundCommandResult(CommandDescription commandDescription, CommandParts commandReference, CommandParts commandArguments, CommandParts queryReference) {
this.commandDescription = commandDescription;
this.commandReference = commandReference;
this.commandArguments = commandArguments;
this.queryReference = queryReference;
}
/**
* Check whether the command was suitable.
*
* @return True if the command was suitable, false otherwise.
*/
public boolean hasProperArguments() {
// Make sure the command description is set
if(this.commandDescription == null)
return false;
// Get and return the result
return getCommandDescription().getSuitableArgumentsDifference(this.queryReference) == 0;
}
/**
* Get the command description.
*
* @return Command description.
*/
public CommandDescription getCommandDescription() {
return this.commandDescription;
}
/**
* Set the command description.
*
* @param commandDescription The command description.
*
*/
@SuppressWarnings("UnusedDeclaration")
public void setCommandDescription(CommandDescription commandDescription) {
this.commandDescription = commandDescription;
}
/**
* Check whether the command is executable.
*
* @return True if the command is executable, false otherwise.
*/
public boolean isExecutable() {
// Make sure the command description is valid
if(this.commandDescription == null)
return false;
// Check whether the command is executable, return the result
return this.commandDescription.isExecutable();
}
/**
* Execute the command.
*
* @param sender The command sender that executed the command.
*
* @return True on success, false on failure.
*/
public boolean executeCommand(CommandSender sender) {
// Make sure the command description is valid
if(this.commandDescription == null)
return false;
// Execute the command
return this.commandDescription.execute(sender, this.commandReference, this.commandArguments);
}
/**
* Check whether a command sender has permission to execute the command.
*
* @param sender The command sender.
*
* @return True if the command sender has permission, false otherwise.
*/
public boolean hasPermission(CommandSender sender) {
// Make sure the command description is valid
if(this.commandDescription == null)
return false;
// Get and return the permission
return this.commandDescription.getCommandPermissions().hasPermission(sender);
}
/**
* Get the command reference.
*
* @return The command reference.
*/
public CommandParts getCommandReference() {
return this.commandReference;
}
/**
* Get the command arguments.
*
* @return The command arguments.
*/
public CommandParts getCommandArguments() {
return this.commandArguments;
}
/**
* Get the original query reference.
*
* @return Original query reference.
*/
public CommandParts getQueryReference() {
return this.queryReference;
}
/**
* Get the difference value between the original query and the result reference.
*
* @return The difference value.
*/
public double getDifference() {
// Get the difference through the command found
if(this.commandDescription != null)
return this.commandDescription.getCommandDifference(this.queryReference);
// Get the difference from the query reference
return this.queryReference.getDifference(commandReference, true);
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.command.executable;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.command.help.HelpProvider;
import org.bukkit.command.CommandSender;
public class HelpCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Check whether quick help should be shown
boolean quickHelp = commandArguments.getCount() == 0;
// Set the proper command arguments for the quick help
if(quickHelp)
commandArguments = new CommandParts(commandReference.get(0));
// Show the new help
if(quickHelp)
HelpProvider.showHelp(sender, commandReference, commandArguments, false, false, false, false, false, true);
else
HelpProvider.showHelp(sender, commandReference, commandArguments);
// Return the result
return true;
}
}

View File

@ -0,0 +1,111 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.List;
public class AccountsCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the player query
String playerQuery = sender.getName();
if(commandArguments.getCount() >= 1)
playerQuery = commandArguments.get(0);
final String playerQueryFinal = playerQuery;
// Command logic
if (!playerQuery.contains(".")) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
PlayerAuth auth;
StringBuilder message = new StringBuilder("[AuthMe] ");
try {
auth = plugin.database.getAuth(playerQueryFinal.toLowerCase());
} catch (NullPointerException npe) {
m.send(sender, "unknown_user");
return;
}
if (auth == null) {
m.send(sender, "unknown_user");
return;
}
List<String> accountList = plugin.database.getAllAuthsByName(auth);
if (accountList == null || accountList.isEmpty()) {
m.send(sender, "user_unknown");
return;
}
if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + playerQueryFinal + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message.append(account);
if (i != accountList.size()) {
message.append(", ");
} else {
message.append(".");
}
}
sender.sendMessage("[AuthMe] " + playerQueryFinal + " has " + String.valueOf(accountList.size()) + " accounts");
sender.sendMessage(message.toString());
}
});
return true;
} else {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
StringBuilder message = new StringBuilder("[AuthMe] ");
List<String> accountList = plugin.database.getAllAuthsByIp(playerQueryFinal);
if (accountList == null || accountList.isEmpty()) {
sender.sendMessage("[AuthMe] This IP does not exist in the database");
return;
}
if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + playerQueryFinal + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
message.append(account);
if (i != accountList.size()) {
message.append(", ");
} else {
message.append(".");
}
}
sender.sendMessage("[AuthMe] " + playerQueryFinal + " has " + String.valueOf(accountList.size()) + " accounts");
sender.sendMessage(message.toString());
}
});
return true;
}
}
}

View File

@ -0,0 +1,29 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class AuthMeCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Show some version info
// TODO: Use plugin name and version constants here!
sender.sendMessage(ChatColor.GREEN + "This server is running " + AuthMe.PLUGIN_NAME + " v" + AuthMe.getVersionName() + "! " + ChatColor.RED + "<3");
sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + commandReference.get(0) + " help" + ChatColor.YELLOW + " to view help.");
sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + commandReference.get(0) + " about" + ChatColor.YELLOW + " to view about.");
return true;
}
}

View File

@ -0,0 +1,100 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.security.NoSuchAlgorithmException;
public class ChangePasswordCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the player and password
String playerName = commandArguments.get(0);
final String playerPass = commandArguments.get(1);
// Validate the password
String playerPassLowerCase = playerPass.toLowerCase();
if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
m.send(sender, "password_error");
return true;
}
if (playerPassLowerCase.equalsIgnoreCase(playerName)) {
m.send(sender, "password_error_nick");
return true;
}
if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
m.send(sender, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
m.send(sender, "password_error_unsafe");
return true;
}
}
// Set the password
final String playerNameLowerCase = playerName.toLowerCase();
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
String hash;
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, playerPass, playerNameLowerCase);
} catch (NoSuchAlgorithmException e) {
m.send(sender, "error");
return;
}
PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
auth = PlayerCache.getInstance().getAuth(playerNameLowerCase);
} else if (plugin.database.isAuthAvailable(playerNameLowerCase)) {
auth = plugin.database.getAuth(playerNameLowerCase);
}
if (auth == null) {
m.send(sender, "unknown_user");
return;
}
auth.setHash(hash);
if (PasswordSecurity.userSalt.containsKey(playerNameLowerCase)) {
auth.setSalt(PasswordSecurity.userSalt.get(playerNameLowerCase));
plugin.database.updateSalt(auth);
}
if (!plugin.database.updatePassword(auth)) {
m.send(sender, "error");
return;
}
sender.sendMessage("pwd_changed");
ConsoleLogger.info(playerNameLowerCase + "'s password changed");
}
});
return true;
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Spawn;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class FirstSpawnCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Make sure the command executor is a player
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null)
((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
else sender.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
}
}

View File

@ -0,0 +1,51 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ForceLoginCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Get the player query
String playerName = sender.getName();
if(commandArguments.getCount() >= 1)
playerName = commandArguments.get(0);
// Command logic
try {
@SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(playerName);
if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!");
return true;
}
if (!plugin.authmePermissible(player, "authme.canbeforced")) {
sender.sendMessage("You cannot force login for the player " + playerName + "!");
return true;
}
plugin.management.performLogin(player, "dontneed", true);
sender.sendMessage("Force Login for " + playerName + " performed!");
} catch (Exception e) {
sender.sendMessage("An error occurred while trying to get that player!");
}
return true;
}
}

View File

@ -0,0 +1,45 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import org.bukkit.command.CommandSender;
public class GetEmailCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
AuthMe plugin = AuthMe.getInstance();
// Messages instance
Messages m = Messages.getInstance();
// Get the player name
String playerName = sender.getName();
if(commandArguments.getCount() >= 1)
playerName = commandArguments.get(0);
// Get the authenticated user
PlayerAuth auth = plugin.database.getAuth(playerName.toLowerCase());
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
// Show the email address
sender.sendMessage("[AuthMe] " + playerName + "'s email: " + auth.getEmail());
return true;
}
}

View File

@ -0,0 +1,41 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GetIpCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Get the player query
String playerName = sender.getName();
if(commandArguments.getCount() >= 1)
playerName = commandArguments.get(0);
@SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(playerName);
if (player == null) {
sender.sendMessage("This player is not actually online");
return true;
}
sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player));
return true;
}
}

View File

@ -0,0 +1,68 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import org.bukkit.command.CommandSender;
import java.util.Date;
public class LastLoginCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
AuthMe plugin = AuthMe.getInstance();
// Messages instance
Messages m = Messages.getInstance();
// Get the player
String playerName = sender.getName();
if(commandArguments.getCount() >= 1)
playerName = commandArguments.get(0);
// Validate the player
PlayerAuth auth;
try {
auth = plugin.database.getAuth(playerName.toLowerCase());
} catch (NullPointerException e) {
m.send(sender, "unknown_user");
return true;
}
if (auth == null) {
m.send(sender, "user_unknown");
return true;
}
// Get the last login date
long lastLogin = auth.getLastLogin();
Date date = new Date(lastLogin);
// Get the difference
final long diff = System.currentTimeMillis() - lastLogin;
// Build the message
final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs.";
// Get the player's last IP
String lastIP = auth.getIp();
// Show the player status
sender.sendMessage("[AuthMe] " + playerName + " last login : " + date.toString());
sender.sendMessage("[AuthMe] The player " + auth.getNickname() + " is unlogged since " + msg);
sender.sendMessage("[AuthMe] Last Player's IP: " + lastIP);
return true;
}
}

View File

@ -0,0 +1,50 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Settings;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class PurgeBannedPlayersCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Get the list of banned players
List<String> bannedPlayers = new ArrayList<>();
for (OfflinePlayer offlinePlayer : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(offlinePlayer.getName().toLowerCase());
}
// Purge the banned players
plugin.database.purgeBanned(bannedPlayers);
if (Settings.purgeEssentialsFile && plugin.ess != null)
plugin.dataManager.purgeEssentials(bannedPlayers);
if (Settings.purgePlayerDat)
plugin.dataManager.purgeDat(bannedPlayers);
if (Settings.purgeLimitedCreative)
plugin.dataManager.purgeLimitedCreative(bannedPlayers);
if (Settings.purgeAntiXray)
plugin.dataManager.purgeAntiXray(bannedPlayers);
// Show a status message
sender.sendMessage("[AuthMe] Database has been purged correctly");
return true;
}
}

View File

@ -0,0 +1,72 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Settings;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Calendar;
import java.util.List;
public class PurgeCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
AuthMe plugin = AuthMe.getInstance();
// Get the days parameter
String daysStr = commandArguments.get(0);
// Convert the days string to an integer value, and make sure it's valid
int days;
try {
days = Integer.valueOf(daysStr);
} catch(Exception ex) {
sender.sendMessage(ChatColor.RED + "The value you've entered is invalid!");
return true;
}
// Validate the value
if(days < 30) {
sender.sendMessage(ChatColor.RED + "You can only purge data older than 30 days");
return true;
}
// Create a calender instance to determine the date
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -days);
long until = calendar.getTimeInMillis();
// Purge the data, get the purged values
List<String> purged = plugin.database.autoPurgeDatabase(until);
// Show a status message
sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts");
// Purge other data
if(Settings.purgeEssentialsFile && plugin.ess != null)
plugin.dataManager.purgeEssentials(purged);
if(Settings.purgePlayerDat)
plugin.dataManager.purgeDat(purged);
if(Settings.purgeLimitedCreative)
plugin.dataManager.purgeLimitedCreative(purged);
if(Settings.purgeAntiXray)
plugin.dataManager.purgeAntiXray(purged);
// Show a status message
sender.sendMessage(ChatColor.GREEN + "[AuthMe] Database has been purged correctly");
return true;
}
}

View File

@ -0,0 +1,64 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PurgeLastPositionCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the player
String playerName = sender.getName();
if(commandArguments.getCount() >= 1)
playerName = commandArguments.get(0);
String playerNameLowerCase = playerName.toLowerCase();
// Purge the last position of the player
try {
// Get the user auth and make sure the user exists
PlayerAuth auth = plugin.database.getAuth(playerNameLowerCase);
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
// Set the last position
auth.setQuitLocX(0D);
auth.setQuitLocY(0D);
auth.setQuitLocZ(0D);
auth.setWorld("world");
plugin.database.updateQuitLoc(auth);
// Show a status message
sender.sendMessage(playerNameLowerCase + "'s last position location is now reset");
} catch (Exception e) {
ConsoleLogger.showError("An error occurred while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player)
sender.sendMessage("An error occurred while trying to reset location or player do not exist, please see logs");
}
return true;
}
}

View File

@ -0,0 +1,92 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.security.NoSuchAlgorithmException;
public class RegisterCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the player name and password
final String playerName = commandArguments.get(0);
final String playerPass = commandArguments.get(1);
final String playerNameLowerCase = playerName.toLowerCase();
final String playerPassLowerCase = playerPass.toLowerCase();
// Command logic
if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
m.send(sender, "password_error");
return true;
}
if (playerPassLowerCase.equalsIgnoreCase(playerName)) {
m.send(sender, "password_error_nick");
return true;
}
if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
m.send(sender, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
m.send(sender, "password_error_unsafe");
return true;
}
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
if (plugin.database.isAuthAvailable(playerNameLowerCase)) {
m.send(sender, "user_regged");
return;
}
String hash = PasswordSecurity.getHash(Settings.getPasswordHash, playerPassLowerCase, playerNameLowerCase);
PlayerAuth auth = new PlayerAuth(playerNameLowerCase, hash, "192.168.0.1", 0L, "your@email.com", playerName);
if (PasswordSecurity.userSalt.containsKey(playerNameLowerCase) && PasswordSecurity.userSalt.get(playerNameLowerCase) != null)
auth.setSalt(PasswordSecurity.userSalt.get(playerNameLowerCase));
else auth.setSalt("");
if (!plugin.database.saveAuth(auth)) {
m.send(sender, "error");
return;
}
plugin.database.setUnlogged(playerNameLowerCase);
if (Bukkit.getPlayerExact(playerName) != null)
Bukkit.getPlayerExact(playerName).kickPlayer("An admin just registered you, please log again");
m.send(sender, "registered");
ConsoleLogger.info(playerNameLowerCase + " registered");
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
}
});
return true;
}
}

View File

@ -0,0 +1,58 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.Profiler;
//import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class ReloadCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Profile the reload process
Profiler p = new Profiler(true);
// AuthMe plugin instance
AuthMe plugin = AuthMe.getInstance();
// Messages instance
Messages m = Messages.getInstance();
// Show a status message
//sender.sendMessage(ChatColor.YELLOW + "Reloading AuthMeReloaded...");
try {
Settings.reload();
plugin.getModuleManager().reloadModules();
Messages.getInstance().reloadMessages();
plugin.setupDatabase();
} catch (Exception e) {
ConsoleLogger.showError("Fatal error occurred! AuthMe instance ABORTED!");
ConsoleLogger.writeStackTrace(e);
plugin.stopOrUnload();
return false;
}
// Show a status message
m.send(sender, "reload");
// AuthMeReloaded reloaded, show a status message
//sender.sendMessage(ChatColor.GREEN + "AuthMeReloaded has been reloaded successfully, took " + p.getTimeFormatted() + "!");
return true;
}
}

View File

@ -0,0 +1,42 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.List;
public class ResetNameCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Command logic
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
List<PlayerAuth> authentications = plugin.database.getAllAuths();
for(PlayerAuth auth : authentications) {
auth.setRealName("Player");
plugin.database.updateSession(auth);
}
}
});
return true;
}
}

View File

@ -0,0 +1,63 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
public class SetEmailCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
AuthMe plugin = AuthMe.getInstance();
// Messages instance
Messages m = Messages.getInstance();
// Get the player name and email address
String playerName = commandArguments.get(0);
String playerEmail = commandArguments.get(1);
// Validate the email address
if (!Settings.isEmailCorrect(playerEmail)) {
m.send(sender, "email_invalid");
return true;
}
// Validate the user
PlayerAuth auth = plugin.database.getAuth(playerName.toLowerCase());
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
// Set the email address
auth.setEmail(playerEmail);
if (!plugin.database.updateEmail(auth)) {
m.send(sender, "error");
return true;
}
// Update the player cache
if (PlayerCache.getInstance().getAuth(playerName.toLowerCase()) != null)
PlayerCache.getInstance().updatePlayer(auth);
// Show a status message
m.send(sender, "email_changed");
return true;
}
}

View File

@ -0,0 +1,36 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Spawn;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SetFirstSpawnCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation()))
sender.sendMessage("[AuthMe] Correctly defined new first spawn point");
else sender.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
}
}

View File

@ -0,0 +1,39 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Spawn;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SetSpawnCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Make sure the command executor is a player
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) {
sender.sendMessage("[AuthMe] Correctly defined new spawn point");
} else {
sender.sendMessage("[AuthMe] SetSpawn has failed, please retry");
}
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Spawn;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SpawnCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Make sure the command executor is a player
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null)
((Player) sender).teleport(Spawn.getInstance().getSpawn());
else sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
}
}

View File

@ -0,0 +1,56 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.command.help.HelpProvider;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class SwitchAntiBotCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Get the new state
String newState = plugin.getAntiBotModMode() ? "OFF" : "ON";
if(commandArguments.getCount() >= 1)
newState = commandArguments.get(0);
// Enable the mod
if(newState.equalsIgnoreCase("ON")) {
plugin.switchAntiBotMod(true);
sender.sendMessage("[AuthMe] AntiBotMod enabled");
return true;
}
// Disable the mod
if(newState.equalsIgnoreCase("OFF")) {
plugin.switchAntiBotMod(false);
sender.sendMessage("[AuthMe] AntiBotMod disabled");
return true;
}
// Show the invalid arguments warning
sender.sendMessage(ChatColor.DARK_RED + "Invalid AntiBot mode!");
// Show the command argument help
HelpProvider.showHelp(sender, commandReference, commandReference, true, false, true, false, false, false);
// Show the command to use for detailed help
CommandParts helpCommandReference = new CommandParts(commandReference.getRange(1));
sender.sendMessage(ChatColor.GOLD + "Detailed help: " + ChatColor.WHITE + "/" + commandReference.get(0) + " help " + helpCommandReference);
return true;
}
}

View File

@ -0,0 +1,98 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
public class UnregisterCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the player name
String playerName = commandArguments.get(0);
String playerNameLowerCase = playerName.toLowerCase();
// Make sure the user is valid
if (!plugin.database.isAuthAvailable(playerNameLowerCase)) {
m.send(sender, "user_unknown");
return true;
}
// Remove the player
if (!plugin.database.removeAuth(playerNameLowerCase)) {
m.send(sender, "error");
return true;
}
// Unregister the player
@SuppressWarnings("deprecation")
Player target = Bukkit.getPlayer(playerNameLowerCase);
PlayerCache.getInstance().removePlayer(playerNameLowerCase);
Utils.setGroup(target, Utils.GroupType.UNREGISTERED);
if (target != null) {
if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(target);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo());
}
}
LimboCache.getInstance().addLimboPlayer(target);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler scheduler = sender.getServer().getScheduler();
if (delay != 0) {
BukkitTask id = scheduler.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, playerNameLowerCase, target), delay);
LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTaskId(id);
}
LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTaskId(scheduler.runTaskAsynchronously(plugin, new MessageTask(plugin, playerNameLowerCase, m.send("reg_msg"), interval)));
if (Settings.applyBlindEffect)
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
target.setWalkSpeed(0.0f);
target.setFlySpeed(0.0f);
}
m.send(target, "unregistered");
}
}
// Show a status message
m.send(sender, "unregistered");
ConsoleLogger.info(playerName + " unregistered");
return true;
}
}

View File

@ -0,0 +1,79 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class VersionCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// Show some version info
sender.sendMessage(ChatColor.GOLD + "==========[ " + AuthMe.PLUGIN_NAME.toUpperCase() + " ABOUT ]==========");
sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.PLUGIN_NAME + " v" + AuthMe.getVersionName() + ChatColor.GRAY + " (code: " + AuthMe.getVersionCode() + ")");
sender.sendMessage(ChatColor.GOLD + "Developers:");
printDeveloper(sender, "Xephi", "xephi", "Lead Developer");
printDeveloper(sender, "Sgdc3", "sgdc3", "Code Contributor");
printDeveloper(sender, "Tim Visee", "timvisee", "Code Contributor");
sender.sendMessage(ChatColor.GOLD + "Website: " + ChatColor.WHITE + "http://dev.bukkit.org/bukkit-plugins/authme-reloaded/");
sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" + ChatColor.GRAY + ChatColor.ITALIC + " (See LICENSE file)");
sender.sendMessage(ChatColor.GOLD + "Copyright: " + ChatColor.WHITE + "Copyright (c) Xephi 2015. All rights reserved.");
return true;
}
/**
* Print a developer with proper styling.
*
* @param sender The command sender.
* @param name The display name of the developer.
* @param minecraftName The Minecraft username of the developer, if available.
* @param function The function of the developer.
*/
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void printDeveloper(CommandSender sender, String name, String minecraftName, String function) {
// Print the name
StringBuilder msg = new StringBuilder();
msg.append(" " + ChatColor.WHITE);
msg.append(name);
// Append the Minecraft name, if available
if(minecraftName.length() != 0)
msg.append(ChatColor.GRAY + " // " + ChatColor.WHITE + minecraftName);
msg.append(ChatColor.GRAY + "" + ChatColor.ITALIC + " (" + function + ")");
// Show the online status
if(minecraftName.length() != 0)
if(isPlayerOnline(minecraftName))
msg.append(ChatColor.GREEN + "" + ChatColor.ITALIC + " (In-Game)");
// Print the message
sender.sendMessage(msg.toString());
}
/**
* Check whether a player is online.
*
* @param minecraftName The Minecraft player name.
*
* @return True if the player is online, false otherwise.
*/
private boolean isPlayerOnline(String minecraftName) {
for(Player player : Bukkit.getOnlinePlayers())
if(player.getName().equalsIgnoreCase(minecraftName))
return true;
return false;
}
}

View File

@ -0,0 +1,82 @@
package fr.xephi.authme.command.executable.captcha;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CaptchaCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Random string instance, for captcha generation (I think) -- timvisee
RandomString randStr = new RandomString(Settings.captchaLength);
// Get the parameter values
String captcha = commandArguments.get(0);
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance and name
final Player player = (Player) sender;
final String playerNameLowerCase = player.getName().toLowerCase();
// Command logic
if (PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
m.send(player, "logged_in");
return true;
}
if (!Settings.useCaptcha) {
m.send(player, "usage_log");
return true;
}
if (!plugin.cap.containsKey(playerNameLowerCase)) {
m.send(player, "usage_log");
return true;
}
if (Settings.useCaptcha && !captcha.equals(plugin.cap.get(playerNameLowerCase))) {
plugin.cap.remove(playerNameLowerCase);
plugin.cap.put(playerNameLowerCase, randStr.nextString());
for (String s : m.send("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(playerNameLowerCase)));
}
return true;
}
try {
plugin.captcha.remove(playerNameLowerCase);
plugin.cap.remove(playerNameLowerCase);
} catch (NullPointerException ignored) { }
// Show a status message
m.send(player, "valid_captcha");
m.send(player, "login_msg");
return true;
}
}

View File

@ -0,0 +1,74 @@
package fr.xephi.authme.command.executable.changepassword;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.ChangePasswordTask;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ChangePasswordCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the passwords
String playerPass = commandArguments.get(0);
String playerPassVerify = commandArguments.get(1);
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance and make sure it's authenticated
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in");
return true;
}
// Make sure the password is allowed
String playerPassLowerCase = playerPass.toLowerCase();
if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
m.send(player, "password_error");
return true;
}
if (playerPassLowerCase.equalsIgnoreCase(name)) {
m.send(player, "password_error_nick");
return true;
}
if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
m.send(player, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
m.send(player, "password_error_unsafe");
return true;
}
}
// Set the password
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, playerPass, playerPassVerify));
return true;
}
}

View File

@ -0,0 +1,108 @@
package fr.xephi.authme.command.executable.converter;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.converter.*;
import fr.xephi.authme.settings.Messages;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ConverterCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the conversion job
String job = commandArguments.get(0);
// Determine the job type
ConvertType jobType = ConvertType.fromName(job);
if (jobType == null) {
m.send(sender, "error");
return true;
}
// Get the proper converter instance
Converter converter = null;
switch (jobType) {
case ftsql:
converter = new FlatToSql();
break;
case ftsqlite:
converter = new FlatToSqlite(sender);
break;
case xauth:
converter = new xAuthConverter(plugin, sender);
break;
case crazylogin:
converter = new CrazyLoginConverter(plugin, sender);
break;
case rakamak:
converter = new RakamakConverter(plugin, sender);
break;
case royalauth:
converter = new RoyalAuthConverter(plugin);
break;
case vauth:
converter = new vAuthConverter(plugin, sender);
break;
case sqltoflat:
converter = new SqlToFlat(plugin, sender);
break;
default:
break;
}
// Run the convert job
Bukkit.getScheduler().runTaskAsynchronously(plugin, converter);
// Show a status message
sender.sendMessage("[AuthMe] Successfully converted from " + jobType.getName());
return true;
}
public enum ConvertType {
ftsql("flattosql"),
ftsqlite("flattosqlite"),
xauth("xauth"),
crazylogin("crazylogin"),
rakamak("rakamak"),
royalauth("royalauth"),
vauth("vauth"),
sqltoflat("sqltoflat");
String name;
ConvertType(String name) {
this.name = name;
}
String getName() {
return this.name;
}
public static ConvertType fromName(String name) {
for (ConvertType type : ConvertType.values()) {
if (type.getName().equalsIgnoreCase(name))
return type;
}
return null;
}
}
}

View File

@ -0,0 +1,90 @@
package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class AddEmailCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the parameter values
String playerMail = commandArguments.get(0);
String playerMailVerify = commandArguments.get(1);
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance and name
final Player player = (Player) sender;
final String playerName = player.getName();
// Command logic
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && plugin.database.getAllAuthsByEmail(playerMail).size() >= Settings.getmaxRegPerEmail) {
m.send(player, "max_reg");
return true;
}
}
if (playerMail.equals(playerMailVerify) && PlayerCache.getInstance().isAuthenticated(playerName)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(playerName);
if (auth.getEmail() == null || (!auth.getEmail().equals("your@email.com") && !auth.getEmail().isEmpty())) {
m.send(player, "usage_email_change");
return true;
}
if (!Settings.isEmailCorrect(playerMail)) {
m.send(player, "email_invalid");
return true;
}
auth.setEmail(playerMail);
if (!plugin.database.updateEmail(auth)) {
m.send(player, "error");
return true;
}
PlayerCache.getInstance().updatePlayer(auth);
m.send(player, "email_added");
player.sendMessage(auth.getEmail());
} else if (PlayerCache.getInstance().isAuthenticated(playerName)) {
m.send(player, "email_confirm");
} else {
if (!plugin.database.isAuthAvailable(playerName)) {
m.send(player, "login_msg");
} else {
m.send(player, "reg_email_msg");
}
}
return true;
}
}

View File

@ -0,0 +1,88 @@
package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
public class ChangeEmailCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the parameter values
String playerMailOld = commandArguments.get(0);
String playerMailNew = commandArguments.get(1);
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance and name
final Player player = (Player) sender;
final String playerName = player.getName();
// Command logic
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(sender, "authme.allow2accounts") && plugin.database.getAllAuthsByEmail(playerMailNew).size() >= Settings.getmaxRegPerEmail) {
m.send(player, "max_reg");
return true;
}
}
if (PlayerCache.getInstance().isAuthenticated(playerName)) {
PlayerAuth auth = PlayerCache.getInstance().getAuth(playerName);
if (auth.getEmail() == null || auth.getEmail().equals("your@email.com") || auth.getEmail().isEmpty()) {
m.send(player, "usage_email_add");
return true;
}
if (!playerMailOld.equals(auth.getEmail())) {
m.send(player, "old_email_invalid");
return true;
}
if (!Settings.isEmailCorrect(playerMailNew)) {
m.send(player, "new_email_invalid");
return true;
}
auth.setEmail(playerMailNew);
if (!plugin.database.updateEmail(auth)) {
m.send(player, "error");
return true;
}
PlayerCache.getInstance().updatePlayer(auth);
m.send(player, "email_changed");
player.sendMessage(Arrays.toString(m.send("email_defined")) + auth.getEmail());
} else if (PlayerCache.getInstance().isAuthenticated(playerName)) {
m.send(player, "email_confirm");
} else {
if (!plugin.database.isAuthAvailable(playerName)) {
m.send(player, "login_msg");
} else {
m.send(player, "reg_email_msg");
}
}
return true;
}
}

View File

@ -0,0 +1,96 @@
package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.security.NoSuchAlgorithmException;
public class RecoverEmailCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Get the parameter values
String playerMail = commandArguments.get(0);
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance and name
final Player player = (Player) sender;
final String playerName = player.getName();
// Command logic
if (plugin.mail == null) {
m.send(player, "error");
return true;
}
if (plugin.database.isAuthAvailable(playerName)) {
if (PlayerCache.getInstance().isAuthenticated(playerName)) {
m.send(player, "logged_in");
return true;
}
try {
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
String thePass = rand.nextString();
String hashNew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, playerName);
PlayerAuth auth;
if (PlayerCache.getInstance().isAuthenticated(playerName)) {
auth = PlayerCache.getInstance().getAuth(playerName);
} else if (plugin.database.isAuthAvailable(playerName)) {
auth = plugin.database.getAuth(playerName);
} else {
m.send(player, "unknown_user");
return true;
}
if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) {
m.send(player, "error");
return true;
}
if (!playerMail.equalsIgnoreCase(auth.getEmail()) || playerMail.equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) {
m.send(player, "email_invalid");
return true;
}
auth.setHash(hashNew);
plugin.database.updatePassword(auth);
plugin.mail.main(auth, thePass);
m.send(player, "email_send");
} catch (NoSuchAlgorithmException | NoClassDefFoundError ex) {
ex.printStackTrace();
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
} else {
m.send(player, "reg_email_msg");
}
return true;
}
}

View File

@ -0,0 +1,40 @@
package fr.xephi.authme.command.executable.login;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class LoginCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance
final Player player = (Player) sender;
// Get the password
String playerPass = commandArguments.get(0);
// Login the player
plugin.management.performLogin(player, playerPass, false);
return true;
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.command.executable.logout;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class LogoutCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the player instance
final Player player = (Player) sender;
// Logout the player
plugin.management.performLogout(player);
return true;
}
}

View File

@ -0,0 +1,69 @@
package fr.xephi.authme.command.executable.register;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class RegisterCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Make sure the sender is a player
if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true;
}
// Make sure the command arguments are valid
final Player player = (Player) sender;
if (commandArguments.getCount() == 0 || (Settings.getEnablePasswordVerifier && commandArguments.getCount() < 2)) {
m.send(player, "usage_reg");
return true;
}
if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if (Settings.doubleEmailCheck) {
if (commandArguments.getCount() < 2 || !commandArguments.get(0).equals(commandArguments.get(1))) {
m.send(player, "usage_reg");
return true;
}
}
final String email = commandArguments.get(0);
if (!Settings.isEmailCorrect(email)) {
m.send(player, "email_invalid");
return true;
}
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
final String thePass = rand.nextString();
plugin.management.performRegister(player, thePass, email);
return true;
}
if (commandArguments.getCount() > 1 && Settings.getEnablePasswordVerifier)
if (!commandArguments.get(0).equals(commandArguments.get(1))) {
m.send(player, "password_error");
return true;
}
plugin.management.performRegister(player, commandArguments.get(0), "");
return true;
}
}

View File

@ -0,0 +1,52 @@
package fr.xephi.authme.command.executable.unregister;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Messages;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class UnregisterCommand extends ExecutableCommand {
/**
* Execute the command.
*
* @param sender The command sender.
* @param commandReference The command reference.
* @param commandArguments The command arguments.
*
* @return True if the command was executed successfully, false otherwise.
*/
@Override
public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Messages instance
final Messages m = Messages.getInstance();
// Make sure the current command executor is a player
if(!(sender instanceof Player)) {
return true;
}
// Get the password
String playerPass = commandArguments.get(0);
// Get the player instance and name
final Player player = (Player) sender;
final String playerNameLowerCase = player.getName().toLowerCase();
// Make sure the player is authenticated
if (!PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
m.send(player, "not_logged_in");
return true;
}
// Unregister the player
plugin.management.performUnregister(player, playerPass, false);
return true;
}
}

View File

@ -0,0 +1,195 @@
package fr.xephi.authme.command.help;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandArgumentDescription;
import fr.xephi.authme.command.CommandDescription;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.command.CommandPermissions;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class HelpPrinter {
/**
* Print the command help information.
*
* @param sender The command sender to print the help to.
* @param command The command to print.
* @param commandReference The command reference used.
*/
public static void printCommand(CommandSender sender, CommandDescription command, CommandParts commandReference) {
// Print the proper command syntax
sender.sendMessage(ChatColor.GOLD + "Command: " + HelpSyntaxHelper.getCommandSyntax(command, commandReference, null, true));
}
/**
* Print the command help description information. This will print both the short, as the detailed description if available.
*
* @param sender The command sender to print the help to.
* @param command The command to print the description help for.
*/
public static void printCommandDescription(CommandSender sender, CommandDescription command) {
// Print the regular description, if available
if(command.hasDescription())
sender.sendMessage(ChatColor.GOLD + "Short Description: " + ChatColor.WHITE + command.getDescription());
// Print the detailed description, if available
if(command.hasDetailedDescription()) {
sender.sendMessage(ChatColor.GOLD + "Detailed Description:");
sender.sendMessage(ChatColor.WHITE + " " + command.getDetailedDescription());
}
}
/**
* Print the command help arguments information if available.
*
* @param sender The command sender to print the help to.
* @param command The command to print the argument help for.
*/
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public static void printArguments(CommandSender sender, CommandDescription command) {
// Make sure there are any commands to print
if(!command.hasArguments() && command.getMaximumArguments() >= 0)
return;
// Print the header
sender.sendMessage(ChatColor.GOLD + "Arguments:");
// Print each argument
for(CommandArgumentDescription arg : command.getArguments()) {
// Create a string builder to build the syntax in
StringBuilder argString = new StringBuilder();
argString.append(" " + ChatColor.YELLOW + ChatColor.ITALIC + arg.getLabel() + " : " + ChatColor.WHITE + arg.getDescription());
// Suffix a note if the command is optional
if(arg.isOptional())
argString.append(ChatColor.GRAY + "" + ChatColor.ITALIC + " (Optional)");
// Print the syntax
sender.sendMessage(argString.toString());
}
// Show the unlimited arguments argument
if(command.getMaximumArguments() < 0)
sender.sendMessage(" " + ChatColor.YELLOW + ChatColor.ITALIC + "... : " + ChatColor.WHITE + "Any additional arguments." + ChatColor.GRAY + ChatColor.ITALIC + " (Optional)");
}
/**
* Print the command help permissions information if available.
*
* @param sender The command sender to print the help to.
* @param command The command to print the permissions help for.
*/
public static void printPermissions(CommandSender sender, CommandDescription command) {
// Get the permissions and make sure it isn't null
CommandPermissions permissions = command.getCommandPermissions();
if(permissions == null)
return;
// Make sure any permission node is set
if(permissions.getPermissionNodeCount() <= 0)
return;
// Print the header
sender.sendMessage(ChatColor.GOLD + "Permissions:");
// Print each node
for(String node : permissions.getPermissionNodes()) {
boolean nodePermission = true;
if(sender instanceof Player)
nodePermission = AuthMe.getInstance().authmePermissible((Player) sender, node);
final String nodePermsString = ChatColor.GRAY + (nodePermission ? ChatColor.ITALIC + " (Permission!)" : ChatColor.ITALIC + " (No Permission!)");
sender.sendMessage(" " + ChatColor.YELLOW + ChatColor.ITALIC + node + nodePermsString);
}
// Print the default permission
switch(permissions.getDefaultPermission()) {
case ALLOWED:
sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.GRAY + ChatColor.ITALIC + "Permission!");
break;
case OP_ONLY:
final String defaultPermsString = ChatColor.GRAY + (permissions.getDefaultPermissionCommandSender(sender) ? ChatColor.ITALIC + " (Permission!)" : ChatColor.ITALIC + " (No Permission!)");
sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.YELLOW + ChatColor.ITALIC + "OP's Only!" + defaultPermsString);
break;
case NOT_ALLOWED:
default:
sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.GRAY + ChatColor.ITALIC + "No Permission!");
break;
}
// Print the permission result
if(permissions.hasPermission(sender))
sender.sendMessage(ChatColor.GOLD + " Result: " + ChatColor.GREEN + ChatColor.ITALIC + "Permission!");
else
sender.sendMessage(ChatColor.GOLD + " Result: " + ChatColor.DARK_RED + ChatColor.ITALIC + "No Permission!");
}
/**
* Print the command help alternatives information if available.
*
* @param sender The command sender to print the help to.
* @param command The command used.
* @param commandReference The original command reference used for this command.
*/
public static void printAlternatives(CommandSender sender, CommandDescription command, CommandParts commandReference) {
// Make sure there are any alternatives
if(command.getLabels().size() <= 1)
return;
// Print the header
sender.sendMessage(ChatColor.GOLD + "Alternatives:");
// Get the label used
final String usedLabel = commandReference.get(command.getParentCount());
// Create a list of alternatives
List<String> alternatives = new ArrayList<>();
for(String entry : command.getLabels()) {
// Exclude the proper argument
if(entry.equalsIgnoreCase(usedLabel))
continue;
alternatives.add(entry);
}
// Sort the alternatives
Collections.sort(alternatives, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Double.compare(StringUtils.getDifference(usedLabel, o1), StringUtils.getDifference(usedLabel, o2));
}
});
// Print each alternative with proper syntax
for(String alternative : alternatives)
sender.sendMessage(" " + HelpSyntaxHelper.getCommandSyntax(command, commandReference, alternative, true));
}
/**
* Print the command help child's information if available.
*
* @param sender The command sender to print the help to.
* @param command The command to print the help for.
* @param commandReference The original command reference used for this command.
*/
public static void printChildren(CommandSender sender, CommandDescription command, CommandParts commandReference) {
// Make sure there are child's
if(command.getChildren().size() <= 0)
return;
// Print the header
sender.sendMessage(ChatColor.GOLD + "Commands:");
// Loop through each child
for(CommandDescription child : command.getChildren())
sender.sendMessage(" " + HelpSyntaxHelper.getCommandSyntax(child, commandReference, null, false) + ChatColor.GRAY + ChatColor.ITALIC + " : " + child.getDescription());
}
}

View File

@ -0,0 +1,114 @@
package fr.xephi.authme.command.help;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.*;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class HelpProvider {
/**
* Show help for a specific command.
*
* @param sender The command sender the help needs to be shown to.
* @param reference The command reference to the help command.
* @param helpQuery The query to show help for.
*/
public static void showHelp(CommandSender sender, CommandParts reference, CommandParts helpQuery) {
showHelp(sender, reference, helpQuery, true, true, true, true, true, true);
}
/**
* Show help for a specific command.
*
* @param sender The command sender the help needs to be shown to.
* @param reference The command reference to the help command.
* @param helpQuery The query to show help for.
* @param showCommand True to show the command.
* @param showDescription True to show the command description, both the short and detailed description.
* @param showArguments True to show the command argument help.
* @param showPermissions True to show the command permission help.
* @param showAlternatives True to show the command alternatives.
* @param showCommands True to show the child commands.
*/
public static void showHelp(CommandSender sender, CommandParts reference, CommandParts helpQuery, boolean showCommand, boolean showDescription, boolean showArguments, boolean showPermissions, boolean showAlternatives, boolean showCommands) {
// Find the command for this help query, one with and one without a prefixed base command
FoundCommandResult result = AuthMe.getInstance().getCommandHandler().getCommandManager().findCommand(new CommandParts(helpQuery.getList()));
CommandParts commandReferenceOther = new CommandParts(reference.get(0), helpQuery.getList());
FoundCommandResult resultOther = AuthMe.getInstance().getCommandHandler().getCommandManager().findCommand(commandReferenceOther);
if(resultOther != null) {
if(result == null)
result = resultOther;
else if(result.getDifference() > resultOther.getDifference())
result = resultOther;
}
// Make sure a result was found
if(result == null) {
// Show a warning message
sender.sendMessage(ChatColor.DARK_RED + "" + ChatColor.ITALIC + helpQuery);
sender.sendMessage(ChatColor.DARK_RED + "Couldn't show any help information for this help query.");
return;
}
// Get the command description, and make sure it's valid
CommandDescription command = result.getCommandDescription();
if(command == null) {
// Show a warning message
sender.sendMessage(ChatColor.DARK_RED + "Failed to retrieve any help information!");
return;
}
// Get the proper command reference to use for the help page
CommandParts commandReference = command.getCommandReference(result.getQueryReference());
// Get the base command
String baseCommand = commandReference.get(0);
// Make sure the difference between the command reference and the actual command isn't too big
final double commandDifference = result.getDifference();
if(commandDifference > 0.20) {
// Show the unknown command warning
sender.sendMessage(ChatColor.DARK_RED + "No help found for '" + helpQuery + "'!");
// Get the suggested command
CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference).getRange(1));
// Show a command suggestion if available and the difference isn't too big
if(commandDifference < 0.75)
if(result.getCommandDescription() != null)
sender.sendMessage(ChatColor.YELLOW + "Did you mean " + ChatColor.GOLD + "/" + baseCommand + " help " + suggestedCommandParts + ChatColor.YELLOW + "?");
// Show the help command
sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help" + ChatColor.YELLOW + " to view help.");
return;
}
// Show a message when the command handler is assuming a command
if(commandDifference > 0) {
// Get the suggested command
CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference).getRange(1));
// Show the suggested command
sender.sendMessage(ChatColor.DARK_RED + "No help found, assuming '" + ChatColor.GOLD + suggestedCommandParts + ChatColor.DARK_RED + "'!");
}
// Print the help header
sender.sendMessage(ChatColor.GOLD + "==========[ " + AuthMe.PLUGIN_NAME.toUpperCase() + " HELP ]==========");
// Print the command help information
if(showCommand)
HelpPrinter.printCommand(sender, command, commandReference);
if(showDescription)
HelpPrinter.printCommandDescription(sender, command);
if(showArguments)
HelpPrinter.printArguments(sender, command);
if(showPermissions)
HelpPrinter.printPermissions(sender, command);
if(showAlternatives)
HelpPrinter.printAlternatives(sender, command, commandReference);
if(showCommands)
HelpPrinter.printChildren(sender, command, commandReference);
}
}

View File

@ -0,0 +1,60 @@
package fr.xephi.authme.command.help;
import fr.xephi.authme.command.CommandArgumentDescription;
import fr.xephi.authme.command.CommandDescription;
import fr.xephi.authme.command.CommandParts;
import fr.xephi.authme.util.ListUtils;
import org.bukkit.ChatColor;
public class HelpSyntaxHelper {
/**
* Get the proper syntax for a command.
*
* @param commandDescription The command to get the syntax for.
* @param commandReference The reference of the command.
* @param alternativeLabel The alternative label to use for this command syntax.
* @param highlight True to highlight the important parts of this command.
*
* @return The command with proper syntax.
*/
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public static String getCommandSyntax(CommandDescription commandDescription, CommandParts commandReference, String alternativeLabel, boolean highlight) {
// Create a string builder to build the command
StringBuilder sb = new StringBuilder();
// Set the color and prefix a slash
sb.append(ChatColor.WHITE + "/");
// Get the help command reference, and the command label
CommandParts helpCommandReference = commandDescription.getCommandReference(commandReference);
final String parentCommand = (new CommandParts(helpCommandReference.getRange(0, helpCommandReference.getCount() - 1))).toString();
String commandLabel = helpCommandReference.get(helpCommandReference.getCount() - 1);
// Check whether the alternative label should be used
if(alternativeLabel != null)
if(alternativeLabel.trim().length() > 0)
commandLabel = alternativeLabel;
// Show the important bit of the command, highlight this part if required
sb.append(ListUtils.implode(parentCommand, (highlight ? ChatColor.YELLOW + "" + ChatColor.BOLD : "") + commandLabel, " "));
if(highlight)
sb.append(ChatColor.YELLOW);
// Add each command arguments
for(CommandArgumentDescription arg : commandDescription.getArguments()) {
// Add the argument as optional or non-optional argument
if(!arg.isOptional())
sb.append(ChatColor.ITALIC + " <" + arg.getLabel() + ">");
else
sb.append(ChatColor.ITALIC + " [" + arg.getLabel() + "]");
}
// Add some dots if the command allows unlimited arguments
if(commandDescription.getMaximumArguments() < 0)
sb.append(ChatColor.ITALIC + " ...");
// Return the build command syntax
return sb.toString();
}
}

View File

@ -0,0 +1,75 @@
package fr.xephi.authme.util;
import java.util.ArrayList;
import java.util.List;
public class ListUtils {
/**
* Implode a list of elements into a single string, with a specified separator.
*
* @param elements The elements to implode.
* @param separator The separator to use.
*
* @return The result string.
*/
public static String implode(List<String> elements, String separator) {
// Create a string builder
StringBuilder sb = new StringBuilder();
// Append each element
for(String element : elements) {
// Make sure the element isn't empty
if(element.trim().length() == 0)
continue;
// Prefix the separator if it isn't the first element
if(sb.length() > 0)
sb.append(separator);
// Append the element
sb.append(element);
}
// Return the result
return sb.toString();
}
/**
* Implode two lists of elements into a single string, with a specified separator.
*
* @param elements The first list of elements to implode.
* @param otherElements The second list of elements to implode.
* @param separator The separator to use.
*
* @return The result string.
*/
public static String implode(List<String> elements, List<String> otherElements, String separator) {
// Combine the lists
List<String> combined = new ArrayList<>();
combined.addAll(elements);
combined.addAll(otherElements);
// Implode and return the result
return implode(combined, separator);
}
/**
* Implode two elements into a single string, with a specified separator.
*
* @param element The first element to implode.
* @param otherElement The second element to implode.
* @param separator The separator to use.
*
* @return The result string.
*/
public static String implode(String element, String otherElement, String separator) {
// Combine the lists
List<String> combined = new ArrayList<>();
combined.add(element);
combined.add(otherElement);
// Implode and return the result
return implode(combined, separator);
}
}

View File

@ -0,0 +1,132 @@
package fr.xephi.authme.util;
import java.text.DecimalFormat;
@SuppressWarnings("UnusedDeclaration")
public class Profiler {
/** Defines the past time in milliseconds. */
private long time = 0;
/** Defines the time in milliseconds the profiler last started at. */
private long start = -1;
/**
* Constructor. This won't start the profiler immediately.
*/
public Profiler() {
this(false);
}
/**
* Constructor.
*
* @param start True to immediately start the profiler.
*/
public Profiler(boolean start) {
// Should the timer be started
if(start)
start();
}
/**
* Start the profiler.
*
* @return True if the profiler was started, false otherwise possibly due to an error.
* True will also be returned if the profiler was started already.
*/
public boolean start() {
// Make sure the timer isn't started already
if(isActive())
return true;
// Set the start time
this.start = System.currentTimeMillis();
return true;
}
/**
* This will start the profiler if it's not active, or will stop the profiler if it's currently active.
*
* @return True if the profiler has been started, false if the profiler has been stopped.
*/
public boolean pause() {
// Toggle the profiler state
if(isStarted())
stop();
else
start();
// Return the result
return isStarted();
}
/**
* Stop the profiler if it's active.
*
* @return True will be returned if the profiler was stopped while it was active. False will be returned if the
* profiler was stopped already.
*/
public boolean stop() {
// Make sure the profiler is active
if(!isActive())
return false;
// Stop the profiler, calculate the passed time
this.time += System.currentTimeMillis() - this.start;
this.start = -1;
return true;
}
/**
* Check whether the profiler has been started. The profiler doesn't need to be active right now.
*
* @return True if the profiler was started, false otherwise.
*/
public boolean isStarted() {
return isActive() || this.time > 0;
}
/**
* Check whether the profiler is currently active.
*
* @return True if the profiler is active, false otherwise.
*/
public boolean isActive() {
return this.start >= 0;
}
/**
* Get the passed time in milliseconds.
*
* @return The passed time in milliseconds.
*/
public long getTime() {
// Check whether the profiler is currently active
if(isActive())
return this.time + (System.currentTimeMillis() - this.start);
return this.time;
}
/**
* Get the passed time in a formatted string.
*
* @return The passed time in a formatted string.
*/
public String getTimeFormatted() {
// Get the passed time
long time = getTime();
// Return the time if it's less than one millisecond
if(time <= 0)
return "<1 ms";
// Return the time in milliseconds
if(time < 1000)
return time + " ms";
// Convert the time into seconds with a single decimal
double timeSeconds = ((double) time) / 1000;
DecimalFormat df = new DecimalFormat("#0.0");
return df.format(timeSeconds) + " s";
}
}

View File

@ -0,0 +1,28 @@
package fr.xephi.authme.util;
import net.ricecode.similarity.LevenshteinDistanceStrategy;
import net.ricecode.similarity.StringSimilarityService;
import net.ricecode.similarity.StringSimilarityServiceImpl;
public class StringUtils {
/**
* Get the difference of two strings.
*
* @param first First string.
* @param second Second string.
*
* @return The difference value.
*/
public static double getDifference(String first, String second) {
// Make sure the strings are valid.
if(first == null || second == null)
return 1.0;
// Create a string similarity service instance, to allow comparison
StringSimilarityService service = new StringSimilarityServiceImpl(new LevenshteinDistanceStrategy());
// Determine the difference value, return the result
return Math.abs(service.score(first, second) - 1.0);
}
}

View File

@ -1,56 +1,56 @@
unknown_user: Gebruiker is niet gevonden in database
unsafe_spawn: De locatie waar je de vorige keer het spel verlied was gevaarlijk, je bent geteleporteert naar de Spawn
unknown_user: Gebruiker is niet gevonden in de database
unsafe_spawn: De locatie waar je de vorige keer het spel verliet was gevaarlijk, je bent geteleporteerd naar de spawn
not_logged_in: '&cNiet ingelogt!'
reg_voluntarily: Je kunt je gebruikersnaam registreren met "/register <wachtwoord> <herhaalWachtwoord>"
usage_log: '&cGebruik: /login <wachtwoord>'
wrong_pwd: '&cFout wachtwoord'
unregistered: '&cRegistratie succesvol ongedaan gemaakt!'
reg_disabled: '&cRegistratie is uitgeschakeld'
valid_session: '&cSessie ingelogt'
login: '&cSuccesvol ingelogt!'
password_error_nick: '&fYou can''t use your name as password'
password_error_unsafe: '&fYou can''t use unsafe passwords'
valid_session: '&cSessie ingelogd'
login: '&cSuccesvol ingelogd!'
password_error_nick: '&fJe kunt je gebruikersnaam niet als wachtwoord gebruiken'
password_error_unsafe: '&fJe kunt geen onveilige wachtwoorden gebruiken'
vb_nonActiv: Je accound is nog niet geactiveerd, controleer je mailbox!
user_regged: '&cGebruikersnaam is al geregistreerd'
usage_reg: '&cGebruik: /register <wachtwoord> <herhaalWachtwoord>'
max_reg: Je hebt de maximale registraties van jouw account overschreden.
no_perm: '&cGeen toegang!'
error: Error; neem contact op met een ADMIN!
error: Error: neem contact op met een administrator!
login_msg: '&cLog in met "/login <wachtwoord>"'
reg_msg: '&cRegistreer met "/register <wachtwoord> <herhaalWachtwoord>"'
usage_unreg: '&cGebruik: /unregister password'
pwd_changed: '&cWachtwoord aangepast!'
user_unknown: '&cGebruikersnaam niet geregistreerd'
password_error: Wachtwoord incorrect!
invalid_session: Sessie beschadigt, wacht tot de sessie is verlopen en join opnieuw.
invalid_session: Sessie beschadigd, wacht tot de sessie is verlopen en verbindt opnieuw.
reg_only: Alleen voor geregistreerde spelers! Bezoek http://example.com om te registreren
logged_in: '&cJe bent al ingelogt!'
logout: '&cJe bent succesvol uitgelogt'
logged_in: '&cJe bent al ingelogd!'
logout: '&cJe bent succesvol uitgelogd'
same_nick: Er is al iemand met jou gebruikersnaam online.
registered: '&cSuccesvol geregistreerd!'
pass_len: Je gekozen wachtwoord voldoet niet aan de minimum of maximum lengte
reload: Configuratie en database is opnieuw opgestard
timeout: Login time-out; het duurde telang voor je je inlogde.
timeout: Login time-out: het duurde telang voor je je inlogde.
usage_changepassword: 'Gebruik: /changepassword <oudWachtwoord> <nieuwWachtwoord>'
name_len: '&cJouw gebruikersnaam is te kort'
regex: '&cJouw gebruikersnaam bestaat uit illegale tekens. tegestaan chars: REG_EX'
add_email: '&cVoeg uw email toe Alstublieft met: /email add jouw wachtwoord herhaalwachtwoord'
recovery_email: '&cWachtwoord vergeten? gebruik alstublieft /email recovery <Jouwemail>'
usage_captcha: '&cGebruik: /captcha <deCaptcha>'
wrong_captcha: '&cverkeerde Captcha, Gebruik alstublieft : /captcha THE_CAPTCHA'
valid_captcha: '&cJouw captcha is geldig!'
kick_forvip: '&cA VIP Gebruiker ga naar de volledige server!'
kick_fullserver: '&cDe server is eigenlijk vol, Sorry!'
usage_email_add: '&fGebruik: /email add <email> <herhaalEmail> '
usage_email_change: '&fGebruik: /email change <oudeEmail> <nieuweEmail> '
usage_email_recovery: '&fGebruik: /email recovery <Email>'
new_email_invalid: '[AuthMe] Nieuw email ongeldig!'
old_email_invalid: '[AuthMe] Oud email ongeldig!'
email_invalid: '[AuthMe] ongeldig Email'
email_added: '[AuthMe] Bevestig jouw Email !'
email_confirm: '[AuthMe] Bevestig jouw Email !'
email_changed: '[AuthMe] Email Veranderd !'
email_send: '[AuthMe] Herstel Email Verzonden !'
country_banned: 'Your country is banned from this server'
antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!'
antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped'
name_len: '&cJe gebruikersnaam is te kort'
regex: '&cJouw gebruikersnaam bevat illegale tekens. Toegestaane karakters: REG_EX'
add_email: '&cVoeg uw E-mail alstublieft toe met: /email add <E-mail> <wachtwoord> <herhaalWachtwoord>'
recovery_email: '&cWachtwoord vergeten? Gebruik alstublieft "/email recovery <E-mail>"'
usage_captcha: '&cGebruik: /captcha <captcha>'
wrong_captcha: '&cVerkeerde Captcha, gebruik alstublieft: /captcha THE_CAPTCHA'
valid_captcha: '&cDe captcha is geldig!'
kick_forvip: '&cEen VIP Gebruiker ga naar de volledige server!'
kick_fullserver: '&cDe server is vol, sorry!'
usage_email_add: '&fGebruik: /email add <E-mail> <herhaalE-mail>'
usage_email_change: '&fGebruik: /email change <oudeE-mail> <nieuweE-mail>'
usage_email_recovery: '&fGebruik: /email recovery <E-mail>'
new_email_invalid: '[AuthMe] Nieuwe E-mail ongeldig!'
old_email_invalid: '[AuthMe] Oude E-mail ongeldig!'
email_invalid: '[AuthMe] Ongeldige E-mail'
email_added: '[AuthMe] Bevestig jouw E-mail!'
email_confirm: '[AuthMe] Bevestig jouw E-mail!'
email_changed: '[AuthMe] Email Veranderd!'
email_send: '[AuthMe] Herstel E-mail Verzonden!'
country_banned: 'Jouw land is geband op deze server'
antibot_auto_enabled: '[AuthMe] AntiBotMod automatisch aangezet vanewge veel verbindingen!'
antibot_auto_disabled: '[AuthMe] AntiBotMod automatisch uitgezet na %m minuten, hopelijk is de invasie gestopt'