diff --git a/.gitignore b/.gitignore
index a0f6e8b..b0616f9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,4 +4,5 @@
/bin
/target
/.classpath
-/.project
\ No newline at end of file
+/.project
+/old
\ No newline at end of file
diff --git a/README.md b/README.md
deleted file mode 100644
index dfa7e15..0000000
--- a/README.md
+++ /dev/null
@@ -1 +0,0 @@
-Will write when I have time.
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 773b5b7..afdec85 100644
--- a/pom.xml
+++ b/pom.xml
@@ -59,6 +59,15 @@
messages.yml
+
+ sql
+ false
+ sql
+
+ h2/*.sql
+ mysql/*.sql
+
+
diff --git a/sql/h2/0001_original_tables.sql b/sql/h2/0001_original_tables.sql
new file mode 100644
index 0000000..a2b0ba6
--- /dev/null
+++ b/sql/h2/0001_original_tables.sql
@@ -0,0 +1,44 @@
+CREATE TABLE IF NOT EXISTS `{TABLE_ACCOUNT}` (
+ `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
+ `playername` VARCHAR(255) NOT NULL,
+ `password` CHAR(255) NOT NULL,
+ `email` VARCHAR(100) NULL,
+ `registerdate` DATETIME NULL,
+ `registerip` CHAR(15) NULL,
+ `lastlogindate` DATETIME NULL,
+ `lastloginip` CHAR(15) NULL,
+ `active` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_SESSION}` (
+ `accountid` INT UNSIGNED NOT NULL,
+ `host` CHAR(15) NOT NULL,
+ `logintime` DATETIME NOT NULL,
+ PRIMARY KEY(`accountid`),
+ FOREIGN KEY (`accountid`) REFERENCES `{TABLE_ACCOUNT}`(`id`) ON DELETE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_LOCATION}` (
+ `worldname` VARCHAR(255) NOT NULL,
+ `x` DOUBLE NOT NULL,
+ `y` DOUBLE NOT NULL,
+ `z` DOUBLE NOT NULL,
+ `yaw` FLOAT NOT NULL,
+ `pitch` FLOAT NOT NULL,
+ PRIMARY KEY(`worldname`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_STRIKE}` (
+ `host` CHAR(15) NOT NULL,
+ `bantime` DATETIME NOT NULL,
+ PRIMARY KEY(`host`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_INVENTORY}` (
+ `playername` VARCHAR(255) NOT NULL,
+ `itemid` TEXT NOT NULL,
+ `amount` TEXT NOT NULL,
+ `durability` TEXT NOT NULL,
+ PRIMARY KEY (`playername`)
+);
\ No newline at end of file
diff --git a/sql/h2/0002_add_location_uid.sql b/sql/h2/0002_add_location_uid.sql
new file mode 100644
index 0000000..7d45797
--- /dev/null
+++ b/sql/h2/0002_add_location_uid.sql
@@ -0,0 +1,6 @@
+ALTER TABLE `{TABLE_LOCATION}` ADD COLUMN `uid` VARCHAR(36) NULL BEFORE `worldname`;
+ALTER TABLE `{TABLE_LOCATION}` ADD COLUMN `global` TINYINT(1) NOT NULL DEFAULT 0;
+UPDATE `{TABLE_LOCATION}` SET `uid` = `worldname`;
+ALTER TABLE `{TABLE_LOCATION}` ALTER COLUMN `uid` VARCHAR(36) NOT NULL;
+ALTER TABLE `{TABLE_LOCATION}` DROP COLUMN `worldname`;
+ALTER TABLE `{TABLE_LOCATION}` ADD PRIMARY KEY (`uid`);
\ No newline at end of file
diff --git a/sql/mysql/0001_original_tables.sql b/sql/mysql/0001_original_tables.sql
new file mode 100644
index 0000000..a2b0ba6
--- /dev/null
+++ b/sql/mysql/0001_original_tables.sql
@@ -0,0 +1,44 @@
+CREATE TABLE IF NOT EXISTS `{TABLE_ACCOUNT}` (
+ `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
+ `playername` VARCHAR(255) NOT NULL,
+ `password` CHAR(255) NOT NULL,
+ `email` VARCHAR(100) NULL,
+ `registerdate` DATETIME NULL,
+ `registerip` CHAR(15) NULL,
+ `lastlogindate` DATETIME NULL,
+ `lastloginip` CHAR(15) NULL,
+ `active` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_SESSION}` (
+ `accountid` INT UNSIGNED NOT NULL,
+ `host` CHAR(15) NOT NULL,
+ `logintime` DATETIME NOT NULL,
+ PRIMARY KEY(`accountid`),
+ FOREIGN KEY (`accountid`) REFERENCES `{TABLE_ACCOUNT}`(`id`) ON DELETE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_LOCATION}` (
+ `worldname` VARCHAR(255) NOT NULL,
+ `x` DOUBLE NOT NULL,
+ `y` DOUBLE NOT NULL,
+ `z` DOUBLE NOT NULL,
+ `yaw` FLOAT NOT NULL,
+ `pitch` FLOAT NOT NULL,
+ PRIMARY KEY(`worldname`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_STRIKE}` (
+ `host` CHAR(15) NOT NULL,
+ `bantime` DATETIME NOT NULL,
+ PRIMARY KEY(`host`)
+);
+
+CREATE TABLE IF NOT EXISTS `{TABLE_INVENTORY}` (
+ `playername` VARCHAR(255) NOT NULL,
+ `itemid` TEXT NOT NULL,
+ `amount` TEXT NOT NULL,
+ `durability` TEXT NOT NULL,
+ PRIMARY KEY (`playername`)
+);
\ No newline at end of file
diff --git a/sql/mysql/0002_add_location_uid.sql b/sql/mysql/0002_add_location_uid.sql
new file mode 100644
index 0000000..e4f9fd0
--- /dev/null
+++ b/sql/mysql/0002_add_location_uid.sql
@@ -0,0 +1,5 @@
+ALTER TABLE `{TABLE_LOCATION}` ADD COLUMN `uid` VARCHAR(36) NOT NULL FIRST;
+ALTER TABLE `{TABLE_LOCATION}` ADD COLUMN `global` TINYINT(1) NOT NULL DEFAULT 0;
+UPDATE `{TABLE_LOCATION}` SET `uid` = `worldname`;
+ALTER TABLE `{TABLE_LOCATION}` DROP COLUMN `worldname`;
+ALTER TABLE `{TABLE_LOCATION}` ADD PRIMARY KEY (`uid`);
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/TeleLocation.java b/src/main/java/com/cypherx/xauth/TeleLocation.java
index f351321..26c2e5d 100644
--- a/src/main/java/com/cypherx/xauth/TeleLocation.java
+++ b/src/main/java/com/cypherx/xauth/TeleLocation.java
@@ -1,34 +1,39 @@
package com.cypherx.xauth;
+import java.util.UUID;
+
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
public class TeleLocation {
- private String worldName;
+ private UUID uid;
private double x;
private double y;
private double z;
private float yaw;
private float pitch;
+ private int global;
public TeleLocation() {}
- public TeleLocation(Location location) {
- worldName = location.getWorld().getName();
+ public TeleLocation(Location location, boolean global) {
+ World world = location.getWorld();
+ uid = world.getUID();
x = location.getX();
y = location.getY();
z = location.getZ();
yaw = location.getYaw();
pitch = location.getPitch();
+ this.global = (global ? 1 : 0);
}
- public void setWorldName(String worldName) {
- this.worldName = worldName;
+ public void setUID(UUID uid) {
+ this.uid = uid;
}
- public String getWorldName() {
- return worldName;
+ public UUID getUID() {
+ return uid;
}
public void setX(double x) {
@@ -71,8 +76,15 @@ public class TeleLocation {
return pitch;
}
+ public void setGlobal(int global) {
+ this.global = global;
+ }
+
+ public int getGlobal() {
+ return global;
+ }
+
public void setLocation(Location location) {
- this.worldName = location.getWorld().getName();
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
@@ -81,7 +93,7 @@ public class TeleLocation {
}
public Location getLocation() {
- World world = Bukkit.getServer().getWorld(worldName);
+ World world = Bukkit.getServer().getWorld(uid);
return new Location(world, x, y, z, yaw, pitch);
}
}
diff --git a/src/main/java/com/cypherx/xauth/Util.java b/src/main/java/com/cypherx/xauth/Util.java
index 5ec2c52..c4df16e 100644
--- a/src/main/java/com/cypherx/xauth/Util.java
+++ b/src/main/java/com/cypherx/xauth/Util.java
@@ -10,6 +10,8 @@ import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.MessageDigest;
+import java.sql.ResultSet;
+import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.UUID;
import java.util.regex.Matcher;
@@ -22,7 +24,7 @@ import com.avaje.ebean.validation.factory.EmailValidatorFactory;
public class Util {
public static void writeConfig(File file, Class> c) {
String fileName = file.getName();
- String content = getResourceAsString(fileName);
+ String content = getResourceAsString("/res/" + fileName);
for (Field field : c.getFields()) {
try {
@@ -45,8 +47,8 @@ public class Util {
}
}
- private static String getResourceAsString(String resource) {
- InputStream input = xAuth.class.getResourceAsStream("/res/" + resource);
+ public static String getResourceAsString(String resource) {
+ InputStream input = xAuth.class.getResourceAsStream(resource);
StringBuilder sb = new StringBuilder();
if (input != null) {
@@ -182,4 +184,52 @@ public class Util {
return intArray;
}
+
+ public static Account buildAccount(ResultSet rs) {
+ Account account = null;
+ try {
+ account = new Account();
+ account.setId(rs.getInt("id"));
+ account.setPlayerName(rs.getString("playername"));
+ account.setPassword(rs.getString("password"));
+ account.setEmail(rs.getString("email"));
+ account.setRegisterDate(rs.getTimestamp("registerdate"));
+ account.setRegisterHost(rs.getString("registerip"));
+ account.setLastLoginDate(rs.getTimestamp("lastlogindate"));
+ account.setLastLoginHost(rs.getString("lastloginip"));
+ account.setActive(rs.getInt("active"));
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not build Account from ResultSet!", e);
+ }
+
+ return account;
+ }
+
+ public static Session buildSession(ResultSet rs) {
+ Session session = null;
+ try {
+ session = new Session();
+ session.setAccountId(rs.getInt("accountid"));
+
+ if (rs.wasNull()) // no session data in database
+ return null;
+
+ session.setHost(rs.getString("host"));
+ session.setLoginTime(rs.getTimestamp("logintime"));
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not build Session from ResultSet!", e);
+ }
+
+ return session;
+ }
+
+ public static boolean isUUID(String str) {
+ try {
+ UUID.fromString(str);
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+
+ return true;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/commands/ChangePasswordCommand.java b/src/main/java/com/cypherx/xauth/commands/ChangePasswordCommand.java
index 9b9db5b..db2e009 100644
--- a/src/main/java/com/cypherx/xauth/commands/ChangePasswordCommand.java
+++ b/src/main/java/com/cypherx/xauth/commands/ChangePasswordCommand.java
@@ -23,7 +23,7 @@ public class ChangePasswordCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
if (!xAuthSettings.pwAllowChange) {
xAuthMessages.send("cpwErrDisabled", player);
diff --git a/src/main/java/com/cypherx/xauth/commands/LoginCommand.java b/src/main/java/com/cypherx/xauth/commands/LoginCommand.java
index 7eb8682..125ef22 100644
--- a/src/main/java/com/cypherx/xauth/commands/LoginCommand.java
+++ b/src/main/java/com/cypherx/xauth/commands/LoginCommand.java
@@ -11,6 +11,7 @@ import com.cypherx.xauth.xAuthLog;
import com.cypherx.xauth.xAuthMessages;
import com.cypherx.xauth.xAuthPlayer;
import com.cypherx.xauth.xAuthSettings;
+import com.cypherx.xauth.database.DbUtil;
public class LoginCommand implements CommandExecutor {
private final xAuth plugin;
@@ -22,7 +23,7 @@ public class LoginCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
if (args.length < 1) {
xAuthMessages.send("loginUsage", player);
@@ -53,7 +54,7 @@ public class LoginCommand implements CommandExecutor {
return true;
}
- int active = plugin.getDataManager().getActive(player.getName());
+ int active = DbUtil.getActive(player.getName());
account.setActive(active);
if (xAuthSettings.activation && active == 0) {
diff --git a/src/main/java/com/cypherx/xauth/commands/LogoutCommand.java b/src/main/java/com/cypherx/xauth/commands/LogoutCommand.java
index c3615cd..395ffa4 100644
--- a/src/main/java/com/cypherx/xauth/commands/LogoutCommand.java
+++ b/src/main/java/com/cypherx/xauth/commands/LogoutCommand.java
@@ -19,7 +19,7 @@ public class LogoutCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
if (!xPlayer.hasSession()) {
xAuthMessages.send("logoutErrLogged", player);
diff --git a/src/main/java/com/cypherx/xauth/commands/RegisterCommand.java b/src/main/java/com/cypherx/xauth/commands/RegisterCommand.java
index 8b2cae5..90b1eea 100644
--- a/src/main/java/com/cypherx/xauth/commands/RegisterCommand.java
+++ b/src/main/java/com/cypherx/xauth/commands/RegisterCommand.java
@@ -7,6 +7,7 @@ import com.cypherx.xauth.xAuthLog;
import com.cypherx.xauth.xAuthMessages;
import com.cypherx.xauth.xAuthPlayer;
import com.cypherx.xauth.xAuthSettings;
+import com.cypherx.xauth.database.DbUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@@ -23,7 +24,7 @@ public class RegisterCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player)sender;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
if (!xAuthSettings.regEnabled) {
xAuthMessages.send("regErrDisabled", player);
@@ -34,7 +35,7 @@ public class RegisterCommand implements CommandExecutor {
} else if (xPlayer.isRegistered()) {
xAuthMessages.send("regErrRegistered", player);
return true;
- } else if (!xAuthSettings.allowMultiple && plugin.getDataManager().isHostUsed(Util.getHostFromPlayer(player))) {
+ } else if (!xAuthSettings.allowMultiple && DbUtil.isHostUsed(Util.getHostFromPlayer(player))) {
xAuthMessages.send("regErrMultiple", player);
return true;
}
diff --git a/src/main/java/com/cypherx/xauth/commands/xAuthCommand.java b/src/main/java/com/cypherx/xauth/commands/xAuthCommand.java
index 8901133..1694d5c 100644
--- a/src/main/java/com/cypherx/xauth/commands/xAuthCommand.java
+++ b/src/main/java/com/cypherx/xauth/commands/xAuthCommand.java
@@ -14,18 +14,16 @@ import com.cypherx.xauth.Util;
import com.cypherx.xauth.xAuth;
import com.cypherx.xauth.xAuthLog;
import com.cypherx.xauth.xAuthMessages;
-import com.cypherx.xauth.xAuthPermissions;
import com.cypherx.xauth.xAuthPlayer;
import com.cypherx.xauth.xAuthSettings;
-import com.cypherx.xauth.datamanager.DataManager;
+import com.cypherx.xauth.database.DbUtil;
+import com.cypherx.xauth.plugins.xPermissions;
public class xAuthCommand implements CommandExecutor {
private final xAuth plugin;
- private DataManager dataManager;
public xAuthCommand(xAuth plugin) {
this.plugin = plugin;
- this.dataManager = plugin.getDataManager();
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
@@ -72,7 +70,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.register")) {
+ if (!xPermissions.has(player, "xauth.admin.register")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 3) {
@@ -83,7 +81,7 @@ public class xAuthCommand implements CommandExecutor {
String targetName = args[1];
String password = args[2];
String email = (args.length > 3 ? args[3] : null);
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (xPlayer.isRegistered()) {
xAuthMessages.send("admnRegRegistered", player, xPlayer.getPlayer());
@@ -92,7 +90,7 @@ public class xAuthCommand implements CommandExecutor {
Account account = new Account(targetName, Util.encrypt(password), email);
xPlayer.setAccount(account);
- dataManager.saveAccount(account);
+ DbUtil.saveAccount(account);
xAuthMessages.send("admnRegSuccess", player, xPlayer.getPlayer());
xAuthLog.info(player.getName() + " has registered an account for " + targetName);
@@ -105,7 +103,7 @@ public class xAuthCommand implements CommandExecutor {
String targetName = args[1];
String password = args[2];
String email = (args.length > 3 ? args[3] : null);
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (xPlayer.isRegistered()) {
xAuthLog.info(targetName + " is already registered!");
@@ -114,7 +112,7 @@ public class xAuthCommand implements CommandExecutor {
Account account = new Account(targetName, Util.encrypt(password), email);
xPlayer.setAccount(account);
- dataManager.saveAccount(account);
+ DbUtil.saveAccount(account);
xAuthLog.info("Account successfully created for: " + targetName);
}
@@ -126,7 +124,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.changepw")) {
+ if (!xPermissions.has(player, "xauth.admin.changepw")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 3) {
@@ -135,7 +133,7 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.isRegistered()) {
xAuthMessages.send("admnCpwRegistered", player, xPlayer.getPlayer());
@@ -155,7 +153,7 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.isRegistered()) {
xAuthLog.info("This player is not registered!");
@@ -176,7 +174,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.logout")) {
+ if (!xPermissions.has(player, "xauth.admin.logout")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 2) {
@@ -185,7 +183,7 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.hasSession()) {
xAuthMessages.send("admnLogoutLogged", player, xPlayer.getPlayer());
@@ -205,7 +203,7 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.hasSession()) {
xAuthLog.info(targetName + " is not logged in!");
@@ -226,7 +224,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.unregister")) {
+ if (!xPermissions.has(player, "xauth.admin.unregister")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 2) {
@@ -235,14 +233,14 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.isRegistered()) {
xAuthMessages.send("admnUnregRegistered", player, xPlayer.getPlayer());
return true;
}
- dataManager.deleteAccount(xPlayer);
+ DbUtil.deleteAccount(xPlayer);
Player target = xPlayer.getPlayer();
if (target != null) {
@@ -260,14 +258,14 @@ public class xAuthCommand implements CommandExecutor {
}
String targetName = args[1];
- xAuthPlayer xPlayer = dataManager.getPlayer(targetName);
+ xAuthPlayer xPlayer = plugin.getPlayer(targetName);
if (!xPlayer.isRegistered()) {
xAuthLog.info(targetName + " is not registered!");
return true;
}
- dataManager.deleteAccount(xPlayer);
+ DbUtil.deleteAccount(xPlayer);
Player target = xPlayer.getPlayer();
if (target != null) {
@@ -286,7 +284,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.location")) {
+ if (!xPermissions.has(player, "xauth.admin.location")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 2 || !(args[1].equals("set") || args[1].equals("remove"))) {
@@ -295,19 +293,43 @@ public class xAuthCommand implements CommandExecutor {
}
String action = args[1];
+ Boolean global = (args.length > 2 && args[2].equals("global") ? true : false);
if (action.equals("set")) {
- dataManager.setTeleLocation(new TeleLocation(player.getLocation()));
- xAuthMessages.send("admnLocSetSuccess", player);
- } else {
- TeleLocation tLoc = dataManager.getTeleLocation(player.getWorld().getName());
- if (tLoc == null) {
- xAuthMessages.send("admnLocRmvNo", player);
+ if (!global && player.getWorld().getUID().equals(plugin.getGlobalUID())) {
+ xAuthMessages.send("admnLocSetErrGlobal", player);
return true;
}
- dataManager.removeTeleLocation(tLoc);
- xAuthMessages.send("admnLocRmvSuccess", player);
+ plugin.setTeleLocation(new TeleLocation(player.getLocation(), global));
+
+ if (global)
+ xAuthMessages.send("admnLocSetGlobalSuccess", player);
+ else
+ xAuthMessages.send("admnLocSetSuccess", player);
+ } else {
+ if (global) {
+ TeleLocation tLoc = plugin.getTeleLocation(plugin.getGlobalUID());
+ if (tLoc == null) {
+ xAuthMessages.send("admnLocRmvGlobalNo", player);
+ return true;
+ }
+
+ plugin.removeTeleLocation(tLoc);
+ xAuthMessages.send("admnLocRmvGlobalSuccess", player);
+ } else {
+ TeleLocation tLoc = plugin.getTeleLocation(player.getWorld().getUID());
+ if (tLoc == null) {
+ xAuthMessages.send("admnLocRmvNo", player);
+ return true;
+ } else if (tLoc.getUID().equals(plugin.getGlobalUID())) {
+ xAuthMessages.send("admnLocRmvErrGlobal", player);
+ return true;
+ }
+
+ plugin.removeTeleLocation(tLoc);
+ xAuthMessages.send("admnLocRmvSuccess", player);
+ }
}
}
@@ -318,7 +340,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (!xAuthPermissions.has(player, "xauth.admin.config")) {
+ if (!xPermissions.has(player, "xauth.admin.config")) {
xAuthMessages.send("admnPermission", player);
return true;
} else if (args.length < 2) {
@@ -442,7 +464,7 @@ public class xAuthCommand implements CommandExecutor {
if (sender instanceof Player) {
Player player = (Player)sender;
- if (xAuthPermissions.has(player, "xauth.admin.reload")) {
+ if (xPermissions.has(player, "xauth.admin.reload")) {
plugin.reload();
xAuthMessages.send("admnReloadSuccess", player);
xAuthLog.info("Reloaded by " + player.getName());
diff --git a/src/main/java/com/cypherx/xauth/database/Database.java b/src/main/java/com/cypherx/xauth/database/Database.java
new file mode 100644
index 0000000..3830b4a
--- /dev/null
+++ b/src/main/java/com/cypherx/xauth/database/Database.java
@@ -0,0 +1,177 @@
+package com.cypherx.xauth.database;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import com.cypherx.xauth.xAuthLog;
+import com.cypherx.xauth.xAuthSettings;
+
+public class Database {
+ private static DBMS dbms = DBMS.H2;
+ private static Connection connection = null;
+
+ public static void connect() {
+ String driver = "";
+ String username = "sa";
+ String password = "";
+
+ switch (dbms) {
+ case H2:
+ driver = "org.h2.Driver";
+ break;
+ case MYSQL:
+ driver = "com.mysql.jdbc.Driver";
+ username = xAuthSettings.mysqlUser;
+ password = xAuthSettings.mysqlPass;
+ break;
+ }
+
+ try {
+ Class.forName(driver);
+ connection = DriverManager.getConnection(getConnString(), username, password);
+ xAuthLog.info("Connection to database established!");
+ } catch (ClassNotFoundException e) {
+ xAuthLog.severe("Missing database library!");
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not connect to database!", e);
+ }
+ }
+
+ private static String getConnString() {
+ switch (dbms) {
+ case H2:
+ return "jdbc:h2:plugins" + File.separator + "xAuth" + File.separator + "xAuth;IGNORECASE=TRUE";
+ case MYSQL:
+ return "jdbc:mysql://" + xAuthSettings.mysqlHost + ":" + xAuthSettings.mysqlPort + "/" + xAuthSettings.mysqlDb + "?zeroDateTimeBehavior=convertToNull";
+ default:
+ return "";
+ }
+ }
+
+ public static ResultSet queryRead(String sql, Object... params) {
+ if (!isConnected())
+ connect();
+
+ PreparedStatement stmt = null;
+
+ try {
+ stmt = connection.prepareStatement(sql);
+
+ for (int i = 0; i < params.length; i++)
+ stmt.setObject(i + 1, params[i]);
+
+ return stmt.executeQuery();
+ } catch (SQLException e) {
+ xAuthLog.severe("SQL query failure [read] (" + sql + ")", e);
+ }
+
+ return null;
+ }
+
+ public static int queryWrite(String sql, Object... params) {
+ if (!isConnected())
+ connect();
+
+ PreparedStatement stmt = null;
+ int result = -1;
+
+ try {
+ stmt = connection.prepareStatement(sql);
+
+ for (int i = 0; i < params.length; i++)
+ stmt.setObject(i + 1, params[i]);
+
+ result = stmt.executeUpdate();
+ } catch (SQLException e) {
+ xAuthLog.severe("SQL query failure [write] (" + sql + ")", e);
+ }
+
+ return result;
+ }
+
+ public static void queryBatch(PreparedStatement stmt) {
+ try {
+ stmt.executeBatch();
+ } catch (SQLException e) {
+ xAuthLog.severe("SQL query failure [batch]", e);
+ }
+ }
+
+ public static int lastInsertId() {
+ if (!isConnected())
+ connect();
+
+ int lastInsertId = -1;
+ ResultSet rs = queryRead("SELECT LAST_INSERT_ID()");
+
+ try {
+ if (rs.next())
+ lastInsertId = rs.getInt(1);
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not retrieve last insert ID!", e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return lastInsertId;
+ }
+
+ public static void printStats() {
+ String sql = "SELECT" +
+ " (SELECT COUNT(*) FROM `" + xAuthSettings.tblAccount + "`) AS accounts," +
+ " (SELECT COUNT(*) FROM `" + xAuthSettings.tblSession + "`) AS sessions";
+ ResultSet rs = queryRead(sql);
+
+ try {
+ if (rs.next())
+ xAuthLog.info("Accounts: " + rs.getInt("accounts") + ", Sessions: " + rs.getInt("sessions"));
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not fetch xAuth statistics!", e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+ }
+
+ public static void close() {
+ try {
+ if (connection != null)
+ connection.close();
+ } catch (SQLException e) {}
+ }
+
+ public static boolean isConnected() {
+ try {
+ if (connection == null || connection.isClosed())
+ return false;
+ } catch (SQLException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public static Connection getConnection() {
+ return connection;
+ }
+
+ public static void setDBMS(DBMS newDBMS) {
+ dbms = newDBMS;
+ }
+
+ public static DBMS getDBMS() {
+ return dbms;
+ }
+
+ public enum DBMS {
+ H2,
+ MYSQL
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/database/DbUpdate.java b/src/main/java/com/cypherx/xauth/database/DbUpdate.java
new file mode 100644
index 0000000..1667167
--- /dev/null
+++ b/src/main/java/com/cypherx/xauth/database/DbUpdate.java
@@ -0,0 +1,148 @@
+package com.cypherx.xauth.database;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.net.URLDecoder;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+import com.cypherx.xauth.Util;
+import com.cypherx.xauth.xAuth;
+import com.cypherx.xauth.xAuthLog;
+import com.cypherx.xauth.xAuthSettings;
+
+public class DbUpdate {
+ private File fVersion = new File(xAuth.dataFolder + File.separator + "DBVERSION");
+ private int version; // Current database version
+ private int sqlVersion = 0; // Version of the .sql files
+ private Map sqlFiles = new HashMap();
+
+ public DbUpdate() {
+ loadVersion();
+ loadSQLFiles();
+ }
+
+ public boolean checkVersion() {
+ return sqlVersion <= version;
+ }
+
+ // Updates the database to the latest version
+ public void update() {
+ update(sqlVersion);
+ }
+
+ // Updates the database to the specified version
+ public void update(int version) {
+ if (version <= this.version)
+ return;
+
+ for (int i = this.version + 1; i <= version; i++) {
+ String sql = Util.getResourceAsString("/" + sqlFiles.get(i));
+ sql = sql.replace("{TABLE_ACCOUNT}", xAuthSettings.tblAccount);
+ sql = sql.replace("{TABLE_SESSION}", xAuthSettings.tblSession);
+ sql = sql.replace("{TABLE_LOCATION}", xAuthSettings.tblLocation);
+ sql = sql.replace("{TABLE_STRIKE}", xAuthSettings.tblStrike);
+ sql = sql.replace("{TABLE_INVENTORY}", xAuthSettings.tblInventory);
+
+ String[] queries = sql.split(";");
+ for (int j = 0; j < queries.length; j++) {
+ String query = queries[j].trim();
+ if (query.isEmpty())
+ continue;
+
+ Database.queryWrite(query);
+ }
+ }
+
+ updateVersionFile(version);
+ }
+
+ private void loadVersion() {
+ BufferedReader reader = null;
+
+ try {
+ reader = new BufferedReader(new FileReader(fVersion));
+ version = Integer.parseInt(reader.readLine());
+ } catch (FileNotFoundException e) {
+ createVersionFile();
+ version = 0;
+ } catch (IOException e) {
+ xAuthLog.severe("Could not load database version from file!", e);
+ } finally {
+ try {
+ if (reader != null)
+ reader.close();
+ } catch (IOException e) {}
+ }
+ }
+
+ private void loadSQLFiles() {
+ String jarPath = "plugins" + File.separator + "xAuth.jar";
+ String sqlPath = "";
+
+ if (xAuthSettings.datasource.equals("mysql"))
+ sqlPath = "sql/mysql/";
+ else
+ sqlPath = "sql/h2/";
+
+ try {
+ JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
+ Enumeration entries = jar.entries();
+
+ while(entries.hasMoreElements()) {
+ String name = entries.nextElement().getName();
+ if (name.startsWith(sqlPath) && name.endsWith(".sql")) {
+ int version = Integer.parseInt(name.substring(name.lastIndexOf("/") + 1, name.indexOf("_")));
+
+ if (sqlVersion < version)
+ sqlVersion = version;
+
+ sqlFiles.put(version, name);
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void createVersionFile() {
+ BufferedWriter writer = null;
+
+ try {
+ fVersion.createNewFile();
+ writer = new BufferedWriter(new FileWriter(fVersion));
+ writer.write("0");
+ } catch (IOException e) {
+ xAuthLog.severe("Could not create database version file!", e);
+ } finally {
+ try {
+ if (writer != null)
+ writer.close();
+ } catch (IOException e) {}
+ }
+ }
+
+ private void updateVersionFile(int version) {
+ BufferedWriter writer = null;
+
+ try {
+ writer = new BufferedWriter(new FileWriter(fVersion));
+ writer.write(Integer.toString(version));
+ } catch (IOException e) {
+ xAuthLog.severe("Could not update database version file!", e);
+ } finally {
+ try {
+ if (writer != null)
+ writer.close();
+ } catch (IOException e) {}
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/database/DbUtil.java b/src/main/java/com/cypherx/xauth/database/DbUtil.java
new file mode 100644
index 0000000..abcc55d
--- /dev/null
+++ b/src/main/java/com/cypherx/xauth/database/DbUtil.java
@@ -0,0 +1,349 @@
+package com.cypherx.xauth.database;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.PlayerInventory;
+
+import com.cypherx.xauth.Account;
+import com.cypherx.xauth.Session;
+import com.cypherx.xauth.StrikeBan;
+import com.cypherx.xauth.TeleLocation;
+import com.cypherx.xauth.Util;
+import com.cypherx.xauth.xAuthLog;
+import com.cypherx.xauth.xAuthPlayer;
+import com.cypherx.xauth.xAuthSettings;
+import com.cypherx.xauth.database.Database.DBMS;
+
+public class DbUtil {
+ /* START ACCOUNT METHODS */
+ public static void saveAccount(Account account) {
+ if (account.getId() == 0)
+ insertAccount(account);
+ else
+ updateAccount(account);
+ }
+
+ private static void insertAccount(Account account) {
+ String sql = "INSERT INTO `" + xAuthSettings.tblAccount + "`" +
+ " (`playername`, `password`, `email`, `registerdate`, `registerip`, `lastlogindate`, `lastloginip`, `active`)" +
+ " VALUES" +
+ " (?, ?, ?, ?, ?, ?, ?, ?)";
+ Database.queryWrite(sql, account.getPlayerName(), account.getPassword(), account.getEmail(),
+ account.getRegisterDate(), account.getRegisterHost(), account.getLastLoginDate(),
+ account.getLastLoginHost(), account.getActive());
+ account.setId(Database.lastInsertId());
+ }
+
+ private static void updateAccount(Account account) {
+ String sql = "UPDATE `" + xAuthSettings.tblAccount + "`" +
+ " SET" +
+ " `playername` = ?," +
+ "`password` = ?," +
+ "`email` = ?," +
+ "`registerdate` = ?," +
+ "`registerip` = ?," +
+ "`lastlogindate` = ?," +
+ "`lastloginip` = ?," +
+ "`active` = ?" +
+ " WHERE id = ?";
+
+ Database.queryWrite(sql, account.getPlayerName(), account.getPassword(), account.getEmail(),
+ account.getRegisterDate(), account.getRegisterHost(), account.getLastLoginDate(),
+ account.getLastLoginHost(), account.getActive(), account.getId());
+ }
+
+ public static void insertAccounts(List accounts) {
+ String sql = "INSERT INTO `" + xAuthSettings.tblAccount + "` (`playername`, `password`) VALUES (?, ?)";
+ Account account;
+
+ try {
+ PreparedStatement stmt = Database.getConnection().prepareStatement(sql);
+
+ for (int i = 0; i < accounts.size(); i++) {
+ account = accounts.get(i);
+ stmt.setString(1, account.getPlayerName());
+ stmt.setString(2, account.getPassword());
+ stmt.addBatch();
+ }
+
+ Database.queryBatch(stmt);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void deleteAccount(xAuthPlayer xPlayer) {
+ String sql = "DELETE FROM `" + xAuthSettings.tblAccount + "` WHERE `id` = ?";
+ Database.queryWrite(sql, xPlayer.getAccount().getId());
+ xPlayer.setAccount(null);
+ xPlayer.setSession(null);
+ }
+ /* END ACCOUNT METHODS */
+
+ /* START SESSION METHODS */
+ public static void insertSession(Session session) {
+ String sql = "INSERT INTO `" + xAuthSettings.tblSession + "` VALUES (?, ?, ?)";
+ Database.queryWrite(sql, session.getAccountId(), session.getHost(), session.getLoginTime());
+ }
+
+ public static void deleteSession(xAuthPlayer xPlayer) {
+ String sql = "DELETE FROM `" + xAuthSettings.tblSession + "` WHERE `accountid` = ?";
+ Database.queryWrite(sql, xPlayer.getSession().getAccountId());
+ xPlayer.setSession(null);
+ }
+ /* END SESSION METHODS */
+
+ /* START LOCATION METHODS */
+ public static void insertTeleLocation(TeleLocation teleLocation) {
+ String sql = "INSERT INTO `" + xAuthSettings.tblLocation + "` VALUES (?, ?, ?, ?, ?, ?, ?)";
+ Database.queryWrite(sql, teleLocation.getUID().toString(), teleLocation.getX(), teleLocation.getY(), teleLocation.getZ(),
+ teleLocation.getYaw(), teleLocation.getPitch(), teleLocation.getGlobal());
+ }
+
+ public static void updateTeleLocation(TeleLocation teleLocation) {
+ String sql = "UPDATE `" + xAuthSettings.tblLocation + "` " +
+ "SET " +
+ "`x` = ?, " +
+ "`y` = ?, " +
+ "`z` = ?, " +
+ "`yaw` = ?, " +
+ "`pitch` = ?, " +
+ "`global` = ? " +
+ "WHERE `uid` = ?";
+ Database.queryWrite(sql, teleLocation.getX(), teleLocation.getY(), teleLocation.getZ(), teleLocation.getYaw(),
+ teleLocation.getPitch(), teleLocation.getGlobal(), teleLocation.getUID().toString());
+ }
+
+ public static void deleteTeleLocation(TeleLocation teleLocation) {
+ String sql = "DELETE FROM `" + xAuthSettings.tblLocation + "` WHERE `uid` = ?";
+ Database.queryWrite(sql, teleLocation.getUID().toString());
+ }
+ /* END LOCATION METHODS */
+
+ /* START STRIKE METHODS */
+ public static StrikeBan loadStrikeBan(String host) {
+ String sql = "SELECT * FROM `" + xAuthSettings.tblStrike + "` WHERE `host` = ?";
+ ResultSet rs = Database.queryRead(sql, host);
+ StrikeBan ban = null;
+
+ try {
+ if (rs.next()) {
+ ban = new StrikeBan();
+ ban.setHost(rs.getString(host));
+ ban.setBanTime(rs.getTimestamp("bantime"));
+ }
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not load StrikeBan for host: " + host, e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return ban;
+ }
+
+ public static void insertStrikeBan(StrikeBan ban) {
+ String sql = "INSERT INTO `" + xAuthSettings.tblStrike + "` VALUES (?, ?)";
+ Database.queryWrite(sql, ban.getHost(), ban.getBanTime());
+ }
+
+ public static void deleteStrikeBan(StrikeBan ban) {
+ String sql = "DELETE FROM `" + xAuthSettings.tblStrike + "` WHERE `host` = ?";
+ Database.queryWrite(sql, ban.getHost());
+ }
+ /* END STRIKE METHODS */
+
+ /* START INVENTORY METHODS */
+ public static ItemStack[] getInventory(xAuthPlayer xPlayer) {
+ String sql = "SELECT * FROM `" + xAuthSettings.tblInventory + "` WHERE `playername` = ?";
+ ResultSet rs = Database.queryRead(sql, xPlayer.getPlayerName());
+
+ try {
+ if (rs.next()) {
+ int[] itemid = Util.stringToInt(rs.getString("itemid").split(","));
+ int[] amount = Util.stringToInt(rs.getString("amount").split(","));
+ int[] durability = Util.stringToInt(rs.getString("durability").split(","));
+ ItemStack[] inv = new ItemStack[itemid.length];
+
+ for (int i = 0; i < inv.length; i++)
+ inv[i] = new ItemStack(itemid[i], amount[i], (short)durability[i]);
+
+ return inv;
+ }
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not load inventory for player: " + xPlayer.getPlayerName(), e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return null;
+ }
+
+ public static void insertInventory(xAuthPlayer xPlayer) {
+ String sql = "SELECT * FROM `" + xAuthSettings.tblInventory + "` WHERE `playername` = ?";
+ ResultSet rs = Database.queryRead(sql, xPlayer.getPlayerName());
+
+ try {
+ if (rs.next())
+ return;
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not check inventory for player: " + xPlayer.getPlayerName(), e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ PlayerInventory inv = xPlayer.getPlayer().getInventory();
+ StringBuilder sbItems = new StringBuilder();
+ StringBuilder sbAmount = new StringBuilder();
+ StringBuilder sbDurability = new StringBuilder();
+
+ for (ItemStack item : inv.getContents()) {
+ int itemid = 0;
+ int amount = 0;
+ short durability = 0;
+
+ if (item != null) {
+ itemid = item.getTypeId();
+ amount = item.getAmount();
+ durability = item.getDurability();
+ }
+
+ sbItems.append(itemid + ",");
+ sbAmount.append(amount + ",");
+ sbDurability.append(durability + ",");
+ }
+
+ for (ItemStack item : inv.getArmorContents()) {
+ int itemid = 0;
+ int amount = 0;
+ short durability = 0;
+
+ if (item != null) {
+ itemid = item.getTypeId();
+ amount = item.getAmount();
+ durability = item.getDurability();
+ }
+
+ sbItems.append(itemid + ",");
+ sbAmount.append(amount + ",");
+ sbDurability.append(durability + ",");
+ }
+
+ sbItems.deleteCharAt(sbItems.lastIndexOf(","));
+ sbAmount.deleteCharAt(sbAmount.lastIndexOf(","));
+ sbDurability.deleteCharAt(sbDurability.lastIndexOf(","));
+
+ sql = "INSERT INTO `" + xAuthSettings.tblInventory + "` VALUES (?, ?, ?, ?)";
+ Database.queryWrite(sql, xPlayer.getPlayerName(), sbItems.toString(), sbAmount.toString(), sbDurability.toString());
+ }
+
+ public static void deleteInventory(xAuthPlayer xPlayer) {
+ String sql = "DELETE FROM `" + xAuthSettings.tblInventory + "` WHERE `playername` = ?";
+ Database.queryWrite(sql, xPlayer.getPlayerName());
+ }
+ /* END INVENTORY FUNCTIONS */
+ public static xAuthPlayer getPlayerFromDb(String playerName) {
+ xAuthPlayer xPlayer = null;
+ String sql = "SELECT a.*, s.*" +
+ " FROM `" + xAuthSettings.tblAccount + "` a" +
+ " LEFT JOIN `" + xAuthSettings.tblSession + "` s" +
+ " ON a.id = s.accountid" +
+ " WHERE `playername` = ?";
+ ResultSet rs = Database.queryRead(sql, playerName);
+
+ try {
+ if (rs.next())
+ xPlayer = new xAuthPlayer(playerName, Util.buildAccount(rs), Util.buildSession(rs));
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not load player: " + playerName, e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return xPlayer;
+ }
+
+ public static xAuthPlayer reloadPlayer(xAuthPlayer xPlayer) {
+ String sql = "SELECT a.*, s.*" +
+ " FROM `" + xAuthSettings.tblAccount + "` a" +
+ " LEFT JOIN `" + xAuthSettings.tblSession + "` s" +
+ " ON a.id = s.accountid" +
+ " WHERE `playername` = ?";
+ ResultSet rs = Database.queryRead(sql, xPlayer.getPlayerName());
+
+ try {
+ if (rs.next()) {
+ xPlayer.setAccount(Util.buildAccount(rs));
+ xPlayer.setSession(Util.buildSession(rs));
+ }
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not reload player: " + xPlayer.getPlayerName(), e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return xPlayer;
+ }
+
+ public static int getActive(String playerName) {
+ String sql = "SELECT `active` FROM `" + xAuthSettings.tblAccount + "` WHERE `playername` = ?";
+ ResultSet rs = Database.queryRead(sql, playerName);
+
+ try {
+ if (rs.next())
+ return rs.getInt("active");
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not check active status of player: " + playerName, e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return 0;
+ }
+
+ public static void deleteExpiredSessions() {
+ String sql;
+
+ if (Database.getDBMS() == DBMS.H2)
+ sql = "DELETE FROM `" + xAuthSettings.tblSession + "`" +
+ " WHERE NOW() > DATEADD('SECOND', " + xAuthSettings.sessionLength + ", `logintime`)";
+ else
+ sql = "DELETE FROM `" + xAuthSettings.tblSession + "`" +
+ " WHERE NOW() > ADDDATE(`logintime`, INTERVAL " + xAuthSettings.sessionLength + " SECOND)";
+
+ Database.queryWrite(sql);
+ }
+
+ public static boolean isHostUsed(String host) {
+ String sql = "SELECT * FROM `" + xAuthSettings.tblAccount + "` WHERE `registerip` = ?";
+ ResultSet rs = Database.queryRead(sql, host);
+
+ try {
+ if (rs.next())
+ return true;
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not check if IP address has been used!", e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/datamanager/DataManager.java b/src/main/java/com/cypherx/xauth/datamanager/DataManager.java
deleted file mode 100644
index a62777c..0000000
--- a/src/main/java/com/cypherx/xauth/datamanager/DataManager.java
+++ /dev/null
@@ -1,829 +0,0 @@
-package com.cypherx.xauth.datamanager;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.PlayerInventory;
-
-import com.cypherx.xauth.Account;
-import com.cypherx.xauth.Session;
-import com.cypherx.xauth.StrikeBan;
-import com.cypherx.xauth.TeleLocation;
-import com.cypherx.xauth.Util;
-import com.cypherx.xauth.xAuth;
-import com.cypherx.xauth.xAuthLog;
-import com.cypherx.xauth.xAuthPlayer;
-import com.cypherx.xauth.xAuthSettings;
-
-public class DataManager {
- private Connection connection = null;
- private Statement stmt = null;
- private PreparedStatement prepStmt = null;
- private ResultSet rs = null;
-
- private ConcurrentHashMap playerCache = new ConcurrentHashMap();
- private ConcurrentHashMap teleLocations = new ConcurrentHashMap();
-
- public DataManager() {
- connect();
- }
-
- private void connect() {
- if (xAuthSettings.datasource.equals("mysql"))
- connectMySQL();
- else
- connectH2();
- }
-
- private void connectMySQL() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + xAuthSettings.mysqlHost + ":" + xAuthSettings.mysqlPort + "/" +
- xAuthSettings.mysqlDb + "?zeroDateTimeBehavior=convertToNull", xAuthSettings.mysqlUser, xAuthSettings.mysqlPass);
- stmt = connection.createStatement();
- xAuthLog.info("Connection to MySQL server established!");
- } catch (ClassNotFoundException e) {
- xAuthLog.severe("Missing MySQL library!", e);
- } catch (SQLException e) {
- xAuthLog.severe("Could not connect to MySQL server!", e);
- }
- }
-
- private void connectH2() {
- if (!xAuthSettings.datasource.equals("default"))
- System.out.println("[" + xAuth.desc.getName() + "] Unknown datasource '" + xAuthSettings.datasource + "' - Using default (H2)");
-
- try {
- Class.forName("org.h2.Driver");
- connection = DriverManager.getConnection("jdbc:h2:" + xAuth.dataFolder.toString() +
- System.getProperty("file.separator") + "xAuth;IGNORECASE=TRUE", "sa", "");
- stmt = connection.createStatement();
- xAuthLog.info("Connection to H2 database established!");
- } catch (ClassNotFoundException e) {
- xAuthLog.severe("Missing H2 library!", e);
- } catch (SQLException e) {
- xAuthLog.severe("Could not connect to H2 database!", e);
- }
- }
-
- public void runStartupTasks() {
- createTables();
- loadTeleLocations();
-
- String sql;
-
- if (xAuthSettings.datasource.equals("mysql")) {
- sql = "DELETE FROM `" + xAuthSettings.tblSession + "`" +
- "WHERE NOW() > ADDDATE(`logintime`, INTERVAL " + xAuthSettings.sessionLength + " SECOND)";
- } else {
- sql = "DELETE FROM `" + xAuthSettings.tblSession + "`" +
- "WHERE NOW() > DATEADD('SECOND', " + xAuthSettings.sessionLength + ", `logintime`)";
- }
-
- if (!isConnected())
- connect();
-
- // delete expired sessions
- try {
- stmt.executeUpdate(sql);
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete expired settings!", e);
- }
- }
-
- public void createTables() {
- if (!isConnected())
- connect();
-
- try {
- stmt.execute(
- "CREATE TABLE IF NOT EXISTS `" + xAuthSettings.tblAccount + "` (" +
- "`id` INT UNSIGNED NOT NULL AUTO_INCREMENT," +
- "`playername` VARCHAR(255) NOT NULL," +
- "`password` CHAR(255) NOT NULL," +
- "`email` VARCHAR(100) NULL," +
- "`registerdate` DATETIME NULL," +
- "`registerip` CHAR(15) NULL," +
- "`lastlogindate` DATETIME NULL," +
- "`lastloginip` CHAR(15) NULL," +
- "`active` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0," +
- "PRIMARY KEY(`id`)" +
- ")"
- );
-
- stmt.execute(
- "CREATE TABLE IF NOT EXISTS `" + xAuthSettings.tblSession + "` (" +
- "`accountid` INT UNSIGNED NOT NULL," +
- "`host` CHAR(15) NOT NULL," +
- "`logintime` DATETIME NOT NULL," +
- "PRIMARY KEY(`accountid`)," +
- "FOREIGN KEY (`accountid`) REFERENCES `" + xAuthSettings.tblAccount + "`(`id`) ON DELETE CASCADE" +
- ")"
- );
-
- stmt.execute(
- "CREATE TABLE IF NOT EXISTS `" + xAuthSettings.tblLocation + "` (" +
- "`worldname` VARCHAR(255) NOT NULL," +
- "`x` DOUBLE NOT NULL," +
- "`y` DOUBLE NOT NULL," +
- "`z` DOUBLE NOT NULL," +
- "`yaw` FLOAT NOT NULL," +
- "`pitch` FLOAT NOT NULL," +
- "PRIMARY KEY(`worldname`)" +
- ")"
- );
-
- stmt.execute(
- "CREATE TABLE IF NOT EXISTS `" + xAuthSettings.tblStrike + "` (" +
- "`host` CHAR(15) NOT NULL," +
- "`bantime` DATETIME NOT NULL," +
- "PRIMARY KEY(`host`)" +
- ")"
- );
-
- stmt.execute(
- "CREATE TABLE IF NOT EXISTS `" + xAuthSettings.tblInventory + "` (" +
- "`playername` VARCHAR(255) NOT NULL," +
- "`itemid` TEXT NOT NULL," +
- "`amount` TEXT NOT NULL," +
- "`durability` TEXT NOT NULL," +
- "PRIMARY KEY (`playername`)" +
- ")"
- );
- } catch (SQLException e) {
- xAuthLog.severe("Could not check/create database tables!", e);
- }
- }
-
- public void printStats() {
- if (!isConnected())
- connect();
-
- try {
- rs = stmt.executeQuery(
- "SELECT" +
- " (SELECT COUNT(*) FROM `" + xAuthSettings.tblAccount + "`) AS accounts," +
- " (SELECT COUNT(*) FROM `" + xAuthSettings.tblSession + "`) AS sessions"
- );
-
- if (rs.next())
- xAuthLog.info("Accounts: " + rs.getInt("accounts") + ", Sessions: " + rs.getInt("sessions"));
- } catch (SQLException e) {
- xAuthLog.severe("Could not fetch xAuth statistics!", e);
- }
- }
-
- public void insertInventory(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT *" +
- " FROM `" + xAuthSettings.tblInventory + "`" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, xPlayer.getPlayerName());
- rs = prepStmt.executeQuery();
-
- if (rs.next())
- return;
- } catch (SQLException e) {
- xAuthLog.severe("Could not check inventory for player: " + xPlayer.getPlayerName(), e);
- }
-
- PlayerInventory inv = xPlayer.getPlayer().getInventory();
- StringBuilder sbItems = new StringBuilder();
- StringBuilder sbAmount = new StringBuilder();
- StringBuilder sbDurability = new StringBuilder();
-
- for (ItemStack item : inv.getContents()) {
- int itemid = 0;
- int amount = 0;
- short durability = 0;
-
- if (item != null) {
- itemid = item.getTypeId();
- amount = item.getAmount();
- durability = item.getDurability();
- }
-
- sbItems.append(itemid + ",");
- sbAmount.append(amount + ",");
- sbDurability.append(durability + ",");
- }
-
- for (ItemStack item : inv.getArmorContents()) {
- int itemid = 0;
- int amount = 0;
- short durability = 0;
-
- if (item != null) {
- itemid = item.getTypeId();
- amount = item.getAmount();
- durability = item.getDurability();
- }
-
- sbItems.append(itemid + ",");
- sbAmount.append(amount + ",");
- sbDurability.append(durability + ",");
- }
-
- sbItems.deleteCharAt(sbItems.lastIndexOf(","));
- sbAmount.deleteCharAt(sbAmount.lastIndexOf(","));
- sbDurability.deleteCharAt(sbDurability.lastIndexOf(","));
-
- try {
- prepStmt = connection.prepareStatement(
- "INSERT INTO `" + xAuthSettings.tblInventory + "`" +
- " VALUES" +
- "(?, ?, ?, ?)"
- );
- prepStmt.setString(1, xPlayer.getPlayerName());
- prepStmt.setString(2, sbItems.toString());
- prepStmt.setString(3, sbAmount.toString());
- prepStmt.setString(4, sbDurability.toString());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not insert inventory for player: " + xPlayer.getPlayerName(), e);
- }
- }
-
- public ItemStack[] getInventory(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT *" +
- " FROM `" + xAuthSettings.tblInventory + "`" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, xPlayer.getPlayerName());
- rs = prepStmt.executeQuery();
-
- if (rs.next()) {
- int[] itemid = Util.stringToInt(rs.getString("itemid").split(","));
- int[] amount = Util.stringToInt(rs.getString("amount").split(","));
- int[] durability = Util.stringToInt(rs.getString("durability").split(","));
- ItemStack[] inv = new ItemStack[itemid.length];
-
- for (int i = 0; i < inv.length; i++)
- inv[i] = new ItemStack(itemid[i], amount[i], (short)durability[i]);
-
- return inv;
- }
- } catch (SQLException e) {
- xAuthLog.severe("Could not load inventory for player: " + xPlayer.getPlayerName(), e);
- }
-
- return null;
- }
-
- public void deleteInventory(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "DELETE FROM `" + xAuthSettings.tblInventory + "`" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, xPlayer.getPlayerName());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete inventory for player: " + xPlayer.getPlayerName(), e);
- }
- }
-
- public xAuthPlayer getPlayer(String playerName) {
- String lowPlayerName = playerName.toLowerCase();
-
- if (playerCache.containsKey(lowPlayerName))
- return playerCache.get(lowPlayerName);
-
- xAuthPlayer xPlayer = getPlayerFromDb(playerName);
- if (xPlayer == null)
- xPlayer = new xAuthPlayer(playerName);
-
- playerCache.put(lowPlayerName, xPlayer);
- return xPlayer;
- }
-
- public xAuthPlayer getPlayerJoin(String playerName) {
- String lowPlayerName = playerName.toLowerCase();
-
- if (playerCache.containsKey(lowPlayerName))
- return reloadPlayer(playerCache.get(lowPlayerName));
-
- xAuthPlayer xPlayer = getPlayerFromDb(playerName);
- if (xPlayer == null)
- xPlayer = new xAuthPlayer(playerName);
-
- playerCache.put(lowPlayerName, xPlayer);
- return xPlayer;
- }
-
- public xAuthPlayer getPlayerFromDb(String playerName) {
- if (!isConnected())
- connect();
-
- xAuthPlayer xPlayer = null;
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT a.*, s.*" +
- " FROM `" + xAuthSettings.tblAccount + "` a" +
- " LEFT JOIN `" + xAuthSettings.tblSession + "` s" +
- " ON a.id = s.accountid" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, playerName);
- rs = prepStmt.executeQuery();
-
- if (rs.next())
- xPlayer = new xAuthPlayer(playerName, buildAccount(rs), buildSession(rs));
- } catch (SQLException e) {
- xAuthLog.severe("Could not load player: " + playerName, e);
- }
-
- return xPlayer;
- }
-
- public xAuthPlayer reloadPlayer(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT a.*, s.*" +
- " FROM `" + xAuthSettings.tblAccount + "` a" +
- " LEFT JOIN `" + xAuthSettings.tblSession + "` s" +
- " ON a.id = s.accountid" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, xPlayer.getPlayerName());
- rs = prepStmt.executeQuery();
-
- if (rs.next()) {
- xPlayer.setAccount(buildAccount(rs));
- xPlayer.setSession(buildSession(rs));
- }
- } catch (SQLException e) {
- xAuthLog.severe("Could not reload player: " + xPlayer.getPlayerName(), e);
- }
-
- return xPlayer;
- }
-
- public int getActive(String playerName) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT `active`" +
- " FROM `" + xAuthSettings.tblAccount + "`" +
- " WHERE `playername` = ?"
- );
- prepStmt.setString(1, playerName);
- rs = prepStmt.executeQuery();
-
- if (rs.next())
- return rs.getInt("active");
- } catch (SQLException e) {
- xAuthLog.severe("Could not check active status of player: " + playerName, e);
- }
-
- return 0;
- }
-
- public void saveAccount(Account account) {
- if (account.getId() == 0)
- insertAccount(account);
- else
- updateAccount(account);
- }
-
- protected void insertAccount(Account account) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "INSERT INTO `" + xAuthSettings.tblAccount + "`" +
- " (`playername`, `password`, `email`, `registerdate`, `registerip`, `lastlogindate`, `lastloginip`, `active`)" +
- " VALUES" +
- " (?, ?, ?, ?, ?, ?, ?, ?)",
- Statement.RETURN_GENERATED_KEYS);
- prepStmt.setString(1, account.getPlayerName());
- prepStmt.setString(2, account.getPassword());
- prepStmt.setString(3, account.getEmail());
- prepStmt.setTimestamp(4, account.getRegisterDate());
- prepStmt.setString(5, account.getRegisterHost());
- prepStmt.setTimestamp(6, account.getLastLoginDate());
- prepStmt.setString(7, account.getLastLoginHost());
- prepStmt.setInt(8, account.getActive());
- prepStmt.executeUpdate();
-
- rs = prepStmt.getGeneratedKeys();
- if (rs.next())
- account.setId(rs.getInt(1));
- } catch (SQLException e) {
- xAuthLog.severe("Could not insert account for player: " + account.getPlayerName(), e);
- }
- }
-
- public void insertAccounts(List accounts) {
- if (!isConnected())
- connect();
-
- StringBuilder sb = new StringBuilder();
- Account account;
- sb.append("INSERT INTO `" + xAuthSettings.tblAccount + "` (`playername`, `password`) VALUES");
- sb.append(" (?, ?)");
-
- for (int i = 1; i < accounts.size(); i++)
- sb.append(", (?, ?)");
- sb.append(";");
-
- try {
- prepStmt = connection.prepareStatement(sb.toString());
- for (int i = 0, j = 1; j < accounts.size() * 2; i++, j += 2) {
- account = accounts.get(i);
- prepStmt.setString(j, account.getPlayerName());
- prepStmt.setString(j + 1, account.getPassword().toLowerCase());
- }
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- protected void updateAccount(Account account) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "UPDATE `" + xAuthSettings.tblAccount + "`" +
- " SET" +
- " `playername` = ?," +
- "`password` = ?," +
- "`email` = ?," +
- "`registerdate` = ?," +
- "`registerip` = ?," +
- "`lastlogindate` = ?," +
- "`lastloginip` = ?," +
- "`active` = ?" +
- " WHERE id = ?"
- );
- prepStmt.setString(1, account.getPlayerName());
- prepStmt.setString(2, account.getPassword());
- prepStmt.setString(3, account.getEmail());
- prepStmt.setTimestamp(4, account.getRegisterDate());
- prepStmt.setString(5, account.getRegisterHost());
- prepStmt.setTimestamp(6, account.getLastLoginDate());
- prepStmt.setString(7, account.getLastLoginHost());
- prepStmt.setInt(8, account.getActive());
- prepStmt.setInt(9, account.getId());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not update account for player: " + account.getPlayerName(), e);
- }
- }
-
- public void deleteAccount(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- Account account = xPlayer.getAccount();
-
- try {
- prepStmt = connection.prepareStatement(
- "DELETE FROM `" + xAuthSettings.tblAccount + "`" +
- " WHERE `id` = ?"
- );
- prepStmt.setInt(1, account.getId());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete account for player: " + xPlayer.getPlayerName(), e);
- }
-
- xPlayer.setAccount(null);
- xPlayer.setSession(null);
- }
-
- public void insertSession(Session session) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "INSERT INTO `" + xAuthSettings.tblSession + "`" +
- " VALUES" +
- " (?, ?, ?)",
- Statement.RETURN_GENERATED_KEYS);
- prepStmt.setInt(1, session.getAccountId());
- prepStmt.setString(2, session.getHost());
- prepStmt.setTimestamp(3, session.getLoginTime());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not insert session for account: " + session.getAccountId(), e);
- }
- }
-
- public void deleteSession(xAuthPlayer xPlayer) {
- if (!isConnected())
- connect();
-
- Session session = xPlayer.getSession();
-
- try {
- prepStmt = connection.prepareStatement(
- "DELETE FROM `" + xAuthSettings.tblSession + "`" +
- " WHERE `accountid` = ?"
- );
- prepStmt.setInt(1, session.getAccountId());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete session for player: " + xPlayer.getPlayerName(), e);
- }
-
- xPlayer.setSession(null);
- }
-
- public void loadTeleLocations() {
- if (!isConnected())
- connect();
-
- try {
- rs = stmt.executeQuery(
- "SELECT * " +
- "FROM `" + xAuthSettings.tblLocation + "`"
- );
-
- while (rs.next()) {
- TeleLocation teleLocation = new TeleLocation();
- teleLocation.setWorldName(rs.getString("worldname"));
- teleLocation.setX(rs.getDouble("x"));
- teleLocation.setY(rs.getDouble("y"));
- teleLocation.setZ(rs.getDouble("z"));
- teleLocation.setYaw(rs.getFloat("yaw"));
- teleLocation.setPitch(rs.getFloat("pitch"));
- teleLocations.put(teleLocation.getWorldName(), teleLocation);
- }
- } catch (SQLException e) {
- xAuthLog.severe("Could not load TeleLocations from database!", e);
- }
- }
-
- public void insertTeleLocation(TeleLocation teleLocation) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "INSERT INTO `" + xAuthSettings.tblLocation + "`" +
- " VALUES" +
- " (?, ?, ?, ?, ?, ?)"
- );
-
- prepStmt.setString(1, teleLocation.getWorldName());
- prepStmt.setDouble(2, teleLocation.getX());
- prepStmt.setDouble(3, teleLocation.getY());
- prepStmt.setDouble(4, teleLocation.getZ());
- prepStmt.setFloat(5, teleLocation.getYaw());
- prepStmt.setFloat(6, teleLocation.getPitch());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not insert TeleLocation for world: " + teleLocation.getWorldName(), e);
- }
- }
-
- public void updateTeleLocation(TeleLocation teleLocation) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "UPDATE `" + xAuthSettings.tblLocation + "`" +
- " SET " +
- "`x` = ?," +
- "`y` = ?," +
- "`z` = ?," +
- "`yaw` = ?," +
- "`pitch` = ?" +
- " WHERE `worldname` = ?"
- );
- prepStmt.setDouble(1, teleLocation.getX());
- prepStmt.setDouble(2, teleLocation.getY());
- prepStmt.setDouble(3, teleLocation.getZ());
- prepStmt.setFloat(4, teleLocation.getYaw());
- prepStmt.setFloat(5, teleLocation.getPitch());
- prepStmt.setString(6, teleLocation.getWorldName());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not update TeleLocation for world: " + teleLocation.getWorldName(), e);
- }
- }
-
- public void deleteTeleLocation(TeleLocation teleLocation) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "DELETE FROM `" + xAuthSettings.tblLocation + "`" +
- " WHERE `worldname` = ?"
- );
-
- prepStmt.setString(1, teleLocation.getWorldName());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete TeleLocation for world: " + teleLocation.getWorldName(), e);
- }
- }
-
- public StrikeBan loadStrikeBan(String host) {
- if (!isConnected())
- connect();
-
- StrikeBan ban = null;
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT * " +
- "FROM `" + xAuthSettings.tblStrike + "`" +
- " WHERE `host` = ?"
- );
-
- prepStmt.setString(1, host);
- rs = prepStmt.executeQuery();
-
- if (rs.next()) {
- ban = new StrikeBan();
- ban.setHost(rs.getString("host"));
- ban.setBanTime(rs.getTimestamp("bantime"));
- }
- } catch (SQLException e) {
- xAuthLog.severe("Could not load StrikeBan for host: " + host, e);
- }
-
- return ban;
- }
-
- public void insertStrikeBan(StrikeBan ban) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "INSERT INTO `" + xAuthSettings.tblStrike + "`" +
- " (`host`, `bantime`)" +
- " VALUES" +
- " (?, ?)"
- );
-
- prepStmt.setString(1, ban.getHost());
- prepStmt.setTimestamp(2, ban.getBanTime());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not insert StrikeBan for host: " + ban.getHost(), e);
- }
- }
-
- public void deleteStrikeBan(StrikeBan ban) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "DELETE FROM `" + xAuthSettings.tblStrike + "`" +
- " WHERE `host` = ?"
- );
-
- prepStmt.setString(1, ban.getHost());
- prepStmt.executeUpdate();
- } catch (SQLException e) {
- xAuthLog.severe("Could not delete StrikeBan for host: " + ban.getHost(), e);
- }
- }
-
- public boolean isHostUsed(String host) {
- if (!isConnected())
- connect();
-
- try {
- prepStmt = connection.prepareStatement(
- "SELECT `id`" +
- " FROM `" + xAuthSettings.tblAccount + "`" +
- " WHERE `registerip` = ?"
- );
- prepStmt.setString(1, host);
- rs = prepStmt.executeQuery();
-
- if (rs.next())
- return true;
- } catch (SQLException e) {
- xAuthLog.severe("Could not check if IP address has been used!", e);
- }
-
- return false;
- }
-
- public void close() {
- try {
- if (rs != null)
- rs.close();
- } catch (SQLException e) {}
-
- try {
- if (stmt != null)
- stmt.close();
- } catch (SQLException e) {}
-
- try {
- if (prepStmt != null)
- prepStmt.close();
- } catch (SQLException e) {}
-
- try {
- if (connection != null)
- connection.close();
- } catch (SQLException e) {}
- }
-
- private Account buildAccount(ResultSet rs) {
- Account account = null;
- try {
- account = new Account();
- account.setId(rs.getInt("id"));
- account.setPlayerName(rs.getString("playername"));
- account.setPassword(rs.getString("password"));
- account.setEmail(rs.getString("email"));
- account.setRegisterDate(rs.getTimestamp("registerdate"));
- account.setRegisterHost(rs.getString("registerip"));
- account.setLastLoginDate(rs.getTimestamp("lastlogindate"));
- account.setLastLoginHost(rs.getString("lastloginip"));
- account.setActive(rs.getInt("active"));
- } catch (SQLException e) {
- xAuthLog.severe("Error while building Account from ResultSet!", e);
- }
-
- return account;
- }
-
- private Session buildSession(ResultSet rs) {
- Session session = null;
- try {
- session = new Session();
- session.setAccountId(rs.getInt("accountid"));
-
- if (rs.wasNull()) // no session data in database
- return null;
-
- session.setHost(rs.getString("host"));
- session.setLoginTime(rs.getTimestamp("logintime"));
- } catch (SQLException e) {
- xAuthLog.severe("Error while building Session from ResultSet!", e);
- }
-
- return session;
- }
-
- public boolean isConnected() {
- try {
- if (connection == null || connection.isClosed())
- return false;
- } catch (SQLException e) {
- return false;
- }
-
- return true;
- }
-
- public TeleLocation getTeleLocation(String worldName) {
- return teleLocations.get(worldName);
- }
-
- public void setTeleLocation(TeleLocation teleLocation) {
- TeleLocation tOld = teleLocations.put(teleLocation.getWorldName(), teleLocation);
- if (tOld == null)
- insertTeleLocation(teleLocation);
- else
- updateTeleLocation(teleLocation);
- }
-
- public void removeTeleLocation(TeleLocation teleLocation) {
- teleLocations.remove(teleLocation.getWorldName());
- deleteTeleLocation(teleLocation);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/listeners/xAuthBlockListener.java b/src/main/java/com/cypherx/xauth/listeners/xAuthBlockListener.java
index 474ba5c..79a222d 100644
--- a/src/main/java/com/cypherx/xauth/listeners/xAuthBlockListener.java
+++ b/src/main/java/com/cypherx/xauth/listeners/xAuthBlockListener.java
@@ -26,7 +26,7 @@ public class xAuthBlockListener extends BlockListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrBreak && !xPlayer.isRegistered())
//return;
@@ -43,7 +43,7 @@ public class xAuthBlockListener extends BlockListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrPlace && !xPlayer.isRegistered())
//return;
diff --git a/src/main/java/com/cypherx/xauth/listeners/xAuthEntityListener.java b/src/main/java/com/cypherx/xauth/listeners/xAuthEntityListener.java
index a6c9332..cb60f4e 100644
--- a/src/main/java/com/cypherx/xauth/listeners/xAuthEntityListener.java
+++ b/src/main/java/com/cypherx/xauth/listeners/xAuthEntityListener.java
@@ -31,7 +31,7 @@ public class xAuthEntityListener extends EntityListener {
Entity entity = event.getEntity();
if (entity instanceof Player && ((Player)entity).isOnline()) { // player taking damage
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(((Player)entity).getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(((Player)entity).getName());
//if (!xAuthSettings.rstrDmgTaken && !xPlayer.isRegistered())
//return;
@@ -46,7 +46,7 @@ public class xAuthEntityListener extends EntityListener {
Entity damager = edbeEvent.getDamager();
if (damager instanceof Player) {
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(((Player)damager).getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(((Player)damager).getName());
//if (!xAuthSettings.rstrDmgGiven && !xPlayer.isRegistered())
//return;
@@ -67,7 +67,7 @@ public class xAuthEntityListener extends EntityListener {
Entity target = event.getTarget();
if (target instanceof Player) {
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(((Player)target).getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(((Player)target).getName());
//if (!xAuthSettings.rstrMobTarget && !xPlayer.isRegistered())
//return;
diff --git a/src/main/java/com/cypherx/xauth/listeners/xAuthPlayerListener.java b/src/main/java/com/cypherx/xauth/listeners/xAuthPlayerListener.java
index 377eb3b..18fc98c 100644
--- a/src/main/java/com/cypherx/xauth/listeners/xAuthPlayerListener.java
+++ b/src/main/java/com/cypherx/xauth/listeners/xAuthPlayerListener.java
@@ -15,6 +15,8 @@ import com.cypherx.xauth.xAuth;
import com.cypherx.xauth.xAuthMessages;
import com.cypherx.xauth.xAuthPlayer;
import com.cypherx.xauth.xAuthSettings;
+import com.cypherx.xauth.database.DbUtil;
+import com.cypherx.xauth.plugins.xBukkitContrib;
public class xAuthPlayerListener extends PlayerListener {
private final xAuth plugin;
@@ -54,12 +56,10 @@ public class xAuthPlayerListener extends PlayerListener {
public void onPlayerJoin(PlayerJoinEvent event) {
final Player player = event.getPlayer();
-
- //Easyban fix?
if (player == null)
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayerJoin(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayerJoin(player.getName());
boolean isRegistered = xPlayer.isRegistered();
if (!xPlayer.isAuthenticated() && (isRegistered || (!isRegistered && xPlayer.mustRegister()))) {
@@ -93,14 +93,14 @@ public class xAuthPlayerListener extends PlayerListener {
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
if (xPlayer.isGuest())
plugin.removeGuest(xPlayer);
else if (xPlayer.hasSession()) {
Session session = xPlayer.getSession();
if (session.isExpired())
- plugin.getDataManager().deleteSession(xPlayer);
+ DbUtil.deleteSession(xPlayer);
}
}
@@ -108,7 +108,7 @@ public class xAuthPlayerListener extends PlayerListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrChat && !xPlayer.isRegistered())
//return;
@@ -125,12 +125,12 @@ public class xAuthPlayerListener extends PlayerListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrCommands && !xPlayer.isRegistered())
//return;
- if (xPlayer.isGuest()) {
+ if (xPlayer.isGuest() && !xBukkitContrib.isVersionCommand(event.getMessage())) {
String command = event.getMessage().split(" ")[0].replaceFirst("/", "");
if (xAuthSettings.allowedCmds.contains(command))
@@ -148,7 +148,7 @@ public class xAuthPlayerListener extends PlayerListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrInteract && !xPlayer.isRegistered())
//return;
@@ -200,7 +200,7 @@ public class xAuthPlayerListener extends PlayerListener {
return;
Player player = event.getPlayer();
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(player.getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(player.getName());
//if (!xAuthSettings.rstrMovement && !xPlayer.isRegistered())
//return;
@@ -220,7 +220,7 @@ public class xAuthPlayerListener extends PlayerListener {
if (event.isCancelled())
return;
- xAuthPlayer xPlayer = plugin.getDataManager().getPlayer(event.getPlayer().getName());
+ xAuthPlayer xPlayer = plugin.getPlayer(event.getPlayer().getName());
//if (!xAuthSettings.rstrPickup && !xPlayer.isRegistered())
//return;
diff --git a/src/main/java/com/cypherx/xauth/plugins/xBukkitContrib.java b/src/main/java/com/cypherx/xauth/plugins/xBukkitContrib.java
new file mode 100644
index 0000000..f3450e4
--- /dev/null
+++ b/src/main/java/com/cypherx/xauth/plugins/xBukkitContrib.java
@@ -0,0 +1,31 @@
+package com.cypherx.xauth.plugins;
+
+import org.bukkit.plugin.Plugin;
+
+import com.cypherx.xauth.xAuth;
+
+public class xBukkitContrib {
+ private static Plugin bcPlugin;
+
+ public static void setup(xAuth plugin) {
+ bcPlugin = plugin.getServer().getPluginManager().getPlugin("BukkitContrib");
+ }
+
+ public static boolean isVersionCommand(String message) {
+ if (bcPlugin == null)
+ return false;
+
+ String split[] = message.substring(1).split("\\.");
+ if (split.length == 3) {
+ try {
+ Integer.valueOf(split[0]);
+ Integer.valueOf(split[1]);
+ Integer.valueOf(split[2]);
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/xAuthHelp.java b/src/main/java/com/cypherx/xauth/plugins/xHelp.java
similarity index 90%
rename from src/main/java/com/cypherx/xauth/xAuthHelp.java
rename to src/main/java/com/cypherx/xauth/plugins/xHelp.java
index 660de80..99bf17e 100644
--- a/src/main/java/com/cypherx/xauth/xAuthHelp.java
+++ b/src/main/java/com/cypherx/xauth/plugins/xHelp.java
@@ -1,9 +1,12 @@
-package com.cypherx.xauth;
+package com.cypherx.xauth.plugins;
import me.taylorkelly.help.Help;
import org.bukkit.plugin.Plugin;
-public class xAuthHelp {
+import com.cypherx.xauth.xAuth;
+import com.cypherx.xauth.xAuthLog;
+
+public class xHelp {
public static void setup(xAuth plugin) {
Plugin test = plugin.getServer().getPluginManager().getPlugin("Help");
if (test != null) {
@@ -22,7 +25,7 @@ public class xAuthHelp {
helpPlugin.registerCommand("xauth config [setting] (new value)", "View info about or change a setting", plugin, permissions[5]);
helpPlugin.registerCommand("xauth reload", "Reload the xAuth configuration and accounts", plugin, permissions[6]);
xAuthLog.info("'Help' support enabled");
- } else
- xAuthLog.warning("'Help' isn't detected. No /help support");
+ }/* else
+ xAuthLog.info("'Help' isn't detected. No /help support");*/
}
}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/xAuthPermissions.java b/src/main/java/com/cypherx/xauth/plugins/xPermissions.java
similarity index 78%
rename from src/main/java/com/cypherx/xauth/xAuthPermissions.java
rename to src/main/java/com/cypherx/xauth/plugins/xPermissions.java
index 493b150..fab6a5d 100644
--- a/src/main/java/com/cypherx/xauth/xAuthPermissions.java
+++ b/src/main/java/com/cypherx/xauth/plugins/xPermissions.java
@@ -1,12 +1,14 @@
-package com.cypherx.xauth;
+package com.cypherx.xauth.plugins;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
+import com.cypherx.xauth.xAuth;
+import com.cypherx.xauth.xAuthLog;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
-public class xAuthPermissions {
+public class xPermissions {
private static PermissionHandler permissionHandler;
public static void setup(xAuth plugin) {
@@ -17,7 +19,7 @@ public class xAuthPermissions {
permissionHandler = ((Permissions) permissionsPlugin).getHandler();
xAuthLog.info("'Permission' support enabled");
} else
- xAuthLog.warning("Permission system not detected, defaulting to OP");
+ xAuthLog.info("Permission system not detected, defaulting to OP");
}
}
diff --git a/src/main/java/com/cypherx/xauth/xAuth.java b/src/main/java/com/cypherx/xauth/xAuth.java
index f5c1c0a..2db2265 100644
--- a/src/main/java/com/cypherx/xauth/xAuth.java
+++ b/src/main/java/com/cypherx/xauth/xAuth.java
@@ -1,16 +1,23 @@
package com.cypherx.xauth;
import com.cypherx.xauth.commands.*;
-import com.cypherx.xauth.datamanager.*;
+import com.cypherx.xauth.database.*;
import com.cypherx.xauth.listeners.*;
+import com.cypherx.xauth.plugins.xBukkitContrib;
+import com.cypherx.xauth.plugins.xHelp;
+import com.cypherx.xauth.plugins.xPermissions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
+import java.sql.ResultSet;
+import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -33,25 +40,31 @@ import java.util.List;
public class xAuth extends JavaPlugin {
public static PluginDescriptionFile desc;
public static File dataFolder;
- private DataManager dataManager;
+ private ConcurrentHashMap playerCache = new ConcurrentHashMap();
+ private ConcurrentHashMap teleLocations = new ConcurrentHashMap();
+ private UUID globalUID = null;
public void onDisable() {
Player[] players = getServer().getOnlinePlayers();
if (players.length > 0) {
for (Player player : players) {
- xAuthPlayer xPlayer = dataManager.getPlayer(player.getName());
+ xAuthPlayer xPlayer = getPlayer(player.getName());
if (xPlayer.isGuest())
removeGuest(xPlayer);
}
}
- if (dataManager != null)
- dataManager.close();
-
+ Database.close();
xAuthSettings.saveChanges();
xAuthLog.info("v" + desc.getVersion() + " Disabled!");
}
+ private void initializePlugins() {
+ xBukkitContrib.setup(this);
+ xHelp.setup(this);
+ xPermissions.setup(this);
+ }
+
public void onEnable() {
desc = getDescription();
dataFolder = getDataFolder();
@@ -68,22 +81,29 @@ public class xAuth extends JavaPlugin {
return;
}
- xAuthPermissions.setup(this);
- xAuthHelp.setup(this);
+ initializePlugins();
- dataManager = new DataManager();
- if (!dataManager.isConnected()) {
+ Database.connect();
+ if (!Database.isConnected()) {
xAuthLog.severe("Disabling - No connection to database");
getServer().getPluginManager().disablePlugin(this);
return;
}
- dataManager.runStartupTasks();
+
+ DbUpdate dbUpdate = new DbUpdate();
+ if (!dbUpdate.checkVersion()) {
+ xAuthLog.info("Updating database..");
+ dbUpdate.update();
+ }
+
+ DbUtil.deleteExpiredSessions();
+ loadTeleLocations();
File oldAuthFile = new File(dataFolder, "auths.txt");
if (oldAuthFile.exists())
importAccounts(oldAuthFile);
- dataManager.printStats();
+ Database.printStats();
Player[] players = getServer().getOnlinePlayers();
if (players.length > 0) // /reload was used
@@ -125,7 +145,7 @@ public class xAuth extends JavaPlugin {
} catch (IOException e) {}
}
- dataManager.insertAccounts(accounts);
+ DbUtil.insertAccounts(accounts);
if (oldAuthFile.renameTo(new File(dataFolder, "auths.txt.old")))
xAuthLog.info("Import complete! auths.txt renamed to auths.txt.old");
@@ -133,9 +153,37 @@ public class xAuth extends JavaPlugin {
xAuthLog.info("Import complete! Verify that all accounts were imported then remove/rename auths.txt");
}
+ public xAuthPlayer getPlayer(String playerName) {
+ String lowPlayerName = playerName.toLowerCase();
+
+ if (playerCache.containsKey(lowPlayerName))
+ return playerCache.get(lowPlayerName);
+
+ xAuthPlayer xPlayer = DbUtil.getPlayerFromDb(playerName);
+ if (xPlayer == null)
+ xPlayer = new xAuthPlayer(playerName);
+
+ playerCache.put(lowPlayerName, xPlayer);
+ return xPlayer;
+ }
+
+ public xAuthPlayer getPlayerJoin(String playerName) {
+ String lowPlayerName = playerName.toLowerCase();
+
+ if (playerCache.containsKey(lowPlayerName))
+ return DbUtil.reloadPlayer(playerCache.get(lowPlayerName));
+
+ xAuthPlayer xPlayer = DbUtil.getPlayerFromDb(playerName);
+ if (xPlayer == null)
+ xPlayer = new xAuthPlayer(playerName);
+
+ playerCache.put(lowPlayerName, xPlayer);
+ return xPlayer;
+ }
+
private void handleReload(Player[] players) {
for (Player player : players) {
- xAuthPlayer xPlayer = dataManager.getPlayerJoin(player.getName());
+ xAuthPlayer xPlayer = getPlayerJoin(player.getName());
boolean isRegistered = xPlayer.isRegistered();
if (!xPlayer.isAuthenticated() && (isRegistered || (!isRegistered && xPlayer.mustRegister()))) {
@@ -150,7 +198,7 @@ public class xAuth extends JavaPlugin {
// remove old session (if any)
if (xPlayer.hasSession())
- dataManager.deleteSession(xPlayer);
+ DbUtil.deleteSession(xPlayer);
if (xAuthSettings.guestTimeout > 0 && xPlayer.isRegistered()) {
int taskId = getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable() {
@@ -180,7 +228,7 @@ public class xAuth extends JavaPlugin {
Player player = xPlayer.getPlayer();
PlayerInventory playerInv = player.getInventory();
- dataManager.insertInventory(xPlayer);
+ DbUtil.insertInventory(xPlayer);
playerInv.clear();
playerInv.setHelmet(null);
playerInv.setChestplate(null);
@@ -199,7 +247,7 @@ public class xAuth extends JavaPlugin {
Player player = xPlayer.getPlayer();
PlayerInventory playerInv = player.getInventory();
- ItemStack[] inv = dataManager.getInventory(xPlayer);
+ ItemStack[] inv = DbUtil.getInventory(xPlayer);
ItemStack[] items = new ItemStack[inv.length - 4];
ItemStack[] armor = new ItemStack[4];
@@ -224,7 +272,7 @@ public class xAuth extends JavaPlugin {
playerInv.setContents(items);
playerInv.setArmorContents(armor);
- dataManager.deleteInventory(xPlayer);
+ DbUtil.deleteInventory(xPlayer);
if (xPlayer.getLocation() != null)
xPlayer.getPlayer().teleport(xPlayer.getLocation());
@@ -235,11 +283,11 @@ public class xAuth extends JavaPlugin {
Account account = xPlayer.getAccount();
account.setLastLoginDate(Util.getNow());
account.setLastLoginHost(Util.getHostFromPlayer(xPlayer.getPlayer()));
- dataManager.saveAccount(account);
+ DbUtil.saveAccount(account);
Session session = new Session(account.getId(), account.getLastLoginHost());
xPlayer.setSession(session);
- dataManager.insertSession(session);
+ DbUtil.insertSession(session);
removeGuest(xPlayer);
xPlayer.setStrikes(0);
@@ -247,7 +295,7 @@ public class xAuth extends JavaPlugin {
public void changePassword(Account account, String newPass) {
account.setPassword(Util.encrypt(newPass));
- dataManager.saveAccount(account);
+ DbUtil.saveAccount(account);
}
public boolean checkPassword(Account account, String checkPass) {
@@ -325,8 +373,77 @@ public class xAuth extends JavaPlugin {
}
}
+ private void loadTeleLocations() {
+ String sql = "SELECT * FROM `" + xAuthSettings.tblLocation + "`";
+ ResultSet rs = Database.queryRead(sql);
+
+ try {
+ while (rs.next()) {
+ TeleLocation teleLocation = new TeleLocation();
+ String uid = rs.getString("uid");
+ boolean update = false;
+
+ // Database version 0001 -> 0002 fix
+ if (Util.isUUID(uid))
+ teleLocation.setUID(UUID.fromString(uid));
+ else {
+ teleLocation.setUID(getServer().getWorld(uid).getUID());
+ update = true;
+ }
+
+ teleLocation.setX(rs.getDouble("x"));
+ teleLocation.setY(rs.getDouble("y"));
+ teleLocation.setZ(rs.getDouble("z"));
+ teleLocation.setYaw(rs.getFloat("yaw"));
+ teleLocation.setPitch(rs.getFloat("pitch"));
+ teleLocation.setGlobal(rs.getInt("global"));
+ teleLocations.put(teleLocation.getUID(), teleLocation);
+
+ if (teleLocation.getGlobal() == 1)
+ globalUID = teleLocation.getUID();
+
+ if (update) {
+ sql = "UPDATE `" + xAuthSettings.tblLocation + "` SET `uid` = ? WHERE `uid` = ?";
+ Database.queryWrite(sql, teleLocation.getUID().toString(), uid);
+ }
+ }
+ } catch (SQLException e) {
+ xAuthLog.severe("Could not load TeleLocations from database!", e);
+ } finally {
+ try {
+ rs.close();
+ } catch (SQLException e) {}
+ }
+ }
+
+ public TeleLocation getTeleLocation(UUID uid) {
+ if (uid == null)
+ return null;
+
+ return teleLocations.get(uid);
+ }
+
+ public void setTeleLocation(TeleLocation teleLocation) {
+ TeleLocation tOld = teleLocations.put(teleLocation.getUID(), teleLocation);
+ if (teleLocation.getGlobal() == 1)
+ globalUID = teleLocation.getUID();
+
+ if (tOld == null)
+ DbUtil.insertTeleLocation(teleLocation);
+ else
+ DbUtil.updateTeleLocation(teleLocation);
+ }
+
+ public void removeTeleLocation(TeleLocation teleLocation) {
+ teleLocations.remove(teleLocation.getUID());
+ if (teleLocation.getGlobal() == 1)
+ globalUID = null;
+
+ DbUtil.deleteTeleLocation(teleLocation);
+ }
+
public Location getLocationToTeleport(World world) {
- TeleLocation teleLocation = dataManager.getTeleLocation(world.getName());
+ TeleLocation teleLocation = getTeleLocation((globalUID == null ? world.getUID() : globalUID));
return (teleLocation == null ? world.getSpawnLocation() : teleLocation.getLocation());
}
@@ -335,7 +452,7 @@ public class xAuth extends JavaPlugin {
if (xAuthSettings.strikeAction.equals("banip")) {
StrikeBan ban = new StrikeBan(Util.getHostFromPlayer(player));
- getDataManager().insertStrikeBan(ban);
+ DbUtil.insertStrikeBan(ban);
xAuthLog.info(ban.getHost() + " banned by strike system");
}
@@ -347,7 +464,7 @@ public class xAuth extends JavaPlugin {
}
public boolean isBanned(String host) {
- final StrikeBan ban = dataManager.loadStrikeBan(host);
+ final StrikeBan ban = DbUtil.loadStrikeBan(host);
if (ban == null)
return false;
@@ -358,7 +475,7 @@ public class xAuth extends JavaPlugin {
if (unbanTime.compareTo(Util.getNow()) > 0) // still banned
return true;
else // no longer banned, remove from database
- dataManager.deleteStrikeBan(ban);
+ DbUtil.deleteStrikeBan(ban);
return false;
}
@@ -368,7 +485,7 @@ public class xAuth extends JavaPlugin {
xAuthMessages.setup(dataFolder);
}
- public DataManager getDataManager() {
- return dataManager;
+ public UUID getGlobalUID() {
+ return globalUID;
}
}
\ No newline at end of file
diff --git a/src/main/java/com/cypherx/xauth/xAuthMessages.java b/src/main/java/com/cypherx/xauth/xAuthMessages.java
index 59ecfa7..5c7556b 100644
--- a/src/main/java/com/cypherx/xauth/xAuthMessages.java
+++ b/src/main/java/com/cypherx/xauth/xAuthMessages.java
@@ -53,7 +53,7 @@ public class xAuthMessages {
public static String admnRegSuccess = "{BRIGHTGREEN}Account successfully created for: {WHITE}{TARGET}";
public static String admnCpwUsage = "{RED}Correct Usage: /xauth changepw ";
public static String admnCpwRegistered = "{RED}This player is not registered!";
- public static String admnCpwSuccess = "{TARGET}''s {BRIGHTGREEN}password has been changed!";
+ public static String admnCpwSuccess = "{TARGET}'s {BRIGHTGREEN}password has been changed!";
public static String admnLogoutUsage = "{RED}Correct Usage: /xauth logout ";
public static String admnLogoutLogged = "{TARGET} {RED}is not logged in!";
public static String admnLogoutSuccess = "{TARGET} {BRIGHTGREEN}has been logged out!";
@@ -61,10 +61,15 @@ public class xAuthMessages {
public static String admnUnregRegistered = "{RED}This player is not registered!";
public static String admnUnregSuccessTgt = "{RED}You have been unregistered and logged out!";
public static String admnUnregSuccessPlyr = "{TARGET} {BRIGHTGREEN}has been unregistered!";
- public static String admnLocUsage = "{RED}Correct Usage: /xauth location set|remove";
+ public static String admnLocUsage = "{RED}Correct Usage: /xauth location set|remove [global]";
+ public static String admnLocSetErrGlobal = "{YELLOW}{PLUGIN} {RED}Global teleport location is set to this world.{NEWLINE}{YELLOW}{PLUGIN} {RED}Please remove it first.";
public static String admnLocSetSuccess = "{YELLOW}{PLUGIN} {BRIGHTGREEN}Teleport location for this world set to your location!";
+ public static String admnLocSetGlobalSuccess = "{YELLOW}{PLUGIN} {BRIGHTGREEN}Global teleport location set to your location!";
public static String admnLocRmvNo = "{YELLOW}{PLUGIN} {BRIGHTGREEN}This world does not have a teleport location!";
+ public static String admnLocRmvErrGlobal = "{YELLOW}{PLUGIN} {RED}Global teleport location is set to this world.{NEWLINE}{YELLOW}{PLUGIN} {RED}Please use /xauth location remove global";
+ public static String admnLocRmvGlobalNo = "{YELLOW}{PLUGIN} {BRIGHTGREEN}A global teleport location is not set!";
public static String admnLocRmvSuccess = "{YELLOW}{PLUGIN} {BRIGHTGREEN}Teleport location for this world has been removed!";
+ public static String admnLocRmvGlobalSuccess = "{YELLOW}{PLUGIN} {BRIGHTGREEN}Global teleport location has been removed!";
public static String admnConfUsage = "{RED}Correct Usage: /xauth config [new value]";
public static String admnConfNo = "{YELLOW}{PLUGIN} {RED}No such setting!";
public static String admnConfDesc = "Setting: {SETTING}{NEWLINE}Type: {TYPE}{NEWLINE}Value: {VALUE}";
@@ -81,7 +86,7 @@ public class xAuthMessages {
/*
* REMEMBER TO CHANGE VERSION AFTER MODIFYING DEFAULT STRINGS
*/
- public static int version = 1;
+ public static int version = 2;
public static void setup(File dataFolder) {
file = new File(dataFolder, "messages.yml");
@@ -145,9 +150,14 @@ public class xAuthMessages {
admnUnregSuccessTgt = getString("admin.unregister.success.target", admnUnregSuccessTgt);
admnUnregSuccessPlyr = getString("admin.unregister.success.player", admnUnregSuccessPlyr);
admnLocUsage = getString("admin.location.usage", admnLocUsage);
+ admnLocSetErrGlobal = getString("admin.location.set.isglobal", admnLocSetErrGlobal);
admnLocSetSuccess = getString("admin.location.set.success", admnLocSetSuccess);
+ admnLocSetGlobalSuccess = getString("admin.location.set.global.success", admnLocSetGlobalSuccess);
admnLocRmvNo = getString("admin.location.remove.no", admnLocRmvNo);
+ admnLocRmvErrGlobal = getString("admin.location.remove.isglobal", admnLocRmvErrGlobal);
admnLocRmvSuccess = getString("admin.location.remove.success", admnLocRmvSuccess);
+ admnLocRmvGlobalNo = getString("admin.location.remove.global.no", admnLocRmvGlobalNo);
+ admnLocRmvGlobalSuccess = getString("admin.location.remove.global.success", admnLocRmvGlobalSuccess);
admnConfUsage = getString("admin.config.usage", admnConfUsage);
admnConfNo = getString("admin.config.no", admnConfNo);
admnConfDesc = getString("admin.config.desc", admnConfDesc);
@@ -172,7 +182,7 @@ public class xAuthMessages {
private static void update() {
if (version > getInt("version", version)) {
xAuthLog.info("Updating file: messages.yml");
- Util.writeConfig(file, xAuthSettings.class);
+ Util.writeConfig(file, xAuthMessages.class);
}
}
diff --git a/src/main/java/com/cypherx/xauth/xAuthPlayer.java b/src/main/java/com/cypherx/xauth/xAuthPlayer.java
index 1873b97..df94d3b 100644
--- a/src/main/java/com/cypherx/xauth/xAuthPlayer.java
+++ b/src/main/java/com/cypherx/xauth/xAuthPlayer.java
@@ -5,8 +5,11 @@ import java.sql.Timestamp;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
+
+import com.cypherx.xauth.plugins.xPermissions;
//import org.bukkit.inventory.ItemStack;
+
public class xAuthPlayer {
private String playerName;
private Account account;
@@ -51,7 +54,7 @@ public class xAuthPlayer {
if (xAuthSettings.regForced)
return true;
- return xAuthPermissions.has(getPlayer(), "xauth.register");
+ return xPermissions.has(getPlayer(), "xauth.register");
}
public boolean canNotify() {
diff --git a/src/main/java/com/cypherx/xauth/xAuthSettings.java b/src/main/java/com/cypherx/xauth/xAuthSettings.java
index 5c47638..aa62912 100644
--- a/src/main/java/com/cypherx/xauth/xAuthSettings.java
+++ b/src/main/java/com/cypherx/xauth/xAuthSettings.java
@@ -6,6 +6,8 @@ import java.util.List;
import org.bukkit.util.config.Configuration;
+import com.cypherx.xauth.database.Database;
+
public class xAuthSettings {
private static File file;
private static Configuration config;
@@ -31,15 +33,6 @@ public class xAuthSettings {
public static String tblStrike = "strike_bans";
public static String tblLocation = "tele_locations";
public static String tblInventory = "inventory";
- /*public static String colAccId = "id";
- public static String colAccPlayerName = "playername";
- public static String colAccPassword = "password";
- public static String colAccEmail = "email";
- public static String colAccRegDate = "registerdate";
- public static String colAccRegIp = "registerip";
- public static String colAccLastLoginDate = "lastlogindate";
- public static String colAccLastLoginIp = "lastloginip";
- public static String colAccActive = "active";*/
// registration
public static boolean regEnabled = true;
@@ -127,15 +120,6 @@ public class xAuthSettings {
tblStrike = getString("mysql.tables.strike", tblStrike);
tblLocation = getString("mysql.tables.location", tblLocation);
tblInventory = getString("mysql.tables.inventory", tblInventory);
- /*colAccId = getString("mysql.columns.account.id", colAccId);
- colAccPlayerName = getString("mysql.columns.account.playername", colAccPlayerName);
- colAccPassword = getString("mysql.columns.account.password", colAccPassword);
- colAccEmail = getString("mysql.columns.account.email", colAccEmail);
- colAccRegDate = getString("mysql.columns.account.registerdate", colAccRegDate);
- colAccRegIp = getString("mysql.columns.account.registerip", colAccRegIp);
- colAccLastLoginDate = getString("mysql.columns.account.lastlogindate", colAccLastLoginDate);
- colAccLastLoginIp = getString("mysql.columns.account.lastloginip", colAccLastLoginIp);
- colAccActive = getString("mysql.columns.account.active", colAccActive);*/
regEnabled = getBool("registration.enabled", regEnabled);
regForced = getBool("registration.forced", regForced);
@@ -186,6 +170,9 @@ public class xAuthSettings {
pwAllowChange = false;
activation = false;
}
+
+ if (datasource.equals("mysql"))
+ Database.setDBMS(Database.DBMS.MYSQL);
}
private static String getString(String key, String def) {
diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml
index 0d3e4e4..1a92dca 100644
--- a/src/main/resources/messages.yml
+++ b/src/main/resources/messages.yml
@@ -1,87 +1,94 @@
join:
- register: '[joinRegister]'
- login: '[joinLogin]'
+ register: "[joinRegister]"
+ login: "[joinLogin]"
error:
- banned: '[joinErrBanned]'
- online: '[joinErrOnline]'
- name: '[joinErrName]'
+ banned: "[joinErrBanned]"
+ online: "[joinErrOnline]"
+ name: "[joinErrName]"
register:
- usage: '[regUsage]'
- success: '[regSuccess]'
+ usage: "[regUsage]"
+ success: "[regSuccess]"
error:
- disabled: '[regErrDisabled]'
- registered: '[regErrRegistered]'
- multiple: '[regErrMultiple]'
- password: '[regErrPassword]'
- email: '[regErrEmail]'
+ disabled: "[regErrDisabled]"
+ registered: "[regErrRegistered]"
+ multiple: "[regErrMultiple]"
+ password: "[regErrPassword]"
+ email: "[regErrEmail]"
login:
- usage: '[loginUsage]'
- success: '[loginSuccess]'
+ usage: "[loginUsage]"
+ success: "[loginSuccess]"
error:
- registered: '[loginErrRegistered]'
- logged: '[loginErrLogged]'
- password: '[loginErrPassword]'
- activate: '[loginErrActivate]'
+ registered: "[loginErrRegistered]"
+ logged: "[loginErrLogged]"
+ password: "[loginErrPassword]"
+ activate: "[loginErrActivate]"
logout:
- success: '[logoutSuccess]'
+ success: "[logoutSuccess]"
error:
- logged: '[logoutErrLogged]'
+ logged: "[logoutErrLogged]"
changepw:
- usage: '[cpwUsage]'
- success: '[cpwSuccess]'
+ usage: "[cpwUsage]"
+ success: "[cpwSuccess]"
error:
- disabled: '[cpwErrDisabled]'
- logged: '[cpwErrLogged]'
- incorrect: '[cpwErrIncorrect]'
- invalid: '[cpwErrInvalid]'
+ disabled: "[cpwErrDisabled]"
+ logged: "[cpwErrLogged]"
+ incorrect: "[cpwErrIncorrect]"
+ invalid: "[cpwErrInvalid]"
admin:
- unknown: '[admnUnknown]'
- permission: '[admnPermission]'
+ unknown: "[admnUnknown]"
+ permission: "[admnPermission]"
register:
- usage: '[admnRegUsage]'
- registered: '[admnRegRegistered]'
- success: '[admnRegSuccess]'
+ usage: "[admnRegUsage]"
+ registered: "[admnRegRegistered]"
+ success: "[admnRegSuccess]"
changepw:
- usage: '[admnCpwUsage]'
- registered: '[admnCpwRegistered]'
- success: '[admnCpwSuccess]'
+ usage: "[admnCpwUsage]"
+ registered: "[admnCpwRegistered]"
+ success: "[admnCpwSuccess]"
logout:
- usage: '[admnLogoutUsage]'
- logged: '[admnLogoutLogged]'
- success: '[admnLogoutSuccess]'
+ usage: "[admnLogoutUsage]"
+ logged: "[admnLogoutLogged]"
+ success: "[admnLogoutSuccess]"
unregister:
- usage: '[admnUnregUsage]'
- registered: '[admnUnregRegistered]'
+ usage: "[admnUnregUsage]"
+ registered: "[admnUnregRegistered]"
success:
- target: '[admnUnregSuccessTgt]'
- player: '[admnUnregSuccessPlyr]'
+ target: "[admnUnregSuccessTgt]"
+ player: "[admnUnregSuccessPlyr]"
location:
- usage: '[admnLocUsage]'
+ usage: "[admnLocUsage]"
set:
- success: '[admnLocSetSuccess]'
+ isglobal: "[admnLocSetErrGlobal]"
+ success: "[admnLocSetSuccess]"
+ global:
+ success: "[admnLocSetGlobalSuccess]"
remove:
- no: '[admnLocRmvNo]'
- success: '[admnLocRmvSuccess]'
+ no: "[admnLocRmvNo]"
+ isglobal: "[admnLocRmvErrGlobal]"
+ success: "[admnLocRmvSuccess]"
+ global:
+ no: "[admnLocRmvGlobalNo]"
+ success: "[admnLocRmvGlobalSuccess]"
config:
- usage: '[admnConfUsage]'
- no: '[admnConfNo]'
- desc: '[admnConfDesc]'
- invalid: '[admnConfInvalid]'
- success: '[admnConfSuccess]'
+ usage: "[admnConfUsage]"
+ no: "[admnConfNo]"
+ desc: "[admnConfDesc]"
+ invalid: "[admnConfInvalid]"
+ success: "[admnConfSuccess]"
reload:
- sucess: '[admnReloadSuccess]'
+ sucess: "[admnReloadSuccess]"
misc:
- illegal: '[miscIllegal]'
- reloaded: '[miscReloaded]'
+ illegal: "[miscIllegal]"
+ reloaded: "[miscReloaded]"
kick:
- timeout: '[miscKickTimeout]'
- strike: '[miscKickStrike]'
+ timeout: "[miscKickTimeout]"
+ strike: "[miscKickStrike]"
# INTERNAL USE ONLY! DO NOT TOUCH!
version: [version]
\ No newline at end of file
diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml
index 6b638be..6684583 100644
--- a/src/main/resources/plugin.yml
+++ b/src/main/resources/plugin.yml
@@ -1,6 +1,6 @@
name: xAuth
main: com.cypherx.xauth.xAuth
-version: 2.0b3.5
+version: 2.0b4
description: Offline-Mode Security Suite
author: CypherX
commands:
@@ -26,7 +26,7 @@ commands:
/ changepw
/ logout
/ unregister
- / location set|remove
+ / location set|remove [global]
/ config [value]
/ reload
/ version
\ No newline at end of file