· 6 years ago · Jul 16, 2019, 12:46 AM
1package minecade.dungeonrealms.Hive;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.lang.reflect.Field;
10import java.net.Socket;
11import java.net.URISyntaxException;
12import java.net.URL;
13import java.net.URLConnection;
14import java.security.CodeSource;
15import java.sql.Connection;
16import java.sql.PreparedStatement;
17import java.sql.ResultSet;
18import java.sql.SQLException;
19import java.text.DecimalFormat;
20import java.util.ArrayList;
21import java.util.Arrays;
22import java.util.HashMap;
23import java.util.LinkedHashSet;
24import java.util.List;
25import java.util.Map;
26import java.util.Map.Entry;
27import java.util.Random;
28import java.util.TimeZone;
29import java.util.concurrent.ConcurrentHashMap;
30import java.util.concurrent.CopyOnWriteArrayList;
31import java.util.logging.Level;
32import java.util.logging.Logger;
33import java.util.zip.ZipEntry;
34import java.util.zip.ZipInputStream;
35
36import javax.persistence.EntityManager;
37
38import minecade.dungeonrealms.Main;
39import minecade.dungeonrealms.Utils;
40import minecade.dungeonrealms.ChatMechanics.ChatMechanics;
41import minecade.dungeonrealms.CommunityMechanics.CommunityMechanics;
42import minecade.dungeonrealms.DuelMechanics.DuelMechanics;
43import minecade.dungeonrealms.EcashMechanics.EcashMechanics;
44import minecade.dungeonrealms.GuildMechanics.GuildMechanics;
45import minecade.dungeonrealms.HealthMechanics.HealthMechanics;
46import minecade.dungeonrealms.Hive.commands.CommandAllowLogin;
47import minecade.dungeonrealms.Hive.commands.CommandBenchmark;
48import minecade.dungeonrealms.Hive.commands.CommandBio;
49import minecade.dungeonrealms.Hive.commands.CommandDRLoad;
50import minecade.dungeonrealms.Hive.commands.CommandDRSave;
51import minecade.dungeonrealms.Hive.commands.CommandHQuery;
52import minecade.dungeonrealms.Hive.commands.CommandLogout;
53import minecade.dungeonrealms.Hive.commands.CommandProfile;
54import minecade.dungeonrealms.Hive.commands.CommandReboot;
55import minecade.dungeonrealms.Hive.commands.CommandShard;
56import minecade.dungeonrealms.Hive.commands.CommandSuicide;
57import minecade.dungeonrealms.Hive.commands.CommandSync;
58import minecade.dungeonrealms.Hive.commands.CommandWhois;
59import minecade.dungeonrealms.Hive.commands.CommandWipe;
60import minecade.dungeonrealms.InstanceMechanics.InstanceMechanics;
61import minecade.dungeonrealms.ItemMechanics.ItemMechanics;
62import minecade.dungeonrealms.KarmaMechanics.KarmaMechanics;
63import minecade.dungeonrealms.LevelMechanics.LevelMechanics;
64import minecade.dungeonrealms.LootMechanics.LootMechanics;
65import minecade.dungeonrealms.ModerationMechanics.ModerationMechanics;
66import minecade.dungeonrealms.MoneyMechanics.MoneyMechanics;
67import minecade.dungeonrealms.MountMechanics.MountMechanics;
68import minecade.dungeonrealms.PermissionMechanics.PermissionMechanics;
69import minecade.dungeonrealms.PetMechanics.PetMechanics;
70import minecade.dungeonrealms.ProfessionMechanics.ProfessionMechanics;
71import minecade.dungeonrealms.RealmMechanics.RealmMechanics;
72import minecade.dungeonrealms.ScoreboardMechanics.ScoreboardMechanics;
73import minecade.dungeonrealms.ShopMechanics.ShopMechanics;
74import minecade.dungeonrealms.SpawnMechanics.SpawnMechanics;
75import minecade.dungeonrealms.TradeMechanics.TradeMechanics;
76import minecade.dungeonrealms.TutorialMechanics.TutorialMechanics;
77import minecade.dungeonrealms.config.Config;
78import minecade.dungeonrealms.database.ConnectionPool;
79import minecade.dungeonrealms.managers.PlayerManager;
80import minecade.dungeonrealms.models.LogModel;
81import net.citizensnpcs.api.CitizensAPI;
82import net.citizensnpcs.api.npc.NPC;
83import net.citizensnpcs.api.trait.trait.Equipment;
84import net.minecraft.server.v1_7_R2.EntityPlayer;
85import net.minecraft.server.v1_7_R2.Packet;
86import net.minecraft.server.v1_7_R2.PacketPlayOutEntityEquipment;
87import net.minecraft.util.io.netty.util.internal.ConcurrentSet;
88
89import org.apache.commons.lang.StringEscapeUtils;
90import org.bukkit.Bukkit;
91import org.bukkit.ChatColor;
92import org.bukkit.Color;
93import org.bukkit.EntityEffect;
94import org.bukkit.GameMode;
95import org.bukkit.Location;
96import org.bukkit.Material;
97import org.bukkit.OfflinePlayer;
98import org.bukkit.Sound;
99import org.bukkit.craftbukkit.v1_7_R2.entity.CraftEntity;
100import org.bukkit.craftbukkit.v1_7_R2.entity.CraftPlayer;
101import org.bukkit.craftbukkit.v1_7_R2.inventory.CraftItemStack;
102import org.bukkit.entity.Entity;
103import org.bukkit.entity.EntityType;
104import org.bukkit.entity.Player;
105import org.bukkit.event.EventHandler;
106import org.bukkit.event.EventPriority;
107import org.bukkit.event.Listener;
108import org.bukkit.event.entity.EntityDamageByEntityEvent;
109import org.bukkit.event.entity.EntityDamageEvent;
110import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
111import org.bukkit.event.entity.PlayerDeathEvent;
112import org.bukkit.event.inventory.InventoryClickEvent;
113import org.bukkit.event.inventory.InventoryCloseEvent;
114import org.bukkit.event.inventory.InventoryOpenEvent;
115import org.bukkit.event.player.AsyncPlayerChatEvent;
116import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
117import org.bukkit.event.player.PlayerAnimationEvent;
118import org.bukkit.event.player.PlayerCommandPreprocessEvent;
119import org.bukkit.event.player.PlayerDropItemEvent;
120import org.bukkit.event.player.PlayerInteractEvent;
121import org.bukkit.event.player.PlayerJoinEvent;
122import org.bukkit.event.player.PlayerKickEvent;
123import org.bukkit.event.player.PlayerLoginEvent;
124import org.bukkit.event.player.PlayerLoginEvent.Result;
125import org.bukkit.event.player.PlayerMoveEvent;
126import org.bukkit.event.player.PlayerQuitEvent;
127import org.bukkit.event.player.PlayerTeleportEvent;
128import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
129import org.bukkit.event.server.ServerCommandEvent;
130import org.bukkit.event.server.ServerListPingEvent;
131import org.bukkit.inventory.Inventory;
132import org.bukkit.inventory.ItemStack;
133import org.bukkit.inventory.meta.ItemMeta;
134import org.bukkit.inventory.meta.LeatherArmorMeta;
135import org.bukkit.metadata.FixedMetadataValue;
136import org.bukkit.scheduler.BukkitRunnable;
137import org.fusesource.jansi.Ansi;
138
139import com.google.common.base.Joiner;
140
141@SuppressWarnings("deprecation")
142public class Hive implements Listener {
143
144 public static int id = getServerNumFromPrefix(Bukkit.getMotd());
145
146 public static boolean no_shard = false;
147 // Do not allow /shard -- toggle.
148
149 public static volatile List<String> offline_servers = new ArrayList<String>();
150 // Reported as offline servers, show them as offline in the UI.
151
152 public static volatile boolean server_frozen = false;
153 // Set to true when the server is frozen, when it =true, a multithreaded data upload is run.
154
155 public static String main_world_name = "";
156 // Thread-safe version of Bukkit.getWorlds().get(0).getName()
157
158 List<Player> local_plist = new ArrayList<Player>();
159 // Although currently depreciated, used when connection to the DungeonRealms hive is lost to create a list of all players who are online at the time of the
160 // d/c.
161
162 public static List<String> pending_upload = new ArrayList<String>();
163 // Players are added to this list when they first logout, and removed once all their data has been saved.
164 // It's used to prevent data loss on server shutdown events -- it lets us know that multithreaded processes are still running.
165
166 public static List<String> no_upload = new ArrayList<String>();
167 // DEPRECIATED(?) - Used originally to prevent FTP uploads of .dat information on corrupt players, but no longer applies due to SQL upload.
168 // Updated for use w/ possible SQL issues.
169
170 static List<String> being_uploaded = new ArrayList<String>();
171 // Players are added to this list on logout, it prevents the players from logging back in locally until AFTER their data has been uploaded.
172
173 static List<String> lockout_players = new ArrayList<String>();
174 // List of players who are 'locked' to the local server due to their data not uploading properly.
175
176 public static List<String> first_login = new ArrayList<String>();
177 // Contains a list of players who are logging in for the very first time.
178
179 public static List<String> online_today = new ArrayList<String>();
180 // Players who are online today, ecash.
181
182 public static List<String> killing_self = new ArrayList<String>();
183 // 2-Step confirmation for the /suicide command.
184 public static ConcurrentSet<String> players_unable_to_join = new ConcurrentSet<String>();
185 public static volatile ConcurrentHashMap<String, List<Object>> remote_player_data = new ConcurrentHashMap<String, List<Object>>();
186 // Packaged version of player data, created in loadPlayerDataSQL() and accessed throughout login proceedure.
187
188 public static HashMap<Integer, List<Integer>> server_population = new HashMap<Integer, List<Integer>>();
189 // Contains min/max players for every server, used for shard menu.
190 // US-1, Array(10,150)
191
192 // Local player data -- THREAD SAFE!
193 public static volatile HashMap<String, String> local_player_ip = new HashMap<String, String>();
194 public static volatile HashMap<String, List<String>> player_ip = new HashMap<String, List<String>>();
195 public static volatile HashMap<String, Inventory> player_inventory = new HashMap<String, Inventory>();
196 public static volatile HashMap<String, Location> player_location = new HashMap<String, Location>();
197 public static volatile HashMap<String, Double> player_hp = new HashMap<String, Double>();
198 public static volatile HashMap<String, Integer> player_level = new HashMap<String, Integer>();
199 public static volatile HashMap<String, Integer> player_food_level = new HashMap<String, Integer>();
200 public static volatile HashMap<String, ItemStack[]> player_armor_contents = new HashMap<String, ItemStack[]>();
201 public static volatile HashMap<String, Integer> player_ecash = new HashMap<String, Integer>();
202 public static volatile HashMap<String, Integer> player_sdays_left = new HashMap<String, Integer>();
203 public static volatile HashMap<String, List<Integer>> player_portal_shards = new HashMap<String, List<Integer>>();
204 // Local player data -- THREAD SAFE!
205
206 public static HashMap<String, Long> player_first_login = new HashMap<String, Long>();
207 // The LONG-format time a player first logged in. Used for noobie-protection.
208
209 public static HashMap<String, String> player_bio = new HashMap<String, String>();
210 // Player Name, Bio(being written)
211
212 // These two hashes are both used for COMBAT-LOGGING NPC management.
213 public static HashMap<String, NPC> player_to_npc = new HashMap<String, NPC>();
214
215 public static HashMap<String, String> player_to_npc_align = new HashMap<String, String>();
216 // ^ Largely Depreciated due to issues with onLogin inventories not being cleared, can cause dupes.
217
218 public static HashMap<String, ItemStack> player_item_in_hand = new HashMap<String, ItemStack>();
219 // Item in player's hand on death.
220
221 public static HashMap<String, Inventory> player_mule_inventory = new HashMap<String, Inventory>();
222 // Stores data for mule inventories on combat log.
223
224 public static HashMap<NPC, List<ItemStack>> npc_inventory = new HashMap<NPC, List<ItemStack>>();
225 // Store player inventory for combat log.
226
227 static ConcurrentHashMap<String, Long> logout_time = new ConcurrentHashMap<String, Long>();
228 // Saves the time at which a combat-logging player logs out to determine when to despawn the NPC.
229
230 public static HashMap<String, Long> last_sync = new HashMap<String, Long>();
231 // Prevents spam of /sync command to manually send data to database.
232
233 public static ConcurrentHashMap<String, Integer> safe_logout = new ConcurrentHashMap<String, Integer>();
234 // Countdown for /logout function.
235
236 public static HashMap<String, Location> safe_logout_location = new HashMap<String, Location>();
237 // Used to ensure players aren't moving too far from their original safe logout location.
238
239 public static volatile HashMap<String, String> to_kick = new HashMap<String, String>();
240 // Used by multi-threading opperations to kick players. The threads add names and reasons to this hashmap, and it kicks the players on the main thread via a
241 // scheduler.
242
243 public static HashMap<String, Integer> forum_usergroup = new HashMap<String, Integer>();
244 // Locally cached forum group -- only used to give baby_zombie currently.
245
246 public static HashMap<String, Long> login_time = new HashMap<String, Long>();
247 // Used by many other plugins to determine when a player has -just- logged in and therfore should be excempt from certain processes.
248
249 public static HashMap<String, String> server_swap = new HashMap<String, String>();
250 // Players who are swapping shards. This map is accessed in uploadPlayerData() to skip certain tasks / checks and such.
251 // PLAYER_NAME, SERVER_ID
252
253 public static HashMap<String, Location> server_swap_location = new HashMap<String, Location>();
254 // Players who are swapping shards. This map is accessed in uploadPlayerData() to skip certain tasks / checks and such.
255 // PLAYER_NAME, SERVER_ID
256
257 public static HashMap<String, String> server_swap_pending = new HashMap<String, String>();
258 // Prevent abuse from mooman and his evil scripts.
259
260 public static volatile ConcurrentHashMap<Integer, Long> last_ping = new ConcurrentHashMap<Integer, Long>();
261 // Last time each server_num sent information to the proxy. If >20 seconds, server is offline.
262
263 public static boolean local_saving = false;
264 // Turns on when the HIVE is detected as offline, meaning it's either being DDOS'd or this server is being DDOS'd.
265
266 public static boolean local_ddos = false;
267 public static boolean possible_local_ddos = false;
268 // =True when local connectivity is lost.
269
270 public static boolean hive_ddos = false;
271 public static boolean possible_hive_ddos = false;
272 // =True when hive connecivity is lost.
273
274 boolean payload_pending = false;
275 // Set to =true after get_payload has been detected as true. It will then begin to check if payload.zip is ready, if it's ready, it'll initiate the download
276 // via async scheduler.
277
278 public static boolean restart_inc = false;
279 // Set to =true for ping events.
280
281 public static boolean reboot_me = false;
282 // Thread-safe reboot command.
283
284 public static boolean get_payload_spoof = false;
285
286 public static boolean get_payload = false;
287 // Set to true in ListenThread when it's time to begin process of grabbing payload.zip
288 // Sets payload_pending to true in scheduler.
289
290 public static boolean server_lock = false;
291 // Server is locked, all logins are disabled, MOTD prefix: [LOCKED]
292
293 public static boolean shutting_down = false;
294 // Run onDisable, used to determine when the server is in the process of turning off.
295
296 public static boolean force_kick = false;
297 // Thread safe 'kick-all' command.
298
299 public static boolean loading_server = true;
300 // Loading server on bootup, don't let players in right away. Initiate stuff.
301
302 public Thread port_listener;
303 // Port listener (payload) listener.
304
305 public static String MOTD = "";
306 // Cached MOTD.
307
308 public static Hive instance = null;
309 // Static plugin reference.
310
311 public static Logger log = Logger.getLogger("Minecraft");
312
313 public static boolean force_stop = false;
314 public static boolean ready_to_die = false;
315 // Used for delayed server 'stops'. Makes sure all data is uploaded and sorted before stopping.
316
317 public static volatile long anti_crash_time = System.currentTimeMillis();
318 // Used as a reference point to determine if the server has responded in last 30 seconds.
319
320 public static String rootDir = "";
321
322 public static int player_count = 0;
323 // Used in a bunch of plugins to determine different spawn rates.
324
325 public static long uptime = 0;
326 // Server uptime in 1/4th seconds.
327
328 public static long seconds_to_reboot = 0;
329 // Seconds remaining until server reboot.
330
331 public static Inventory ShardMenu = null;
332 // Seconds remaining until server reboot.
333
334 public static long last_shard_update = 0;
335 // When to requery shard menu.
336
337 public static Thread backup;
338 // Controls 15min automated backup of player data.
339
340 public static Thread sync;
341 // Controls /sync multithreaded
342
343 public static int last_player_count = 0;
344 // For Minecade server stuff
345
346 public static List<String> loaded_players = new ArrayList<String>();
347 // Players whose data has been loaded, prevents wipe from quick login/outs.
348
349 public static volatile List<String> sync_queue = new ArrayList<String>();
350 // /sync multithreading
351
352 public final static long serverStart = System.currentTimeMillis();
353 // Server startup time for monitoring schedule reboots.
354
355 Thread ThreadPool;
356 // Controls all new Thread() SQL queries.
357
358 public static volatile CopyOnWriteArrayList<String> sql_query = new CopyOnWriteArrayList<String>();
359 // All SQL queries to run on ThreadPool.
360
361 public static volatile CopyOnWriteArrayList<LogModel> logs = new CopyOnWriteArrayList<LogModel>();
362 // All logs
363
364 public static EntityManager npc_manager = null;
365
366 public void onEnable() {
367 instance = this;
368 log.info(TimeZone.getDefault().toString());
369 TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
370
371 Main.plugin.getCommand("benchmark").setExecutor(new CommandBenchmark());
372 Main.plugin.getCommand("bio").setExecutor(new CommandBio());
373 Main.plugin.getCommand("drload").setExecutor(new CommandDRLoad());
374 Main.plugin.getCommand("drsave").setExecutor(new CommandDRSave());
375 Main.plugin.getCommand("hquery").setExecutor(new CommandHQuery());
376 Main.plugin.getCommand("logout").setExecutor(new CommandLogout());
377 Main.plugin.getCommand("profile").setExecutor(new CommandProfile());
378 Main.plugin.getCommand("reboot").setExecutor(new CommandReboot());
379 Main.plugin.getCommand("shard").setExecutor(new CommandShard());
380 Main.plugin.getCommand("suicide").setExecutor(new CommandSuicide());
381 Main.plugin.getCommand("sync").setExecutor(new CommandSync());
382 Main.plugin.getCommand("whois").setExecutor(new CommandWhois());
383 Main.plugin.getCommand("wipe").setExecutor(new CommandWipe());
384 Main.plugin.getCommand("allowjoin").setExecutor(new CommandAllowLogin());
385 MOTD = Bukkit.getMotd();
386
387 restoreCorruptShops(false);
388
389 ThreadPool = new ThreadPool();
390 ThreadPool.start();
391
392 backup = new BackupPlayerData();
393 backup.start();
394
395 sync = new SyncCommand();
396 sync.start();
397
398 Thread echo_online = new Thread(new Runnable() {
399 public void run() {
400 try {
401 Thread.sleep(20000);
402 } catch (InterruptedException ie) {
403 }
404
405 CommunityMechanics.sendPacketCrossServer("[online]" + MOTD.substring(0, MOTD.indexOf(" ")), -1, true);
406
407 }
408 });
409 echo_online.start();
410
411 makeAllTables();
412 setSystemPath();
413
414 Main.plugin.getServer().getPluginManager().registerEvents(this, Main.plugin);
415 Main.plugin.getServer().getMessenger().registerOutgoingPluginChannel(Main.plugin, "BungeeCord");
416
417 main_world_name = Bukkit.getWorlds().get(0).getName();
418
419 for (NPC n : CitizensAPI.getNPCRegistry().sorted()) {
420 if (n.data().get("combat_log_npc") != null && (Boolean) n.data().get("combat_log_npc") == true) {
421 n.destroy();
422 }
423 }
424
425 Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
426 public void run() {
427 updateServerPlayers();
428 }
429 /* 5 second delay, 10 second increments */
430 }, 20 * 5, 20 * 10);
431
432 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
433 public void run() {
434 loading_server = false; // Let people in!
435 }
436 }, 15 * 20L);
437
438 Main.plugin.getServer().getScheduler().runTaskTimerAsynchronously(Main.plugin, new Runnable() {
439 public void run() {
440 updateServerPopulations();
441 }
442 }, 10 * 20L, 10 * 20L);
443
444 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
445 public void run() {
446 uptime++;
447 }
448 }, 5L, 5L);
449
450 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
451 public void run() {
452 if (seconds_to_reboot > 0) {
453 seconds_to_reboot--;
454 }
455 if (MoneyMechanics.no_bank_use) {
456 for (Player pl : Main.plugin.getServer().getOnlinePlayers()) {
457 if (pl.getInventory().getName().startsWith("Bank Chest") || pl.getInventory().getName().equalsIgnoreCase("Collection Bin")) {
458 pl.closeInventory();
459 }
460 }
461 }
462 }
463 }, 1 * 20L, 1 * 20L);
464
465 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
466 public void run() {
467 for (Entry<Integer, Long> data : last_ping.entrySet()) {
468 long time = data.getValue();
469 int server_num = data.getKey();
470
471 if ((System.currentTimeMillis() - time) > (15 * 1000)) {
472 String server_prefix = getServerPrefixFromNum(server_num);
473 if (!(offline_servers.contains(server_prefix))) {
474 offline_servers.add(server_prefix);
475 }
476 server_population.put(server_num, new ArrayList<Integer>(Arrays.asList(0, 0)));
477 last_ping.remove(server_num);
478 }
479 }
480 }
481 }, 10 * 20L, 1 * 20L);
482
483 /*
484 * this.getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() { public void run() {
485 *
486 * if(possible_local_ddos && hasConnection()){ possible_local_ddos = false; }
487 *
488 * if(possible_hive_ddos && isHiveOnline()){ possible_hive_ddos = false; }
489 *
490 * if(local_ddos){ // We can't upload our data cause we're being DDOS'd -- players will d/c shortly so we'll lock the server until it's over. try {
491 * if(hasConnection()){ // Make sure all data has been uploaded. local_ddos = false; possible_local_ddos = false; // We have connectivity back! // Now
492 * all the pending data will upload. Bukkit.getServer().broadcastMessage(ChatColor.GREEN.toString() + ChatColor.BOLD + ">>" + ChatColor.GREEN +
493 * " Local Connectivity has been " + ChatColor.UNDERLINE + "restored" + ChatColor.GREEN + ", uploading all local data then unlocking server.");
494 * force_kick = false; server_lock = false; return; } return; // Do nothing else, let's sort out local ddos situation first. } catch (Exception e)
495 * {e.printStackTrace();} }
496 *
497 * /*if(hive_ddos){ // Hive is offline, so we need to cache all local data, lock server, and wait to upload it. // The upload function will just keep
498 * trying to upload until it works. if(isHiveOnline()){ // The hive is back online! hive_ddos = false; possible_hive_ddos = false;
499 * Bukkit.getServer().broadcastMessage(ChatColor.GREEN.toString() + ChatColor.BOLD + ">>" + ChatColor.GREEN + " Database Connectivity has been " +
500 * ChatColor.UNDERLINE + "restored" + ChatColor.GREEN + ", local login servers are now online."); } }
501 *
502 * if(!local_ddos && !(hasConnection())){ if(possible_local_ddos == true){ Bukkit.getServer().broadcastMessage(ChatColor.RED.toString() + ChatColor.BOLD
503 * + ">>" + ChatColor.RED + " Local Connectivity has been " + ChatColor.UNDERLINE + "lost" + ChatColor.RED +
504 * ", locking server and freezing local data."); local_ddos = true; force_kick = true; server_lock = true; possible_local_ddos = false; return; } else{
505 * possible_local_ddos = true; } }
506 *
507 * /*if(!hive_ddos && !(isHiveOnline())){ if(possible_hive_ddos == true){ Bukkit.getServer().broadcastMessage(ChatColor.RED.toString() + ChatColor.BOLD
508 * + ">>" + ChatColor.RED + " Database Connectivity has been " + ChatColor.UNDERLINE + "lost" + ChatColor.RED +
509 * ", local login servers have been disabled. Your data will be uploaded once connection is re-established."); hive_ddos = true; possible_hive_ddos =
510 * false; } else{ possible_hive_ddos = true; } }
511 *
512 * } }, 10 * 20L, 10 * 20L);
513 */// Require at least a 20 second d/c for it to care, otherwise it could just lag spike out and fix itself.
514
515 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
516 public void run() {
517 player_count = Bukkit.getServer().getOnlinePlayers().length;
518 }
519 }, 10 * 20L, 5 * 20L);
520
521 // TODO: Is this needed?
522 /*
523 * this.getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() { public void run() { for(Player pl :
524 * getServer().getOnlinePlayers()){ if(pending_upload.contains(pl.getName()) || server_swap.containsKey(pl.getName())){ continue; // Do not write new
525 * data if the player is uploading or changing shards. } player_inventory.put(pl.getName(), pl.getInventory()); player_location.put(pl.getName(),
526 * pl.getLocation()); player_hp.put(pl.getName(), (double)pl.getHealth()); player_level.put(pl.getName(), pl.getLevel());
527 * player_food_level.put(pl.getName(), pl.getFoodLevel()); player_armor_contents.put(pl.getName(), pl.getInventory().getArmorContents()); // Save data
528 * locally so if there's a crash multithread can access. } } }, 10 * 20L, 5 * 20L);
529 */
530
531 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
532 public void run() {
533 if (reboot_me == true) {
534 reboot_me = false;
535
536 for (Player p : Bukkit.getOnlinePlayers()) {
537 if (!(Hive.server_frozen)) {
538 p.saveData();
539 }
540 p.kickPlayer(ChatColor.GREEN.toString() + "You have been safely logged out by the server." + "\n\n" + ChatColor.GRAY.toString()
541 + "Your player data has been synced.");
542 }
543
544 int count = 0;
545 while (pending_upload.size() > 0 && count <= 200) {
546 count++;
547 try {
548 Thread.sleep(100); // Let all pending multi-thread uploads finish.
549 } catch (InterruptedException e) {
550 e.printStackTrace();
551 }
552 }
553
554 Main.plugin.getServer().shutdown();
555 }
556 }
557 }, 10 * 20L, 1 * 20L);
558
559 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
560 public void run() {
561 List<String> to_remove = new ArrayList<String>();
562 for (Entry<String, String> data : to_kick.entrySet()) {
563 String s = data.getKey();
564 String reason = data.getValue();
565 if (Bukkit.getPlayer(s) != null) {
566 Player pl = Bukkit.getPlayer(s);
567 pl.kickPlayer(reason);
568 }
569 to_remove.add(s);
570 }
571
572 for (String s : to_remove) {
573 to_kick.remove(s);
574 }
575 }
576 }, 20 * 20L, 1 * 20L);
577
578 Main.plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(Main.plugin, new Runnable() {
579 public void run() {
580 if (Hive.server_lock == true) {
581 return;
582 }
583 Thread t = new FixBrokenLoginCodes();
584 t.start();
585 }
586 }, 10 * 20L, 20 * 20L); // Perform it quickly on launch, then after a while.
587
588 Main.plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(Main.plugin, new Runnable() {
589 public void run() {
590 if (payload_pending == true) {
591 try {
592 URL url = new URL("ftp://" + Config.ftp_user + ":" + Config.ftp_pass + "@" + Config.Hive_IP + "/sdata/payload.zip");
593 url.openConnection();
594 URLConnection urlc = url.openConnection();
595 InputStream is = urlc.getInputStream();
596 is.close();
597 } catch (IOException not_ready) {
598 log.info("[HIVE (SLAVE Edition)] payload.zip is not yet ready for pickup, waiting 5s...");
599 return;
600 }
601
602 try {
603 payload_pending = false;
604 downloadPayload();
605 } catch (IOException e) {
606 e.printStackTrace();
607 }
608 }
609
610 if (get_payload == true) {
611 get_payload = false;
612 payload_pending = true;
613 }
614 }
615
616 }, 10 * 20L, 5 * 20L);
617
618 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
619 public void run() {
620 if (server_lock == true && (force_kick == true || get_payload == true || get_payload_spoof == true)
621 && Main.plugin.getServer().getOnlinePlayers().length > 0) {
622 for (Player p : Main.plugin.getServer().getOnlinePlayers()) {
623 if (p.isOp() && get_payload == false && get_payload_spoof == false) {
624 continue; // Don't kick the OP's.
625 }
626 if (!(Hive.server_frozen)) {
627 p.saveData();
628 }
629 if (force_kick == true) {
630 p.kickPlayer("\n" + ChatColor.GREEN.toString() + "This " + ChatColor.BOLD.toString() + "Dungeon Realms"
631 + ChatColor.GREEN.toString() + " shard has been temporarily " + ChatColor.UNDERLINE + "LOCKED." + "\n\n" + ChatColor.GRAY
632 + "Your player data is being synced.");
633 } else if (get_payload == true || get_payload_spoof == true) {
634 p.kickPlayer("\n" + ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "Dungeon Realms" + ChatColor.GREEN.toString()
635 + " is running a content patch." + "\n\n" + ChatColor.GRAY
636 + "This shard is currently downloading a new SNAPSHOT of the server software.");
637 }
638 }
639 }
640 }
641 }, 5 * 20L, 5L);
642
643 Main.plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(Main.plugin, new Runnable() {
644 public void run() {
645 if (ready_to_die == true) {
646 if ((new File(rootDir + "/" + "payload.zip").exists()) || force_stop) {
647 ready_to_die = false;
648 Main.plugin.getServer().shutdown();
649 }
650 }
651 }
652 }, 10 * 20L, 1 * 20L);
653
654 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
655 public void run() {
656 List<String> to_remove = new ArrayList<String>();
657 for (Entry<String, Integer> data : safe_logout.entrySet()) {
658 String p_name = data.getKey();
659 Integer seconds_left = data.getValue();
660
661 if (Bukkit.getPlayer(p_name) == null) {
662 to_remove.add(p_name);
663 continue;
664 }
665
666 Player p = Bukkit.getPlayer(p_name);
667
668 if (seconds_left <= 0) {
669 if (HealthMechanics.in_combat.containsKey(p_name)) {
670 to_remove.add(p_name);
671 continue; // They're in combat...
672 }
673 HealthMechanics.in_combat.remove(p_name);
674 to_remove.add(p_name);
675 p.kickPlayer(ChatColor.GREEN.toString() + "You have safely logged out." + "\n\n" + ChatColor.GRAY.toString()
676 + "Your player data has been synced.");
677 continue;
678 }
679
680 p.sendMessage(ChatColor.RED + "Logging out in ... " + ChatColor.BOLD + seconds_left + "s");
681 seconds_left = seconds_left - 1;
682 safe_logout.put(p.getName(), seconds_left);
683 }
684
685 }
686 }, 5 * 20L, 20L);
687
688 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
689 public void run() {
690 for (Map.Entry<String, Long> set : logout_time.entrySet()) {
691 try {
692 final String p_name = set.getKey();
693 Long log_time = set.getValue();
694
695 if ((System.currentTimeMillis() - log_time) > (20 * 1000)) {
696 if (!(player_to_npc.containsKey(p_name))) { // If the NPC died or something.
697 logout_time.remove(p_name);
698
699 log.info(Ansi.ansi().fg(Ansi.Color.CYAN).boldOff().toString() + "[HIVE (SLAVE Edition)] Player " + p_name
700 + "'s NPC has been killed [DEBUG]." + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
701
702 Thread t = new Thread(new Runnable() {
703 public void run() {
704 setCombatLogger(p_name);
705 Hive.setPlayerOffline(p_name, 5);
706 }
707 });
708
709 t.start();
710 continue;
711 }
712
713 NPC n = player_to_npc.get(p_name);
714
715 logout_time.remove(p_name); // The player is now safe and may log back in again with their items still intact.
716 player_to_npc.remove(p_name);
717 player_to_npc_align.remove(p_name);
718
719 log.info(Ansi.ansi().fg(Ansi.Color.CYAN).boldOff().toString() + "[HIVE (SLAVE Edition)] Player " + p_name
720 + "'s NPC has been despawned." + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
721 List<Player> lpl = new ArrayList<Player>();
722 for (Entity ent : n.getBukkitEntity().getNearbyEntities(32, 32, 32)) {
723 if (ent instanceof Player) {
724 lpl.add((Player) ent);
725 }
726 }
727
728 n.despawn();
729 n.destroy();
730
731 Thread t = new Thread(new Runnable() {
732 public void run() {
733 Hive.setPlayerOffline(p_name, 5);
734 }
735 });
736
737 t.start();
738 }
739 } catch (Exception e) {
740 e.printStackTrace();
741 continue;
742 }
743 }
744 }
745
746 }, 5 * 20L, 20L);
747
748 Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() {
749 public void run() {
750 anti_crash_time = System.currentTimeMillis();
751 // Update variable to determine if server is responding....
752 }
753 }, 5 * 20L, 1 * 20L);
754
755 Thread crash_checker = new Thread(new Runnable() {
756 @Override
757 public void run() {
758 long multithread_anti_crash = 0;
759 multithread_anti_crash = Hive.anti_crash_time;
760 boolean crashed = false;
761
762 while (!crashed) {
763 try {
764 Thread.sleep(30 * 1000);
765 } catch (InterruptedException e) {
766 continue;
767 }
768 if (multithread_anti_crash == Hive.anti_crash_time) {
769 if (server_frozen == true || shutting_down == true || ShopMechanics.shop_shutdown == true) {
770 continue; // Pointless.
771 }
772
773 // No tick in last 30 seconds, upload local data and reboot.
774 System.out
775 .println("[HIVE (Slave Edition)] Detected no activity in main thread for 30 seconds, uploading local data and locking server.");
776
777 server_frozen = true;
778 uploadDataOnCrash();
779
780 CommunityMechanics.sendPacketCrossServer("[crash]" + MOTD.substring(0, MOTD.indexOf(" ")), -1, true);
781
782 crashed = true;
783 break;
784 } else if (multithread_anti_crash != Hive.anti_crash_time) {
785 multithread_anti_crash = Hive.anti_crash_time;
786 // Update time.
787 }
788 }
789 }
790 });
791
792 crash_checker.start();
793
794 /*
795 * Thread update_population = new Thread(new Runnable() { public void run() { try { Thread.sleep(10 * 1000); } catch(Exception err) {} while(true) { try
796 * { Thread.sleep(10 * 1000); } catch(Exception err) {}
797 *
798 * if(Hive.shutting_down || Hive.server_frozen || Hive.server_lock || Hive.force_kick || Hive.restart_inc) { continue; // Do not update population if
799 * server is not reachable, so the timeout will occur on the proxy. }
800 *
801 * updateServerPopulations(); } } });
802 *
803 * update_population.start();
804 */
805
806 /*
807 * if(!(isThisRootMachine())){ port_listener = new ListenThread(); port_listener.start(); }
808 */
809
810 log.info(Ansi.ansi().fg(Ansi.Color.GREEN).boldOff().toString() + "**************************");
811 log.info(Ansi.ansi().fg(Ansi.Color.GREEN).boldOff().toString() + "[HIVE (SLAVE Edition)] has been enabled.");
812 log.info(Ansi.ansi().fg(Ansi.Color.GREEN).boldOff().toString() + "**************************" + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
813 }
814
815 public void onDisable() {
816 // backup.interrupt();
817 // Interrupts backup process.
818 for (String s : players_unable_to_join) {
819 setPlayerCanJoin(s, true);
820 }
821 if (shutting_down == true) {
822 return;
823 }
824
825 shutting_down = true;
826
827 for (NPC n : player_to_npc.values()) {
828 // n.removeFromWorld();
829 n.destroy();
830 }
831
832 player_to_npc.clear();
833
834 /*
835 * int count = 0; while(pending_upload.size() > 0 && count <= 200){ count++; log.info("[HIVE (SLAVE Edition)] ONLINE PLAYERS: " +
836 * Bukkit.getOnlinePlayers().length); log.info("[HIVE (SLAVE Edition)] PENDING UPLOAD: " + pending_upload.size()); try { Thread.sleep(100); // Let all
837 * pending multi-thread uploads finish. } catch (InterruptedException e) { e.printStackTrace(); } }
838 */
839
840 log.info(Ansi.ansi().fg(Ansi.Color.RED).boldOff().toString() + "**************************");
841 log.info(Ansi.ansi().fg(Ansi.Color.RED).boldOff().toString() + "[HIVE (SLAVE Edition)] has been disabled.");
842 log.info(Ansi.ansi().fg(Ansi.Color.RED).boldOff().toString() + "**************************" + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
843 }
844
845 public void updateServerPlayers() {
846 final int playerCount = Bukkit.getOnlinePlayers().length;
847 if (playerCount == last_player_count) {
848 return;
849 }
850 last_player_count = playerCount;
851 sql_query.add("UPDATE server SET online_players='" + playerCount + "' WHERE id='" + id + "';");
852 }
853
854 public void uploadDataOnCrash() {
855 server_lock = true;
856 force_kick = true;
857
858 for (String s : ShopMechanics.shop_stock.keySet()) {
859 // This will convert all shop stocks to collection bins in collection_bin, and upload the data of any players not online.
860 // uploadShopDatabaseData() will take care of online players.
861 ShopMechanics.backupStoreData(s);
862 }
863
864 for (String s : player_inventory.keySet()) {
865 try {
866 uploadPlayerDatabaseData(s); // Uploads all player-specific data that is stored locally on this server.
867 } catch (SQLException err) {
868 err.printStackTrace();
869 }
870
871 MoneyMechanics.uploadBankDatabaseData(s, false); // Uploads bank records of local players.
872 ShopMechanics.uploadShopDatabaseData(s, false); // Uploads collection bin and shop level of all current logged in users. Collection bin will be
873 // accurate due to the .backupStoreData(s) above.
874 ShopMechanics.asyncSetShopServerSQL(s, -1); // Sets the shop to no longer exist, as the server will be rebooting shortly.
875
876 log.info("[HIVE (RECOVERY)] Uploaded local data for: " + s);
877 }
878
879 RealmMechanics.uploadLocalRealms();
880 setAllPlayersAsOffline(); // Sets all players to offline so they can log in again whenever they want now that their data is uploaded.
881 Main.plugin.getServer().shutdown();
882 }
883
884 public static void runSyncQuery(String query) {
885 Connection con = null;
886 PreparedStatement pst = null;
887
888 try {
889 pst = ConnectionPool.getConnection().prepareStatement(query);
890 pst.executeUpdate();
891
892 Hive.log.info("[Hive] SYNC Executed query: " + query);
893
894 } catch (SQLException ex) {
895 Hive.log.log(Level.SEVERE, ex.getMessage(), ex);
896
897 } finally {
898 try {
899 if (pst != null) {
900 pst.close();
901 }
902 if (con != null) {
903 con.close();
904 }
905
906 } catch (SQLException ex) {
907 Hive.log.log(Level.WARNING, ex.getMessage(), ex);
908 }
909 }
910 }
911
912 public static void restoreCorruptShops(boolean all) {
913 // Grabs a query of all shops reported to be on this server, if the shop doesn't exist, the shop_backup data is converted into collection_bin data.
914 if (MOTD.contains("US-V")) {
915 return;
916 }
917 System.err.println(MOTD);
918 int lserver_num = Integer.parseInt(MOTD.substring(MOTD.indexOf("-") + 1, MOTD.indexOf(" ")));
919 if (MOTD.contains("EU-")) {
920 lserver_num += 1000;
921 }
922 if (MOTD.contains("BR-")) {
923 lserver_num += 2000;
924 }
925 if (MOTD.contains("US-YT")) {
926 lserver_num += 3000;
927 }
928
929 PreparedStatement pst = null;
930
931 try {
932
933 if (all) {
934 pst = ConnectionPool
935 .getConnection()
936 .prepareStatement(
937 "SELECT p_name, shop_backup FROM shop_database WHERE shop_backup!='null' && shop_backup IS NOT NULL && shop_backup!='' && (collection_bin IS NULL) && server_num>=0"); // collection_bin
938 // IS
939 // NOT
940 // NULL
941 // &&
942 // collection_bin!='null'
943 // &&
944
945 pst.execute();
946 } else if (!all) {
947 pst = ConnectionPool.getConnection().prepareStatement(
948 "SELECT p_name, shop_backup FROM shop_database WHERE server_num = '" + lserver_num
949 + "' && server_num!=-1 && shop_backup!='null' && shop_backup IS NOT NULL && shop_backup!='' && (collection_bin IS NULL)"); // collection_bin
950 // IS
951 // NOT
952 // NULL
953 // &&
954 // collection_bin!='null'
955 // &&
956
957 pst.execute();
958 }
959
960 ResultSet rs = pst.getResultSet();
961
962 if (!(rs.next())) {
963 log.info("[ShopMechanics] No corrupt shop data found, skipping restore function.");
964 return;
965 }
966
967 int fix_count = 0;
968 rs.beforeFirst();
969
970 while (rs.next()) {
971 String s_p_name = rs.getString("p_name");
972 String s_shop_backup = rs.getString("shop_backup");
973 if (s_shop_backup.length() > 0 && !(ShopMechanics.shop_stock.containsKey(s_p_name))) {
974 // Convert shop_backup to collection_bin.
975 setCollectionBinSQL(s_p_name, s_shop_backup);
976 fix_count++;
977 log.info("[ShopMechanics] Recovered collection bin data of " + s_p_name + " -- set collection_bin string.");
978 }
979 }
980
981 log.info("[ShopMechanics] Recovered a total of " + fix_count + " corrupt shops.");
982
983 } catch (Exception e) {
984 e.printStackTrace();
985 return;
986 }
987 }
988
989 public static void setCollectionBinSQL(String p_name, String contents) {
990 PreparedStatement pst = null;
991
992 try {
993 pst = ConnectionPool.getConnection().prepareStatement(
994 "INSERT INTO shop_database (p_name, collection_bin, server_num) VALUES('" + p_name + "', '" + contents
995 + "', '-1') ON DUPLICATE KEY UPDATE collection_bin='" + contents + "', server_num='-1'");
996
997 pst.executeUpdate();
998 } catch (SQLException ex) {
999 log.log(Level.SEVERE, ex.getMessage(), ex);
1000
1001 } finally {
1002 try {
1003 if (pst != null) {
1004 pst.close();
1005 }
1006 } catch (SQLException ex) {
1007 log.log(Level.WARNING, ex.getMessage(), ex);
1008 }
1009 }
1010 }
1011
1012 public void updateServerPopulations() {
1013 final String prefix = MOTD.substring(0, MOTD.indexOf(" "));
1014
1015 // if(prefix.equalsIgnoreCase("US-0") || prefix.equalsIgnoreCase("US-99")) { return; }
1016
1017 int players_on = Main.plugin.getServer().getOnlinePlayers().length;
1018 int players_max = Main.plugin.getServer().getMaxPlayers();
1019
1020 if (Hive.shutting_down || Hive.server_frozen || Hive.server_lock || Hive.force_kick || Hive.restart_inc) {
1021 players_on = 0;
1022 players_max = 0;
1023 // This will mark the shard as offline.
1024 }
1025
1026 CommunityMechanics.sendPacketCrossServer("@population@" + prefix + ":" + players_on + "/" + players_max, -1, true);
1027
1028 /*
1029 * Socket kkSocket = null; PrintWriter out = null; try { kkSocket = new Socket(); kkSocket.connect(new InetSocketAddress(Proxy_IP, Hive.transfer_port),
1030 * 1000); out = new PrintWriter(kkSocket.getOutputStream(), true);
1031 *
1032 * out.println("@population@" + prefix + ":" + Main.plugin.getServer().getOnlinePlayers().length + "/" + Main.plugin.getServer().getMaxPlayers());
1033 * kkSocket.close(); } catch (IOException e) { e.printStackTrace(); }finally{ out.close(); }
1034 */
1035
1036 /*
1037 * int lserver_num = Integer.parseInt(MOTD.substring(MOTD.indexOf("-") + 1, MOTD.indexOf(" "))); if(MOTD.contains("EU-")){ lserver_num += 1000; }
1038 * if(MOTD.contains("BR-")){ lserver_num += 2000; } if(MOTD.contains("US-YT")){ lserver_num += 3000; }
1039 *
1040 * for(Entry<Integer, String> data : CommunityMechanics.server_list.entrySet()){ int server_num = data.getKey(); if(server_num == lserver_num){
1041 * continue; // Don't query ourselves. We're realtime. } String ip = data.getValue(); try{ MCQuery mcQuery = new MCQuery(ip, 32778); QueryResponse
1042 * response = mcQuery.basicStat();
1043 *
1044 * int online_players = response.getOnlinePlayers(); //(int)((double)response.getOnlinePlayers() * 1.30D); int max_players = response.getMaxPlayers();
1045 *
1046 * if(online_players > max_players){ online_players = max_players; }
1047 *
1048 * String server_prefix = getServerPrefixFromNum(server_num);
1049 *
1050 * if(online_players > 0 && offline_servers.contains(server_prefix)){ offline_servers.remove(server_prefix); } server_population.put(server_num, new
1051 * ArrayList<Integer>(Arrays.asList(online_players, max_players))); } catch(Exception err){ //err.printStackTrace(); server_population.put(server_num,
1052 * new ArrayList<Integer>(Arrays.asList(0, 0))); continue; } }
1053 */
1054 }
1055
1056 public static String getServerPrefixFromNum(int server_num) {
1057 String result = "";
1058 if (server_num < 1000) {
1059 result = "US-" + server_num;
1060 }
1061 if (server_num >= 1000 && server_num < 2000) {
1062 result = "EU-" + (server_num - 1000);
1063 }
1064 if (server_num > 2000) {
1065 result = "BR-" + (server_num - 2000);
1066 }
1067 return result;
1068 }
1069
1070 @SuppressWarnings("resource")
1071 public void makeAllTables() {
1072 Connection con = null;
1073 PreparedStatement pst = null;
1074
1075 try {
1076
1077 // Combines: gems, bank_data, bank_level
1078 pst = ConnectionPool.getConnection()
1079 .prepareStatement(
1080 "CREATE TABLE IF NOT EXISTS " + "bank_database"
1081 + "(p_name VARCHAR(18) PRIMARY KEY, content LONGTEXT, level INT, money INT) ENGINE=InnoDB;");
1082 pst.executeUpdate();
1083
1084 // Combines: shop_data, cbin_data, shop_level
1085 pst = ConnectionPool.getConnection().prepareStatement(
1086 "CREATE TABLE IF NOT EXISTS " + "shop_database"
1087 + "(p_name VARCHAR(18) PRIMARY KEY, server_num INT, level INT, collection_bin LONGTEXT, shop_backup LONGTEXT) ENGINE=InnoDB;");
1088 pst.executeUpdate();
1089
1090 // Combines player_data, p_login_data, max_health, last_login, align_status, align_time
1091 pst = ConnectionPool
1092 .getConnection()
1093 .prepareStatement(
1094 "CREATE TABLE IF NOT EXISTS "
1095 + "player_database"
1096 + "(p_name VARCHAR(18) PRIMARY KEY, location TEXT, inventory LONGTEXT, hp INT, food_level INT, level INT, guild_name VARCHAR(16), combat_log BIT, last_login_time LONG, rank TINYTEXT, server_num INT, align_status VARCHAR(16), align_time LONG, toggles TEXT, pets TEXT, buddy_list TEXT, ignore_list TEXT, realm_tier INT, realm_title TINYTEXT, realm_loaded TINYINT(1), noob_player TINYINT(1), last_server TINYTEXT, ecash INT, ip TEXT, portal_shards TEXT, saved_gear TEXT, mule_inventory TEXT) ENGINE=InnoDB;");
1097 pst.executeUpdate();
1098
1099 pst = ConnectionPool.getConnection().prepareStatement(
1100 "CREATE TABLE IF NOT EXISTS " + "instance" + "(instance_template VARCHAR(18) PRIMARY KEY, times LONGTEXT) ENGINE=InnoDB;");
1101 pst.executeUpdate();
1102
1103 pst = ConnectionPool
1104 .getConnection()
1105 .prepareStatement(
1106 "CREATE TABLE IF NOT EXISTS "
1107 + "guilds"
1108 + "(guild_name VARCHAR(16) PRIMARY KEY, guild_handle VARCHAR(3), guild_color INT, guild_server_num INT, members LONGTEXT, motd LONGTEXT) ENGINE=InnoDB;");
1109 pst.executeUpdate();
1110
1111 pst = ConnectionPool
1112 .getConnection()
1113 .prepareStatement(
1114 "CREATE TABLE IF NOT EXISTS "
1115 + "reports"
1116 + "(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), type CHAR(18), reporter CHAR(18), offender CHAR(18), report TEXT, server VARCHAR(4), time DATETIME, cords TEXT) ENGINE=InnoDB;");
1117 pst.executeUpdate();
1118
1119 pst = ConnectionPool.getConnection().prepareStatement(
1120 "CREATE TABLE IF NOT EXISTS " + "statistics"
1121 + "(pname CHAR(18) PRIMARY KEY, unlawful_kills INT, lawful_kills INT, deaths INT, mob_kills INT, money INT) ENGINE=InnoDB;");
1122 pst.executeUpdate();
1123
1124 pst = ConnectionPool.getConnection().prepareStatement(
1125 "CREATE TABLE IF NOT EXISTS " + "perm_statistics"
1126 + "(pname CHAR(18) PRIMARY KEY, unlawful_kills INT, lawful_kills INT, deaths INT, mob_kills INT, money INT) ENGINE=InnoDB;");
1127 pst.executeUpdate();
1128
1129 pst = ConnectionPool
1130 .getConnection()
1131 .prepareStatement(
1132 "CREATE TABLE IF NOT EXISTS "
1133 + "ban_list"
1134 + "(pname CHAR(18) PRIMARY KEY, unban_date DATETIME, ban_reason TEXT, who_banned CHAR(18), ban_date DATETIME, unban_reason TEXT, who_unbanned CHAR(18), rank CHAR(12), ban_count TINYINT) ENGINE=InnoDB;");
1135 pst.executeUpdate();
1136
1137 pst = ConnectionPool.getConnection().prepareStatement(
1138 "CREATE TABLE IF NOT EXISTS " + "mute_map" + "(pname CHAR(18) PRIMARY KEY, unmute LONG, who_muted CHAR(18)) ENGINE=InnoDB;");
1139 pst.executeUpdate();
1140
1141 } catch (SQLException ex) {
1142 log.log(Level.SEVERE, ex.getMessage(), ex);
1143
1144 } finally {
1145 try {
1146 if (pst != null) {
1147 pst.close();
1148 }
1149 if (con != null) {
1150 con.close();
1151 }
1152
1153 } catch (SQLException ex) {
1154 log.log(Level.WARNING, ex.getMessage(), ex);
1155 }
1156 }
1157
1158 log.info("[HIVE (SLAVE Edition) Completed creating SQL tables.");
1159 }
1160
1161 public void setFirstLoginSQL(String p_name) {
1162 PreparedStatement pst = null;
1163
1164 try {
1165 pst = ConnectionPool.getConnection().prepareStatement(
1166 "INSERT INTO player_database (p_name, first_login) VALUES('" + p_name + "', '" + System.currentTimeMillis()
1167 + "') ON DUPLICATE KEY UPDATE first_login=" + System.currentTimeMillis());
1168
1169 pst.executeUpdate();
1170 } catch (SQLException ex) {
1171 log.log(Level.SEVERE, ex.getMessage(), ex);
1172
1173 } finally {
1174 try {
1175 if (pst != null) {
1176 pst.close();
1177 }
1178 } catch (SQLException ex) {
1179 log.log(Level.WARNING, ex.getMessage(), ex);
1180 }
1181 }
1182 }
1183
1184 public static void setCombatLogger(String p_name) {
1185 PreparedStatement pst = null;
1186
1187 try {
1188 pst = ConnectionPool.getConnection().prepareStatement(
1189 "INSERT INTO player_database (p_name, combat_log) VALUES('" + p_name + "', " + 1 + ") ON DUPLICATE KEY UPDATE combat_log=1");
1190
1191 pst.executeUpdate();
1192 } catch (SQLException ex) {
1193 log.log(Level.SEVERE, ex.getMessage(), ex);
1194
1195 } finally {
1196 try {
1197 if (pst != null) {
1198 pst.close();
1199 }
1200 } catch (SQLException ex) {
1201 log.log(Level.WARNING, ex.getMessage(), ex);
1202 }
1203 }
1204 }
1205
1206 public static void uploadPlayerDatabaseData(String p_name) throws SQLException {
1207 Inventory inv = null;
1208 Location loc = null;
1209
1210 String location = "";
1211
1212 int level = -1;
1213 int food_level = -1;
1214 double hp = -1;
1215 String ip = "";
1216
1217 if (Bukkit.getPlayer(p_name) != null && !(pending_upload.contains(p_name))) {
1218 Player pl = Bukkit.getPlayer(p_name);
1219 loc = pl.getLocation();
1220 inv = pl.getInventory();
1221
1222 level = HealthMechanics.getPlayerHP(pl.getName());
1223 food_level = pl.getFoodLevel();
1224 hp = pl.getHealth();
1225 } else {
1226 if (player_location.containsKey(p_name)) {
1227 loc = player_location.get(p_name);
1228 }
1229 if (player_inventory.containsKey(p_name)) {
1230 inv = player_inventory.get(p_name);
1231 }
1232
1233 level = player_level.get(p_name);
1234 hp = player_hp.get(p_name);
1235 food_level = player_food_level.get(p_name);
1236 }
1237
1238 if (loc == null || inv == null) {
1239 return;
1240 } // We don't want to upload null values for inventory / location -- could result in wipe.
1241 if (!(player_location.containsKey(p_name)) || !(player_inventory.containsKey(p_name))) {
1242 return;
1243 } // ^
1244
1245 location = convertLocationToString(loc);
1246
1247 int inv_count = 0;
1248 for (ItemStack is : inv.getContents()) {
1249 if (is == null || is.getType() == Material.AIR) {
1250 continue;
1251 }
1252 inv_count++;
1253 }
1254
1255 if (inv_count <= 0) {
1256 log.info("[HIVE] Empty inventory detected on upload for player: " + p_name);
1257 // return; // Empty inventory being uploaded.
1258 }
1259
1260 String inventory = convertInventoryToString(p_name, inv, true);
1261
1262 long align_time = 0;
1263 String align_status = "good";
1264
1265 if (KarmaMechanics.align_map.containsKey(p_name)) {
1266 align_status = KarmaMechanics.align_map.get(p_name);
1267 if (KarmaMechanics.align_time.containsKey(p_name)) {
1268 align_time = KarmaMechanics.align_time.get(p_name);
1269 }
1270 }
1271
1272 String rank = PermissionMechanics.getRank(p_name);
1273
1274 int realm_tier = 1;
1275
1276 try {
1277 realm_tier = RealmMechanics.realm_tier.get(p_name);
1278 } catch (NullPointerException npe) {
1279 log.info("[HIVE] Null 'realm tier' value for player: " + p_name);
1280 realm_tier = 1; // Null? Impossible, but ok bro.
1281 }
1282
1283 String realm_title = StringEscapeUtils.escapeSql(RealmMechanics.realm_title.get(p_name));
1284 long last_login_time = System.currentTimeMillis();
1285
1286 String buddy_list = "";
1287 String ignore_list = "";
1288
1289 if (PlayerManager.getPlayerModel(p_name).getBuddyList() != null) {
1290 List<String> lbuddy_list = PlayerManager.getPlayerModel(p_name).getBuddyList();
1291 for (String s : lbuddy_list) {
1292 buddy_list += StringEscapeUtils.escapeSql(s + ",");
1293 }
1294 }
1295
1296 if (PlayerManager.getPlayerModel(p_name).getIgnoreList() != null) {
1297 List<String> lignore_list = PlayerManager.getPlayerModel(p_name).getIgnoreList();
1298 for (String s : lignore_list) {
1299 ignore_list += StringEscapeUtils.escapeSql(s + ",");
1300 }
1301 }
1302
1303 String toggles = "";
1304
1305 if (PlayerManager.getPlayerModel(p_name).getToggleList() != null) {
1306 final List<String> ltoggle_list = PlayerManager.getPlayerModel(p_name).getToggleList();
1307 for (String s : ltoggle_list) {
1308 toggles += s + ",";
1309 }
1310 }
1311
1312 boolean new_player = HealthMechanics.noob_players.contains(p_name);
1313 int i_new_player = 0;
1314 if (new_player) {
1315 i_new_player = 1;
1316 }
1317
1318 if (player_ip.containsKey(p_name)) {
1319 for (String l_ip : player_ip.get(p_name)) {
1320 ip += l_ip + ",";
1321 }
1322 if (ip.endsWith(",")) {
1323 ip = ip.substring(0, ip.length() - 1);
1324 }
1325 }
1326
1327 String last_server = MOTD.substring(0, MOTD.indexOf(" "));
1328
1329 String portal_shard_string = "";
1330 if (player_portal_shards.containsKey(p_name)) {
1331 for (int i : player_portal_shards.get(p_name)) {
1332 portal_shard_string += i + ",";
1333 }
1334 if (portal_shard_string.endsWith(",")) {
1335 portal_shard_string = portal_shard_string.substring(0, portal_shard_string.lastIndexOf(","));
1336 }
1337 }
1338
1339 String saved_gear = "";
1340 if (KarmaMechanics.saved_gear.containsKey(p_name)) {
1341 saved_gear = StringEscapeUtils.escapeSql(convertInventoryToString(KarmaMechanics.saved_gear.get(p_name)));
1342 }
1343
1344 String mule_inventory_string = "";
1345 if (MountMechanics.mule_inventory.containsKey(p_name)) {
1346 mule_inventory_string = Hive.convertInventoryToString(null, MountMechanics.mule_inventory.get(p_name), false);
1347 }
1348 if (mule_inventory_string.equalsIgnoreCase("") && !MountMechanics.mule_inventory.containsKey(p_name)) {
1349 if (MountMechanics.mule_itemlist_string.containsKey(p_name)) {
1350 mule_inventory_string = StringEscapeUtils.escapeSql(MountMechanics.mule_itemlist_string.get(p_name));
1351 }
1352 }
1353
1354 String achievments = "";
1355 if (PlayerManager.getPlayerModel(p_name).getAchievements() != null) {
1356 achievments = PlayerManager.getPlayerModel(p_name).getAchievements();
1357 }
1358
1359 String ecash_storage = "";
1360 if (EcashMechanics.ecash_storage_map.containsKey(p_name)) {
1361 ecash_storage = StringEscapeUtils.escapeSql(EcashMechanics.ecash_storage_map.get(p_name));
1362 }
1363
1364 PreparedStatement pst = null;
1365
1366 // 15 KEYS! -- Monster Query.
1367 pst = ConnectionPool
1368 .getConnection()
1369 .prepareStatement(
1370 "INSERT INTO player_database (p_name, location, inventory, hp, food_level, level, last_login_time, rank, align_status, align_time, toggles, buddy_list, ignore_list, realm_tier, realm_title, noob_player, combat_log, last_server, ip, portal_shards, saved_gear, mule_inventory, achievments, ecash_storage) "
1371 + "VALUES('"
1372 + p_name
1373 + "', '"
1374 + location
1375 + "', '"
1376 + StringEscapeUtils.escapeSql(inventory)
1377 + "', '"
1378 + hp
1379 + "', '"
1380 + food_level
1381 + "', '"
1382 + level
1383 + "', '"
1384 + last_login_time
1385 + "', '"
1386 + rank
1387 + "', '"
1388 + align_status
1389 + "', '"
1390 + align_time
1391 + "', '"
1392 + toggles
1393 + "', '"
1394 + buddy_list
1395 + "', '"
1396 + ignore_list
1397 + "', '"
1398 + realm_tier
1399 + "', '"
1400 + realm_title
1401 + "', '"
1402 + i_new_player
1403 + "', 0, '"
1404 + last_server
1405 + "', '"
1406 + ip
1407 + "', '"
1408 + portal_shard_string
1409 + "', '"
1410 + saved_gear
1411 + "', '"
1412 + mule_inventory_string
1413 + "', '"
1414 + achievments
1415 + "', '"
1416 + ecash_storage
1417 + "') "
1418 +
1419
1420 "ON DUPLICATE KEY UPDATE location='"
1421 + location
1422 + "', inventory='"
1423 + StringEscapeUtils.escapeSql(inventory)
1424 + "', hp='"
1425 + hp
1426 + "', food_level='"
1427 + food_level
1428 + "', level='"
1429 + level
1430 + "', "
1431 + "last_login_time='"
1432 + last_login_time
1433 + "', rank='"
1434 + rank
1435 + "', align_status='"
1436 + align_status
1437 + "', align_time='"
1438 + align_time
1439 + "', toggles='"
1440 + toggles
1441 + "', buddy_list='"
1442 + buddy_list
1443 + "', "
1444 + "ignore_list='"
1445 + ignore_list
1446 + "', realm_tier='"
1447 + realm_tier
1448 + "', realm_title='"
1449 + realm_title
1450 + "', noob_player='"
1451 + i_new_player
1452 + "', combat_log=0, last_server='"
1453 + last_server
1454 + "', ip='"
1455 + ip
1456 + "', portal_shards='"
1457 + portal_shard_string
1458 + "', saved_gear='"
1459 + saved_gear
1460 + "', mule_inventory='"
1461 + mule_inventory_string
1462 + "', achievments='"
1463 + achievments + "', ecash_storage='" + ecash_storage + "'");
1464
1465 pst.executeUpdate();
1466 }
1467
1468 public Object downloadPlayerDatabaseData(String p_name) {
1469 // Any # = Don't let them log in, they're on another server or something, the # will = the server. (server_num >= 0)
1470 // false = Data does not exist / error. (server_num = -2)
1471 // true = Everything is fine. (server_num = -1)
1472
1473 online_today.remove(p_name);
1474 Hive.player_inventory.remove(p_name);
1475 Hive.player_location.remove(p_name);
1476 Hive.player_hp.remove(p_name);
1477 Hive.player_level.remove(p_name);
1478 Hive.player_food_level.remove(p_name);
1479 Hive.player_armor_contents.remove(p_name);
1480 Hive.player_ecash.remove(p_name);
1481 Hive.player_sdays_left.remove(p_name);
1482 KarmaMechanics.align_map.remove(p_name);
1483 KarmaMechanics.align_time.remove(p_name);
1484 KarmaMechanics.saved_gear.remove(p_name);
1485 PlayerManager.getPlayerModel(p_name).setIgnoreList(new ArrayList<String>());
1486 PlayerManager.getPlayerModel(p_name).setBuddyList(new ArrayList<String>());
1487 PlayerManager.getPlayerModel(p_name).setToggleList(new ArrayList<String>());
1488 HealthMechanics.noob_player_warning.remove(p_name);
1489 HealthMechanics.noob_players.remove(p_name);
1490 RealmMechanics.realm_title.remove(p_name);
1491 RealmMechanics.realm_tier.remove(p_name);
1492 MountMechanics.mule_inventory.remove(p_name);
1493 MountMechanics.mule_itemlist_string.remove(p_name);
1494
1495 PreparedStatement pst = null;
1496
1497 try {
1498 pst = ConnectionPool
1499 .getConnection()
1500 .prepareStatement(
1501 "SELECT server_num, location, inventory, hp, food_level, level, first_login, combat_log, last_login_time, rank, align_status, align_time, toggles, pets, buddy_list, ignore_list, realm_tier, realm_title, realm_loaded, noob_player, ecash, ip, sdays_left, portal_shards, saved_gear, lost_gear, mule_inventory, achievments, online_today, ecash_storage FROM player_database WHERE p_name = '"
1502 + p_name + "'");
1503
1504 pst.execute();
1505 ResultSet rs = pst.getResultSet();
1506
1507 if (!(rs.next())) {
1508 // Could either be problem with SQL (unlikely, would throw exception), or it's a new player.
1509 log.info("[HIVE (Slave Edition)] No PLAYER DATA found for " + p_name + ", return null.");
1510 return false;
1511 }
1512
1513 List<Object> data = new ArrayList<Object>();
1514
1515 int server_num = rs.getInt("server_num");
1516 if (server_num >= 0) {
1517 return server_num; // They're online somewhere, or they're new!
1518 }
1519
1520 long first_login = rs.getLong("first_login");
1521 player_first_login.put(p_name, first_login);
1522
1523 int combat_log = rs.getInt("combat_log");
1524 if (combat_log == 1) {
1525 HealthMechanics.combat_logger.add(p_name); // Combat logger, you will enjoy a slow death! (not really!)
1526 }
1527
1528 int l_online_today = rs.getInt("online_today");
1529 if (l_online_today != 1) {
1530 online_today.add(p_name);
1531 }
1532
1533 PlayerManager.getPlayerModel(p_name).setLastLocalLogin(rs.getLong("last_login_time"));
1534 // Used for certain cooldown events and such.
1535
1536 PermissionMechanics.setRank(p_name, rs.getString("rank"), false);
1537 // Set's server rank, needed for cross-server chat events.
1538 // false = Don't upload the new rank -- we're already pulling it from DB so no need.
1539
1540 KarmaMechanics.align_time.put(p_name, rs.getInt("align_time"));
1541 String align_status = rs.getString("align_status");
1542 if (align_status == null || align_status.equalsIgnoreCase("null")) {
1543 align_status = "good";
1544 }
1545
1546 KarmaMechanics.setAlignment(p_name, align_status, 1);
1547 // Karma alignment and seconds left until it expires.
1548
1549 List<String> ltoggle_list = new ArrayList<String>();
1550 String toggles = rs.getString("toggles");
1551 if (toggles != null) {
1552 for (String s : toggles.split(",")) {
1553 if (s.length() > 0) {
1554 ltoggle_list.add(s);
1555 }
1556 }
1557 }
1558
1559 PlayerManager.getPlayerModel(p_name).setToggleList(ltoggle_list);
1560 // Toggles for a multitude of different settings.
1561
1562 List<String> pet_data = new ArrayList<String>();
1563 String pet_list = rs.getString("pets");
1564 if (pet_list != null) {
1565 if (pet_list.contains(",")) {
1566 for (String s : pet_list.split(",")) {
1567 pet_data.add(s);
1568 }
1569 } else {
1570 pet_data.add(pet_list);
1571 }
1572 }
1573 PetMechanics.player_pets.put(p_name, pet_data);
1574 // Sets up pet ownership for the player, will spawn them eggs and such.
1575
1576 List<String> lbuddy_list = new ArrayList<String>();
1577 String buddy_list = rs.getString("buddy_list");
1578 if (buddy_list != null && buddy_list.contains(",")) {
1579 for (String s : buddy_list.split(",")) {
1580 if (s.length() > 0) {
1581 lbuddy_list.add(s);
1582 }
1583 }
1584 }
1585
1586 PlayerManager.getPlayerModel(p_name).setBuddyList(lbuddy_list);
1587 // Friend list!
1588
1589 List<String> lignore_list = new ArrayList<String>();
1590 String ignore_list = rs.getString("ignore_list");
1591 if (ignore_list != null && ignore_list.contains(",")) {
1592 for (String s : ignore_list.split(",")) {
1593 if (s.length() > 0) {
1594 lignore_list.add(s);
1595 }
1596 }
1597 }
1598
1599 PlayerManager.getPlayerModel(p_name).setIgnoreList(lignore_list);
1600 // Ignore list!
1601
1602 RealmMechanics.realm_tier.put(p_name, rs.getInt("realm_tier"));
1603 RealmMechanics.realm_title.put(p_name, rs.getString("realm_title"));
1604 RealmMechanics.realm_loaded_status.put(p_name, rs.getBoolean("realm_loaded"));
1605 // Realm tier (for size) and the description showed on right click.
1606
1607 int noob_player = rs.getInt("noob_player");
1608 if (noob_player == 1) {
1609 HealthMechanics.noob_players.add(p_name);
1610 }
1611
1612 String loc_s = rs.getString("location");
1613 Location loc = null;
1614 if (loc_s == null) {
1615 log.info("[HIVE (Slave Edition)] No LOCATION data found for " + p_name + ", return null.");
1616 return false;
1617 } else if (loc_s != null) {
1618 loc = convertStringToLocation(loc_s);
1619 }
1620
1621 String inventory_s = rs.getString("inventory");
1622 if (inventory_s == null) {
1623 log.info("[HIVE (Slave Edition)] No INVENTORY data found for " + p_name + ", return null.");
1624 return false;
1625 }
1626
1627 int ecash = rs.getInt("ecash");
1628 if (ecash > 0) {
1629 player_ecash.put(p_name, ecash); // Store E-CASH locally -- they'll need to relog to get any new E-CASH.
1630 }
1631
1632 int sdays_left = rs.getInt("sdays_left");
1633 if (sdays_left > 0) {
1634 player_sdays_left.put(p_name, sdays_left);
1635 }
1636
1637 List<String> ip_list = new ArrayList<String>();
1638
1639 String raw_ip_list = rs.getString("ip");
1640 if (raw_ip_list != null && raw_ip_list.length() > 0) {
1641 if (raw_ip_list.contains(",")) {
1642 for (String s_ip : raw_ip_list.split(",")) {
1643 ip_list.add(s_ip);
1644 }
1645 } else { // Only 1 IP in the DB.
1646 ip_list.add(raw_ip_list);
1647 }
1648 }
1649 if (local_player_ip.containsKey(p_name) && !ip_list.contains(local_player_ip.get(p_name))) {
1650 ip_list.add(local_player_ip.get(p_name));
1651 }
1652
1653 player_ip.put(p_name, ip_list);
1654
1655 String portal_shard_string = rs.getString("portal_shards");
1656 List<Integer> portal_shards = new ArrayList<Integer>();
1657 if (portal_shard_string != null && portal_shard_string.contains(",") && portal_shard_string.split(",").length == 5) {
1658 for (String s : portal_shard_string.split(",")) {
1659 int i = Integer.parseInt(s);
1660 portal_shards.add(i);
1661 }
1662 player_portal_shards.put(p_name, portal_shards);
1663 } else {
1664 player_portal_shards.put(p_name, new ArrayList<Integer>(Arrays.asList(0, 0, 0, 0, 0)));
1665 }
1666
1667 int level = rs.getInt("level");
1668 double hp = rs.getInt("hp");
1669 int food_level = rs.getInt("food_level");
1670
1671 String saved_gear = rs.getString("saved_gear");
1672 if (saved_gear != null && saved_gear.length() > 0) {
1673 List<ItemStack> sg_list = convertStringToInventoryString(saved_gear);
1674 KarmaMechanics.saved_gear.put(p_name, sg_list);
1675 if (!HealthMechanics.combat_logger.contains(p_name)) {
1676 // If combat_logger contains them, they'll be killed on login anyway. We don't want to double kill.
1677 HealthMechanics.combat_logger.add(p_name); // Use this method, it actually works.
1678 }
1679 }
1680
1681 String lost_gear = rs.getString("lost_gear");
1682 if (lost_gear != null && lost_gear.length() > 0) {
1683 KarmaMechanics.lost_gear.put(p_name, lost_gear);
1684 }
1685
1686 String mule_inventory = rs.getString("mule_inventory");
1687 if (mule_inventory != null && mule_inventory.contains("@item@")) {
1688 // We put the ItemStack list into a hashmap, when they OPEN the mule, it will generate the inventory and the slots based on the mule they're
1689 // using.;
1690 MountMechanics.mule_itemlist_string.put(p_name, mule_inventory);
1691 }
1692
1693 String achievments = rs.getString("achievments");
1694 if (achievments == null) {
1695 achievments = "";
1696 }
1697 PlayerManager.getPlayerModel(p_name).setAchievements(achievments);
1698
1699 String ecash_storage = rs.getString("ecash_storage");
1700 if (ecash_storage != null) {
1701 EcashMechanics.ecash_storage_map.put(p_name, ecash_storage);
1702 }
1703
1704 data.add(loc);
1705 data.add(inventory_s);
1706 data.add(level);
1707 data.add((double) hp);
1708 data.add(food_level);
1709
1710 remote_player_data.put(p_name, data);
1711
1712 } catch (Exception ex) {
1713 ex.printStackTrace();
1714 return ex;
1715
1716 } finally {
1717 try {
1718 if (pst != null) {
1719 pst.close();
1720 }
1721
1722 } catch (SQLException ex) {
1723 log.log(Level.WARNING, ex.getMessage(), ex);
1724 return false;
1725 }
1726 }
1727
1728 return true;
1729 }
1730
1731 public static String convertInventoryToString(List<ItemStack> inv) {
1732 // @item@Slot:ItemID-Amount.Durability#Item_Name#$Item_Lore$[lam1]lam_color[lam2]
1733 // @item@1:267-1.54#Magic Sword#$DMG: 5 - 7, CRIT: 5%$@item@
1734
1735 String return_string = "";
1736 int slot = -1;
1737
1738 for (ItemStack is : inv) {
1739 slot++;
1740 if (is == null || is.getType() == Material.AIR) {
1741 continue;
1742 }
1743
1744 String i_name = "";
1745 if (is.hasItemMeta() && is.getItemMeta().hasDisplayName()) {
1746 i_name = is.getItemMeta().getDisplayName();
1747 } else {
1748 // Default name.
1749 i_name = "null";
1750 }
1751
1752 String i_lore = "";
1753 if (is.hasItemMeta() && is.getItemMeta().hasLore()) {
1754 for (String s : is.getItemMeta().getLore()) {
1755 i_lore = i_lore + "," + s;
1756 }
1757 } else {
1758 // No lore.
1759 i_lore = "null";
1760 }
1761
1762 return_string = return_string
1763 + ("@item@" + slot + ":" + is.getTypeId() + "-" + is.getAmount() + "." + is.getDurability() + "#" + i_name + "#" + "$" + i_lore + "$");
1764 if (is.hasItemMeta() && is.getItemMeta() instanceof LeatherArmorMeta) {
1765 return_string = return_string + "[lam1]" + ((LeatherArmorMeta) is.getItemMeta()).getColor().asBGR() + "[lam2]";
1766 }
1767 }
1768
1769 return return_string;
1770 }
1771
1772 public static String convertInventoryToString(String p_name, Inventory inv, boolean player) {
1773 // @item@Slot:ItemID-Amount.Durability#Item_Name#$Item_Lore$[lam1]lam_color[lam2]
1774 // @item@1:267-1.54#Magic Sword#$DMG: 5 - 7, CRIT: 5%$@item@
1775
1776 String return_string = "";
1777 int slot = -1;
1778 for (ItemStack is : inv.getContents()) {
1779 slot++;
1780 if (is == null || is.getType() == Material.AIR) {
1781 continue;
1782 }
1783
1784 String i_name = "";
1785 if (is.hasItemMeta() && is.getItemMeta().hasDisplayName()) {
1786 i_name = is.getItemMeta().getDisplayName();
1787 } else {
1788 // Default name.
1789 i_name = "null";
1790 }
1791
1792 String i_lore = "";
1793 if (is.hasItemMeta() && is.getItemMeta().hasLore()) {
1794 for (String s : is.getItemMeta().getLore()) {
1795 i_lore = i_lore + "," + s;
1796 }
1797 } else {
1798 // No lore.
1799 i_lore = "null";
1800 }
1801
1802 while (i_lore.contains(",,")) {
1803 i_lore = i_lore.replace(",,", ",");
1804 }
1805
1806 return_string = return_string
1807 + ("@item@" + slot + ":" + is.getTypeId() + "-" + is.getAmount() + "." + is.getDurability() + "#" + i_name + "#" + "$" + i_lore + "$");
1808 if (is.hasItemMeta() && is.getItemMeta() instanceof LeatherArmorMeta) {
1809 return_string = return_string + "[lam1]" + ((LeatherArmorMeta) is.getItemMeta()).getColor().asBGR() + "[lam2]";
1810 }
1811 }
1812
1813 List<ItemStack> armor_contents = new ArrayList<ItemStack>();
1814 if (player) {
1815 if (Bukkit.getPlayer(p_name) != null) {
1816 Player owner = Bukkit.getPlayer(p_name);
1817 for (ItemStack is : owner.getInventory().getArmorContents()) {
1818 armor_contents.add(is);
1819 }
1820 } else {
1821 if (player_armor_contents.containsKey(p_name)) {
1822 for (ItemStack is : player_armor_contents.get(p_name)) {
1823 armor_contents.add(is);
1824 }
1825 }
1826 }
1827
1828 if (armor_contents.size() > 0) {
1829 for (ItemStack is : armor_contents) {
1830 slot++;
1831 if (is == null) {
1832 continue;
1833 }
1834
1835 String i_name = "";
1836 if (is.hasItemMeta() && is.getItemMeta().hasDisplayName()) {
1837 i_name = is.getItemMeta().getDisplayName();
1838 } else {
1839 // Default name.
1840 i_name = "null";
1841 }
1842
1843 String i_lore = "";
1844 if (is.hasItemMeta() && is.getItemMeta().hasLore()) {
1845 for (String s : is.getItemMeta().getLore()) {
1846 i_lore = i_lore + "," + s;
1847 }
1848 } else {
1849 // No lore.
1850 i_lore = "null";
1851 }
1852
1853 return_string = return_string
1854 + ("@item@" + slot + ":" + is.getTypeId() + "-" + is.getAmount() + "." + is.getDurability() + "#" + i_name + "#" + "$" + i_lore + "$");
1855 if (is.hasItemMeta() && is.getItemMeta() instanceof LeatherArmorMeta) {
1856 return_string = return_string + "[lam1]" + ((LeatherArmorMeta) is.getItemMeta()).getColor().asBGR() + "[lam2]";
1857 }
1858 }
1859 }
1860 }
1861
1862 return return_string;
1863 }
1864
1865 public static List<ItemStack> convertStringToInventoryString(String inventory_string) {
1866 List<ItemStack> is_list = new ArrayList<ItemStack>();
1867 // int expected_item_size = inventory_string.split("@item@").length;
1868 // int slot_cache = -1;
1869
1870 for (String s : inventory_string.split("@item@")) {
1871 // slot_cache++;
1872
1873 if (s.length() <= 1) {
1874 continue;
1875 }
1876
1877 // int slot = Integer.parseInt(s.substring(0, s.indexOf(":")));
1878 int item_id = Integer.parseInt(s.substring(s.indexOf(":") + 1, s.indexOf("-")));
1879 int amount = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.indexOf(".")));
1880 short durability = Short.parseShort(s.substring(s.indexOf(".") + 1, s.indexOf("#")));
1881
1882 String i_name = s.substring(s.indexOf("#") + 1, s.lastIndexOf("#"));
1883 String i_lore = s.substring(s.indexOf("$") + 1, s.lastIndexOf("$"));
1884
1885 Color leather_armor_color = null;
1886 if (s.contains("[lam1]")) {
1887 leather_armor_color = Color.fromBGR(Integer.parseInt(s.substring(s.indexOf("[lam1]") + 6, s.lastIndexOf("[lam2]"))));
1888 }
1889
1890 ItemStack is = new ItemStack(Material.getMaterial(item_id), amount, durability);
1891
1892 while (i_lore.contains(",,")) {
1893 i_lore = i_lore.replace(",,", ",");
1894 }
1895
1896 List<String> splitlore = new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(i_lore.split(","))));
1897 i_lore = Joiner.on(',').join(splitlore);
1898
1899 if (is.getType() == Material.POTION && is.getDurability() > 0) {
1900 // Renames potion to Instant Heal.
1901
1902 is = ItemMechanics.signNewCustomItem(Material.getMaterial(item_id), durability, i_name, i_lore);
1903 is_list.add(is);
1904 continue;
1905 }
1906
1907 if (is.getType() == Material.WRITTEN_BOOK) {
1908 continue; // TODO: Code book loading.
1909 }
1910
1911 ItemMeta im = is.getItemMeta();
1912
1913 if (!(i_name.equalsIgnoreCase("null"))) {
1914 // Custom name!
1915 im.setDisplayName(i_name);
1916 }
1917
1918 if (!(i_lore.equalsIgnoreCase("null"))) {
1919 // Lore!
1920 List<String> all_lore = new ArrayList<String>();
1921
1922 for (String lore : i_lore.split(",")) {
1923 if (lore.length() > 1) {
1924 all_lore.add(lore);
1925 }
1926 }
1927 im.setLore(all_lore);
1928 }
1929
1930 if (!(leather_armor_color == null)) {
1931 ((LeatherArmorMeta) im).setColor(leather_armor_color);
1932 }
1933
1934 if (!(i_name.equalsIgnoreCase("null")) || !(i_lore.equalsIgnoreCase("null"))) {
1935 is.setItemMeta(im);
1936 }
1937
1938 is_list.add(is);
1939 }
1940
1941 return is_list;
1942 }
1943
1944 public static Inventory convertStringToInventory(Player pl, String inventory_string, String inventory_name, int slots) {
1945 Inventory inv = null;
1946 // int slot_cache = -1;
1947 int expected_item_size = inventory_string.split("@item@").length - 1;
1948
1949 if (pl == null && inventory_name != null) {
1950 // Using inventory.
1951 inv = Bukkit.createInventory(null, slots, inventory_name);
1952 }
1953 for (String s : inventory_string.split("@item@")) {
1954 // slot_cache++;
1955
1956 if (s.length() <= 1 || s.equalsIgnoreCase("null")) {
1957 continue;
1958 }
1959
1960 int slot = Integer.parseInt(s.substring(0, s.indexOf(":")));
1961
1962 if (inventory_name != null && inventory_name.startsWith("Bank Chest")) {
1963 if (slot > expected_item_size && (slot > (slots - 1))) { // slots - 1, 0 index = start
1964 slot = inv.firstEmpty();
1965 }
1966 }
1967
1968 if (s.length() <= 1) {
1969 continue;
1970 }
1971
1972 int item_id = Integer.parseInt(s.substring(s.indexOf(":") + 1, s.indexOf("-")));
1973 int amount = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.indexOf(".")));
1974 short durability = Short.parseShort(s.substring(s.indexOf(".") + 1, s.indexOf("#")));
1975
1976 String i_name = s.substring(s.indexOf("#") + 1, s.lastIndexOf("#"));
1977 String i_lore = s.substring(s.indexOf("$") + 1, s.lastIndexOf("$"));
1978
1979 Color leather_armor_color = null;
1980 if (s.contains("[lam1]")) {
1981 leather_armor_color = Color.fromBGR(Integer.parseInt(s.substring(s.indexOf("[lam1]") + 6, s.lastIndexOf("[lam2]"))));
1982 }
1983
1984 ItemStack is = new ItemStack(Material.getMaterial(item_id), amount, durability);
1985
1986 List<String> splitlore = new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(i_lore.split(","))));
1987 i_lore = Joiner.on(',').join(splitlore);
1988
1989 if (is.getType() == Material.POTION && is.getDurability() > 0) {
1990 // Renames potion to Instant Heal.
1991
1992 is = ItemMechanics.signNewCustomItem(Material.getMaterial(item_id), durability, i_name, i_lore);
1993 if (pl != null) {
1994 pl.getInventory().setItem(slot, is);
1995 } else if (inv != null) {
1996 inv.setItem(slot, is);
1997 }
1998 continue;
1999 }
2000
2001 if (is.getType() == Material.WRITTEN_BOOK) {
2002 continue; // TODO: Code book loading.
2003 }
2004
2005 ItemMeta im = is.getItemMeta();
2006
2007 if (!(i_name.equalsIgnoreCase("null"))) {
2008 // Custom name!
2009 im.setDisplayName(i_name);
2010 }
2011
2012 if (!(i_lore.equalsIgnoreCase("null"))) {
2013 // Lore!
2014 List<String> all_lore = new ArrayList<String>();
2015
2016 for (String lore : i_lore.split(",")) {
2017 if (lore.length() > 1) {
2018 all_lore.add(lore);
2019 }
2020 }
2021 im.setLore(all_lore);
2022 }
2023
2024 if (!(leather_armor_color == null)) {
2025 ((LeatherArmorMeta) im).setColor(leather_armor_color);
2026 }
2027
2028 if (!(i_name.equalsIgnoreCase("null")) || !(i_lore.equalsIgnoreCase("null"))) {
2029 is.setItemMeta(im);
2030 }
2031
2032 if (pl != null) {
2033 pl.getInventory().setItem(slot, is);
2034 } else if (inv != null) {
2035 inv.setItem(slot, is);
2036 }
2037 }
2038
2039 if (inv != null) {
2040 return inv;
2041 } else {
2042 return null;
2043 }
2044 }
2045
2046 public static String convertLocationToString(Location l) {
2047 // 0,0,0:yaw$pitch
2048 DecimalFormat df = new DecimalFormat("#.####");
2049 return (df.format(l.getBlockX()) + "," + df.format(l.getBlockY()) + "," + df.format(l.getBlockZ()) + ":" + df.format(l.getYaw()) + "$" + df.format(l
2050 .getPitch()));
2051 }
2052
2053 public Location convertStringToLocation(String s_l) {
2054 double x = Double.parseDouble(s_l.substring(0, s_l.indexOf(",")));
2055 double y = Double.parseDouble(s_l.substring(s_l.indexOf(",") + 1, s_l.indexOf(",", s_l.indexOf(",") + 1)));
2056 double z = Double.parseDouble(s_l.substring(s_l.lastIndexOf(",") + 1, s_l.indexOf(":")));
2057
2058 float yaw = Float.parseFloat(s_l.substring(s_l.indexOf(":") + 1, s_l.indexOf("$")));
2059 float pitch = Float.parseFloat(s_l.substring(s_l.indexOf("$") + 1, s_l.length()));
2060
2061 Location loc = new Location(Bukkit.getWorlds().get(0), x, y, z, yaw, pitch);
2062 return loc;
2063 }
2064
2065 public boolean hasAccountData(String p_name) {
2066 PreparedStatement pst;
2067
2068 try {
2069 pst = ConnectionPool.getConnection().prepareStatement("SELECT location FROM player_database WHERE p_name = '" + p_name + "'");
2070
2071 pst.execute();
2072 ResultSet rs = pst.getResultSet();
2073
2074 if (!(rs.next()) || rs.getString("location") == null) {
2075 log.info("[HIVE (Slave Edition)] No PLAYER DATA found for " + p_name + ", return null.");
2076 return false;
2077 }
2078
2079 String s_loc = rs.getString("location");
2080 if (s_loc != null && s_loc.length() > 1) {
2081 return true;
2082 }
2083 } catch (SQLException e) {
2084 e.printStackTrace();
2085 return false;
2086 }
2087
2088 return false;
2089 }
2090
2091 public static String getServerRank(String p_name) {
2092
2093 // rank_forumgroup.put("default", 2);
2094 // rank_forumgroup.put("pmod", 11);
2095 // rank_forumgroup.put("sub", 75);
2096 // rank_forumgroup.put("sub+", 76);
2097 // rank_forumgroup.put("sub++", 79);
2098 // rank_forumgroup.put("gm", 72);
2099 // rank_forumgroup.put("wd", 72);
2100
2101 PreparedStatement pst;
2102
2103 try {
2104 pst = ConnectionPool.getConnection().prepareStatement("SELECT rank FROM player_database WHERE p_name = '" + p_name + "'");
2105
2106 pst.execute();
2107 ResultSet rs = pst.getResultSet();
2108
2109 if (!(rs.next())) {
2110 log.info("[HIVE (Slave Edition)] No PLAYER DATA found for " + p_name + ", return null.");
2111 return "default";
2112 }
2113
2114 String rank = rs.getString("rank");
2115 if (rank != null && rank.length() > 1) {
2116 return rank;
2117 }
2118 } catch (SQLException e) {
2119 e.printStackTrace();
2120 return null;
2121 }
2122
2123 return "default";
2124 }
2125
2126 /*
2127 * public boolean isPremiumBetaTester(String p_name){ Connection con = null; PreparedStatement pst = null;
2128 *
2129 * try { // con = DriverManager.getConnection(site_sql_url, site_sql_user, site_sql_password); pst = WebsiteConnectionPool.getConneciton().prepareStatement(
2130 * "SELECT userid FROM userfield WHERE field5 = '" + p_name + "'");
2131 *
2132 * pst.execute(); ResultSet rs = pst.getResultSet(); if(!(rs.next())){ return false; //return "Unregistered"; // Player is not registered on forums. }
2133 *
2134 * int userid = rs.getInt("userid"); pst = WebsiteConnectionPool.getConneciton().prepareStatement(
2135 * "SELECT usergroupid, membergroupids FROM user WHERE userid = '" + userid + "'");
2136 *
2137 * pst.execute(); rs = pst.getResultSet(); if(!(rs.next())){ return false; //return "nominecraftname"; // Player is not registered on forums. } int
2138 * primary_rank = rs.getInt("usergroupid"); if(primary_rank == 9){ return true; } else if(primary_rank != 9){ // 9 == Beta Tester String all_groups =
2139 * rs.getString("membergroupids"); if(all_groups.contains("9")){ return true; } }
2140 *
2141 * } catch (SQLException ex) { log.log(Level.SEVERE, ex.getMessage(), ex);
2142 *
2143 * } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); }
2144 *
2145 * } catch (SQLException ex) { log.log(Level.WARNING, ex.getMessage(), ex); } }
2146 *
2147 * return false; }
2148 */
2149
2150 public boolean isThisRootMachine() {
2151 File f = new File("key");
2152 if (f.exists()) {
2153 return true;
2154 } else {
2155 return false;
2156 }
2157 }
2158
2159 public void setAllPlayersAsOffline() {
2160 Connection con = null;
2161 PreparedStatement pst = null;
2162
2163 try {
2164 for (String p_name : player_inventory.keySet()) {
2165 pst = ConnectionPool.getConnection().prepareStatement(
2166 "INSERT INTO player_database (p_name, server_num)" + " VALUES" + "('" + p_name + "', '" + (-1)
2167 + "') ON DUPLICATE KEY UPDATE server_num = '" + (-1) + "'");
2168
2169 pst.executeUpdate();
2170
2171 }
2172 } catch (SQLException ex) {
2173 log.log(Level.SEVERE, ex.getMessage(), ex);
2174
2175 } finally {
2176 try {
2177 if (pst != null) {
2178 pst.close();
2179 }
2180 if (con != null) {
2181 con.close();
2182 }
2183
2184 } catch (SQLException ex) {
2185 log.log(Level.WARNING, ex.getMessage(), ex);
2186 }
2187 }
2188
2189 log.info("[HIVE (SLAVE Edition)] Set all players to 'offline' on p_login_data table.");
2190
2191 }
2192
2193 public void setSystemPath() {
2194 CodeSource codeSource = Hive.class.getProtectionDomain().getCodeSource();
2195 File jarFile = null;
2196 try {
2197 jarFile = new File(codeSource.getLocation().toURI().getPath());
2198 } catch (URISyntaxException e1) {
2199 }
2200 rootDir = jarFile.getParentFile().getPath();
2201 int rep = rootDir.contains("/plugins") ? rootDir.indexOf("/plugins") : rootDir.indexOf("\\plugins");
2202 rootDir = rootDir.substring(0, rep);
2203 }
2204
2205 public static void sendTimeout(int time) {
2206 if (time == 10) {
2207 Bukkit.getServer().broadcastMessage(
2208 ChatColor.RED + "" + ChatColor.BOLD + ">>" + ChatColor.RED + " The server will be " + ChatColor.UNDERLINE + "REBOOTING" + ChatColor.RED
2209 + " in " + ChatColor.BOLD + time + "s...");
2210 Bukkit.getServer().broadcastMessage(
2211 ChatColor.RED + "" + ChatColor.BOLD + ">>" + ChatColor.RED + " Removing all open shops and saving to Collection-Bin...");
2212 } else {
2213 Bukkit.getServer().broadcastMessage(
2214 ChatColor.RED + "" + ChatColor.BOLD + ">>" + ChatColor.RED + " The server will be " + ChatColor.UNDERLINE + "REBOOTING" + ChatColor.RED
2215 + " in " + ChatColor.BOLD + time + "s...");
2216 // Bukkit.getServer().broadcastMessage(ChatColor.RED + "" + ChatColor.BOLD + ">>" + ChatColor.RED + " The server will be " + ChatColor.UNDERLINE +
2217 // "REBOOTING" + ChatColor.RED + " in " + ChatColor.BOLD + time + "s...");
2218 }
2219 }
2220
2221 public static boolean isPlayerOnline(String p_name) {
2222 int server_num = getPlayerServer(p_name, true);
2223 if (server_num <= -1) {
2224 return false;
2225 }
2226 if (pending_upload.contains(p_name)) {
2227 return false;
2228 } // They're not literally online.
2229 else {
2230 return true;
2231 }
2232 }
2233
2234 public static int getPlayerServer(String p_name, boolean sql) {
2235 String motd = Bukkit.getMotd();
2236
2237 if (Bukkit.getPlayer(p_name) != null && Bukkit.getPlayer(p_name).isOnline()) {
2238 if (motd.contains("US-YT")) {
2239 return 3001;
2240 }
2241 int server_num = Integer.parseInt(motd.substring(motd.indexOf("-") + 1, motd.indexOf(" ")));
2242 if (motd.contains("EU-")) {
2243 server_num += 1000;
2244 }
2245 if (MOTD.contains("BR-")) {
2246 server_num += 2000;
2247 }
2248 if (motd.contains("US-YT")) {
2249 server_num += 3000;
2250 }
2251 return server_num;
2252 }
2253
2254 if (PlayerManager.getPlayerModel(p_name).getServerNum() > 0)
2255 return PlayerManager.getPlayerModel(p_name).getServerNum();
2256 // If it doesn't contain, the servers could not be synced properly or they're a -2, just let SQL take care of the rest.
2257
2258 if (sql == true) {
2259 // p_name = p_name.replaceAll("\"", "\\");
2260
2261 Connection con = null;
2262 PreparedStatement pst = null;
2263
2264 try {
2265 pst = ConnectionPool.getConnection().prepareStatement("SELECT server_num FROM player_database WHERE p_name = '" + p_name + "'");
2266
2267 pst.execute();
2268
2269 ResultSet rs = pst.getResultSet();
2270 if (!rs.next()) {
2271 return -2;
2272 } // NEVER been online.
2273 return rs.getInt("server_num");
2274
2275 } catch (SQLException ex) {
2276 log.log(Level.SEVERE, ex.getMessage(), ex);
2277 return -1;
2278
2279 } finally {
2280 try {
2281 if (pst != null) {
2282 pst.close();
2283 }
2284 if (con != null) {
2285 con.close();
2286 }
2287
2288 } catch (SQLException ex) {
2289 log.log(Level.WARNING, ex.getMessage(), ex);
2290 }
2291 }
2292 }
2293 return -1;
2294
2295 }
2296
2297 public void setPlayerServer(final String p_name) {
2298 final String motd = Bukkit.getMotd();
2299 int lserver_num = 1;
2300 if (motd.contains("US-YT")) {
2301 lserver_num += 3000;
2302 }
2303 try {
2304 lserver_num = Integer.parseInt(motd.substring(motd.indexOf("-") + 1, motd.indexOf(" ")));
2305 } catch (NumberFormatException nfe) {
2306 // Thrown by non- CC-## format.
2307 }
2308
2309 if (motd.contains("EU-")) {
2310 lserver_num += 1000;
2311 }
2312 if (MOTD.contains("BR-")) {
2313 lserver_num += 2000;
2314 }
2315
2316 final int server_num = lserver_num;
2317
2318 Connection con = null;
2319 PreparedStatement pst = null;
2320
2321 try {
2322
2323 pst = ConnectionPool.getConnection().prepareStatement(
2324 "INSERT INTO player_database (p_name, server_num)" + " VALUES" + "('" + p_name + "', '" + server_num
2325 + "') ON DUPLICATE KEY UPDATE server_num = '" + server_num + "'");
2326
2327 pst.executeUpdate();
2328
2329 PlayerManager.getPlayerModel(p_name).setServerNum(server_num);
2330
2331 List<Object> qdata = new ArrayList<Object>();
2332 qdata.add("@server_num@" + p_name + ":" + server_num);
2333 qdata.add(null);
2334 qdata.add(true);
2335 CommunityMechanics.social_query_list.put(p_name, qdata);
2336 // CommunityMechanics.sendPacketCrossServer("@server_num@" + p_name + ":" + server_num, server_num, true);
2337
2338 } catch (SQLException ex) {
2339 log.log(Level.SEVERE, ex.getMessage(), ex);
2340 setPlayerServer(p_name);
2341
2342 } finally {
2343 try {
2344 if (pst != null) {
2345 pst.close();
2346 }
2347 if (con != null) {
2348 con.close();
2349 }
2350
2351 } catch (SQLException ex) {
2352 log.log(Level.WARNING, ex.getMessage(), ex);
2353 }
2354 }
2355
2356 }
2357
2358 public void deletePlayerServer(final String p_name) {
2359 Thread t = new Thread(new Runnable() {
2360 public void run() {
2361
2362 Connection con = null;
2363 PreparedStatement pst = null;
2364
2365 try {
2366
2367 pst = ConnectionPool.getConnection().prepareStatement("DELETE FROM p_login_data WHERE pname = '" + p_name + "'");
2368 pst.executeUpdate();
2369
2370 } catch (SQLException ex) {
2371 log.log(Level.SEVERE, ex.getMessage(), ex);
2372 setPlayerServer(p_name);
2373
2374 } finally {
2375 try {
2376 if (pst != null) {
2377 pst.close();
2378 }
2379 if (con != null) {
2380 con.close();
2381 }
2382
2383 } catch (SQLException ex) {
2384 log.log(Level.WARNING, ex.getMessage(), ex);
2385 }
2386 }
2387 }
2388 });
2389
2390 t.start();
2391 }
2392
2393 public static void setPlayerOffline(final String p_name, int second_delay, boolean ignore_all_checks) {
2394 final int login_delay_s = second_delay * 1000;
2395
2396 try {
2397 if (second_delay > 0) {
2398 Thread.sleep(login_delay_s);
2399 }
2400
2401 Connection con = null;
2402 PreparedStatement pst = null;
2403
2404 try {
2405 pst = ConnectionPool.getConnection().prepareStatement(
2406 "INSERT INTO player_database (p_name, server_num)" + " VALUES" + "('" + p_name + "', '" + (-1)
2407 + "') ON DUPLICATE KEY UPDATE server_num = '" + (-1) + "'");
2408
2409 pst.executeUpdate();
2410
2411 being_uploaded.remove(p_name);
2412
2413 } catch (SQLException ex) {
2414 log.log(Level.SEVERE, ex.getMessage(), ex);
2415
2416 } finally {
2417 try {
2418 if (pst != null) {
2419 pst.close();
2420 }
2421 if (con != null) {
2422 con.close();
2423 }
2424
2425 } catch (SQLException ex) {
2426 log.log(Level.WARNING, ex.getMessage(), ex);
2427 }
2428 }
2429 } catch (Exception e) {
2430 e.printStackTrace();
2431 }
2432
2433 }
2434
2435 public static void setPlayerOffline(final String p_name, int second_delay) {
2436 final int login_delay_s = second_delay * 1000;
2437
2438 try {
2439 if (second_delay > 0) {
2440 Thread.sleep(login_delay_s);
2441 }
2442
2443 if (lockout_players.contains(p_name)) {
2444 log.info("[HIVE (SLAVE EDITION] Player " + p_name
2445 + " has been detected in the lockout_players table, and will not be set as offline this server.");
2446 return; // Don't set them as offline to prevent a desync.
2447 }
2448
2449 if (!(player_to_npc.containsKey(p_name)) && Bukkit.getPlayer(p_name) != null && Bukkit.getPlayer(p_name).isOnline() && shutting_down == false) {
2450 return; // They're back online locally! WOO!
2451 }
2452
2453 if (player_to_npc.containsKey(p_name)) {
2454 // Let that event finish and handle when they're 'offline'.
2455 return;
2456 }
2457
2458 Connection con = null;
2459 PreparedStatement pst = null;
2460
2461 try {
2462 pst = ConnectionPool.getConnection().prepareStatement(
2463 "INSERT INTO player_database (p_name, server_num)" + " VALUES" + "('" + p_name + "', '" + (-1)
2464 + "') ON DUPLICATE KEY UPDATE server_num = '" + (-1) + "'");
2465
2466 pst.executeUpdate();
2467
2468 // pending_upload.remove(p_name);
2469 being_uploaded.remove(p_name);
2470
2471 } catch (SQLException ex) {
2472 log.log(Level.SEVERE, ex.getMessage(), ex);
2473
2474 } finally {
2475 try {
2476 if (pst != null) {
2477 pst.close();
2478 }
2479 if (con != null) {
2480 con.close();
2481 }
2482
2483 } catch (SQLException ex) {
2484 log.log(Level.WARNING, ex.getMessage(), ex);
2485 }
2486 }
2487 } catch (Exception e) {
2488 e.printStackTrace();
2489 }
2490
2491 List<Object> qdata = new ArrayList<Object>();
2492 qdata.add("@server_num@" + p_name + ":" + -1);
2493 qdata.add(null);
2494 qdata.add(true);
2495 CommunityMechanics.social_query_list.put(p_name, qdata);
2496 // CommunityMechanics.sendPacketCrossServer("@server_num@" + p_name + ":" + -1, -1, true);
2497 PlayerManager.getPlayerModel(p_name).setServerNum(-1);
2498
2499 }
2500
2501 public static int getServerNumFromPrefix(String prefix) {
2502 int server_num = -1;
2503 if (prefix.contains(" ")) {
2504 prefix = prefix.substring(0, prefix.indexOf(" "));
2505 }
2506
2507 try {
2508 if (prefix.contains("-")) {
2509 server_num = Integer.parseInt(prefix.substring(prefix.indexOf("-") + 1, prefix.length()));
2510 }
2511 if (prefix.contains("US")) {
2512 } else if (prefix.contains("EU")) {
2513 server_num += 1000;
2514 } else if (prefix.contains("BR")) {
2515 server_num += 2000;
2516 }
2517 } catch (Exception err) {
2518 err.printStackTrace();
2519 return 0;
2520 }
2521
2522 return server_num;
2523 }
2524
2525 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
2526 public void onCommandPreProcess(PlayerCommandPreprocessEvent e) {
2527 if (e.getMessage().equalsIgnoreCase("/stop")
2528 && e.getPlayer() != null
2529 && (e.getPlayer().getName().equalsIgnoreCase("availer") || e.getPlayer().getName().equalsIgnoreCase("vaquxine"))) {
2530 server_lock = true;
2531 force_kick = true;
2532 setAllPlayersAsOffline();
2533 for (Player p : Bukkit.getServer().getOnlinePlayers()) {
2534 if (!(Hive.server_frozen)) {
2535 p.saveData();
2536 }
2537 p.kickPlayer("\n" + ChatColor.GREEN.toString() + "This " + ChatColor.BOLD.toString() + "Dungeon Realms" + ChatColor.GREEN.toString()
2538 + " shard is rebooting." + "\n\n" + ChatColor.GRAY.toString() + ChatColor.UNDERLINE.toString() + "www.s4scraft.net");
2539 }
2540 e.setCancelled(true);
2541
2542 Thread t = new Thread(new Runnable() {
2543 public void run() {
2544 int count = 0;
2545 while (pending_upload.size() > 0 && count <= 200) {
2546 count++;
2547 try {
2548 Thread.sleep(100); // Let all pending multi-thread uploads finish.
2549 } catch (InterruptedException e) {
2550 e.printStackTrace();
2551 }
2552 }
2553 ready_to_die = true;
2554 force_stop = true;
2555 }
2556 });
2557
2558 t.start();
2559 }
2560 }
2561
2562 // TODO: SEE IF THIS IS EVEN NEEDED
2563 /*
2564 * @EventHandler(priority = EventPriority.LOWEST) public void onPlayerRespawn(PlayerRespawnEvent e) { final Player pl = e.getPlayer(); final Location loc =
2565 * pl.getLocation(); if(HealthMechanics.getPlayerHP(pl.getName()) > 0 || pl.getHealth() > 0) { // Invalid death, so let's not drop ANYTHING, and just spawn
2566 * them back. Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() { public void run() { pl.teleport(loc); // Set location back to
2567 * where they are. Main.plugin.getServer().getConsoleSender().sendMessage(ChatColor.RED + "Player had an invalid death! Location: " + loc); } }, 5L);
2568 *
2569 * pl.setHealth(20); pl.setLevel(HealthMechanics.getMaxHealthValue(pl.getName())); } }
2570 */
2571
2572 @EventHandler(priority = EventPriority.LOWEST)
2573 public void onPlayerDeath(PlayerDeathEvent e) {
2574 Player pl = e.getEntity();
2575 if (server_swap.containsKey(pl.getName())) {
2576 e.getDrops().clear();
2577 }
2578 }
2579
2580 @EventHandler
2581 public void onServerCommandEvent(ServerCommandEvent e) {
2582 if (e.getCommand().equalsIgnoreCase("stop") && !(e.getSender() instanceof Player)) {
2583 shutting_down = true;
2584 server_lock = true;
2585 force_kick = true;
2586 if (Bukkit.getMotd().contains("US-0")) {
2587 try {
2588 for (Entity ent : Bukkit.getWorld(main_world_name).getEntities()) {
2589 if (ent.getType() == EntityType.DROPPED_ITEM) {
2590 ent.remove();
2591 log.info("[HIVE] Removing dropped item: " + ent.toString());
2592 }
2593 }
2594
2595 Bukkit.getWorld("DungeonRealms").save();
2596 } catch (Exception err) {
2597 err.printStackTrace();
2598 }
2599
2600 }
2601 setAllPlayersAsOffline();
2602 for (Player p : Bukkit.getServer().getOnlinePlayers()) {
2603 if (!(Hive.server_frozen)) {
2604 p.saveData();
2605 }
2606 p.kickPlayer("\n" + ChatColor.GREEN.toString() + "This " + ChatColor.BOLD.toString() + "Dungeon Realms" + ChatColor.GREEN.toString()
2607 + " shard is rebooting." + "\n\n" + ChatColor.GRAY.toString() + ChatColor.UNDERLINE.toString() + "www.s4scraft.net");
2608 }
2609
2610 e.setCommand(""); // Nullify stop.
2611
2612 Thread t = new Thread(new Runnable() {
2613 public void run() {
2614 int count = 0;
2615 while (pending_upload.size() > 0 && count <= 200) {
2616 count++;
2617 try {
2618 Thread.sleep(1000); // Let all pending multi-thread uploads finish.
2619 } catch (InterruptedException e) {
2620 e.printStackTrace();
2621 }
2622 }
2623 ready_to_die = true;
2624 force_stop = true;
2625 }
2626 });
2627
2628 t.start();
2629 }
2630 }
2631
2632 @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
2633 public void onPlayerAsyncChatEvent(final AsyncPlayerChatEvent e) {
2634 Bukkit.getScheduler().runTask(Main.plugin, new Runnable() {
2635
2636 public void run() {
2637 Player pl = e.getPlayer();
2638 if (player_bio.containsKey(pl.getName())) {
2639 // They're writing their guild bio!
2640 e.setCancelled(true);
2641
2642 // Add on to the bio.
2643 String bio = player_bio.get(pl.getName());
2644
2645 String msg = ChatMechanics.censorMessage(e.getMessage());
2646 if (msg.equalsIgnoreCase("cancel")) {
2647 pl.sendMessage(ChatColor.RED + "/bio - " + ChatColor.BOLD + "CANCELLED");
2648 player_bio.remove(pl.getName());
2649 return;
2650 }
2651 if (msg.equalsIgnoreCase("confirm")) {
2652 bio = StringEscapeUtils.escapeSql(bio);
2653 Hive.sql_query.add("INSERT INTO player_database (p_name, biography) VALUES('" + pl.getName() + "', '" + bio
2654 + "') ON DUPLICATE KEY UPDATE biography='" + bio + "'");
2655 pl.sendMessage(ChatColor.GREEN.toString() + ChatColor.BOLD.toString() + "Profile Biography Submitted.");
2656 pl.sendMessage(ChatColor.GRAY + bio);
2657 player_bio.remove(pl.getName());
2658 return;
2659 }
2660
2661 if ((bio.length() + msg.length()) > 255) {
2662 // Too long.
2663 int length = (bio.length() + msg.length());
2664 int overflow = length - 255;
2665 pl.sendMessage(ChatColor.RED + "Your profile biography would be " + length + " characters long with this addition, that's "
2666 + ChatColor.UNDERLINE + overflow + " more characters than allowed.");
2667 pl.sendMessage(ChatColor.GRAY + "No additional text has been added to the biography.");
2668 return;
2669 }
2670
2671 if (bio.length() > 0) {
2672 bio += " ";
2673 }
2674 bio += msg;
2675
2676 player_bio.put(pl.getName(), bio);
2677 pl.sendMessage(ChatColor.GREEN + "Biography appended. " + ChatColor.BOLD.toString() + bio.length() + "/512 characters.");
2678 }
2679
2680 if (killing_self.contains(pl.getName())) {
2681 e.setCancelled(true);
2682 String msg = e.getMessage();
2683 if (msg.equalsIgnoreCase("y")) {
2684 KarmaMechanics.plast_hit.remove(pl.getName());
2685 KarmaMechanics.last_hit_time.remove(pl.getName());
2686
2687 pl.setLastDamageCause(new EntityDamageEvent(pl, DamageCause.SUICIDE, 0)); // Sets death message to suicide.
2688 // pl.setLevel(0);
2689 HealthMechanics.setPlayerHP(pl.getName(), 0);
2690 pl.setHealth(0);
2691 pl.setMetadata("hp", new FixedMetadataValue(Main.plugin, 0));
2692 killing_self.remove(pl.getName());
2693 } else {
2694 pl.sendMessage(ChatColor.YELLOW + "/suicide - " + ChatColor.BOLD + "CANCELLED");
2695 killing_self.remove(pl.getName());
2696 }
2697 }
2698
2699 }
2700 });
2701 }
2702
2703 @EventHandler(priority = EventPriority.LOW)
2704 public void onPlayerPreLogin(AsyncPlayerPreLoginEvent e) {
2705 String p_name = e.getName();
2706
2707 // This is a very special case
2708 if (p_name.startsWith("idminecraft")) {
2709 e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "Nope, Nope, Nope!");
2710 return;
2711 }
2712
2713 if (e.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED || e.getKickMessage().length() > 0) {
2714 return; // They failed a login check.
2715 }
2716
2717 /*
2718 * if(p_name.equalsIgnoreCase("Vaquxine")){ return; }
2719 */
2720 if (loaded_players.contains(p_name) && Main.plugin.getServer().getPlayer(p_name) == null) {
2721 loaded_players.remove(p_name);
2722 }
2723
2724 login_time.put(p_name, System.currentTimeMillis());
2725 OfflinePlayer of = Bukkit.getOfflinePlayer(p_name);
2726
2727 if (Bukkit.getMotd().contains("DESYNC") || local_ddos || hive_ddos) {
2728 e.setKickMessage(ChatColor.RED.toString() + "This " + ChatColor.BOLD + "Dungeon Realms" + ChatColor.RED.toString()
2729 + " server is currently desynced from the hive -- local login servers are offline." + "\n\n" + ChatColor.GRAY.toString()
2730 + ChatColor.UNDERLINE.toString() + "www.s4scraft.net");
2731 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2732 return;
2733 }
2734
2735 if (payload_pending == true) {
2736 e.setKickMessage(ChatColor.YELLOW.toString() + "This " + ChatColor.BOLD + "Dungeon Realms" + ChatColor.YELLOW.toString()
2737 + " server is currently downloading a server snapshot." + "\n" + ChatColor.GRAY + "The shard will be back online in about "
2738 + (seconds_to_reboot + 10) + ChatColor.BOLD + "s" + "\n\n" + ChatColor.GRAY.toString() + ChatColor.UNDERLINE.toString()
2739 + "www.s4scraft.net");
2740 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2741 return;
2742 }
2743
2744 if (restart_inc == true) {
2745 e.setKickMessage(ChatColor.YELLOW.toString() + "This " + ChatColor.BOLD + "Dungeon Realms" + ChatColor.YELLOW.toString()
2746 + " server is currently rebooting." + "\n" + ChatColor.GRAY + "The shard will be back online in about " + (seconds_to_reboot + 10)
2747 + ChatColor.BOLD + "s" + "\n\n" + ChatColor.GRAY.toString() + ChatColor.UNDERLINE.toString() + "www.s4scraft.net");
2748 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2749 return;
2750 }
2751
2752 if (server_lock == true || force_kick == true) {
2753 if (!(of.isOp())) {
2754 e.setKickMessage(ChatColor.RED.toString() + "This server is currently " + ChatColor.BOLD.toString() + "LOCKED" + ChatColor.RED.toString()
2755 + ", only Dungeon Realms developers are authorized to login.");
2756 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2757 return;
2758 } else {
2759 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.ALLOWED);
2760 }
2761 }
2762 if (!canTheyLogin(e.getName())) {
2763 int seconds_to_login = getTimeToLogin(e.getName());
2764 if (seconds_to_login == 0) {
2765 e.allow();
2766 } else {
2767 e.setKickMessage(ChatColor.RED + "You cannot login because you have recently logged out in wilderness.\n" + ChatColor.BOLD + "You must wait "
2768 + seconds_to_login + " seconds to login again.");
2769 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2770 return;
2771 }
2772 }
2773 if (Bukkit.hasWhitelist()) {
2774 if (Bukkit.getMotd().contains("DEVELOPER") && (!(Bukkit.getWhitelistedPlayers().contains(of)))) { // !of.isOp() ||
2775 e.setKickMessage(ChatColor.RED.toString() + "You are currently " + ChatColor.BOLD.toString() + "NOT" + ChatColor.RED.toString()
2776 + " authorized to login to this #DungeonRealms DEVELOPEMENT server." + "\n" + "\n" + ChatColor.GRAY.toString()
2777 + "CONTACT: staff@s4scraft.net");
2778 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST);
2779 return;
2780 }
2781 if (Bukkit.getMotd().contains("-YT") && !(Bukkit.getWhitelistedPlayers().contains(of))) {
2782 e.setKickMessage(ChatColor.RED.toString() + "You are currently " + ChatColor.BOLD.toString() + "NOT" + ChatColor.RED.toString()
2783 + " authorized to login to this #DungeonRealms YOUTUBE VIP server." + "\n" + "\n" + ChatColor.GRAY.toString()
2784 + "CONTACT: staff@s4scraft.net");
2785 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST);
2786 return;
2787 }
2788 }
2789
2790 if (loading_server == true) {
2791 if (getLoadPercent() < 30 && !Bukkit.getMotd().contains("US-99")) {
2792 e.setKickMessage(ChatColor.AQUA.toString() + "This " + ChatColor.BOLD + "Dungeon Realms" + ChatColor.AQUA.toString()
2793 + " shard is loading objects into memory for " + ChatColor.UNDERLINE + "maximum" + ChatColor.AQUA + " performance. ("
2794 + getLoadPercent() + "%)" + "\n" + ChatColor.GRAY + "You may join as soon as this process is complete." + "\n\n"
2795 + ChatColor.GRAY.toString() + ChatColor.UNDERLINE.toString() + "www.s4scraft.net");
2796 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2797 return;
2798 }
2799 }
2800
2801 if (logout_time.containsKey(p_name)) {
2802 e.setKickMessage(ChatColor.GRAY.toString() + "You recently logged out " + ChatColor.UNDERLINE.toString() + "WHILE IN COMBAT"
2803 + ChatColor.GRAY.toString() + ", so you must wait " + ChatColor.BOLD.toString() + "15" + ChatColor.GRAY.toString()
2804 + " seconds before logging in." + "\n\n" + ChatColor.RED.toString() + "To avoid this in the future, use " + ChatColor.BOLD.toString()
2805 + "/logout to safetly exit the game.");
2806 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2807 return;
2808 }
2809
2810 /*
2811 * if(being_uploaded.contains(p_name) || RealmMechanics.uploading_realms.contains(p_name)){ e.setKickMessage(ChatColor.RED.toString() +
2812 * "ERROR: Logged in too quickly after last logout." + "\n" + ChatColor.GRAY.toString() + "Please wait a few seconds and try again.");
2813 * e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); return; }
2814 */
2815
2816 if (new File(main_world_name + "/players/" + p_name + ".dat").exists()) {
2817 String motd = Bukkit.getMotd();
2818 int server_num_local = 1;
2819 try {
2820 server_num_local = Integer.parseInt(motd.substring(motd.indexOf("-") + 1, motd.indexOf(" ")));
2821 } catch (NumberFormatException nfe) {
2822 server_num_local += 3000;
2823 }
2824 String server_name = motd.substring(0, motd.indexOf("-") + 1);
2825
2826 if (server_num_local > 3000) {
2827 server_name = "US-YT";
2828 server_num_local = 0;
2829 }
2830
2831 e.setKickMessage(ChatColor.YELLOW.toString() + "The account " + ChatColor.BOLD.toString() + p_name + ChatColor.YELLOW.toString()
2832 + " is already loaded on " + ChatColor.UNDERLINE.toString() + server_name + server_num_local + "." + "\n\n" + ChatColor.GRAY.toString()
2833 + "If you have just recently changed servers, your character data is being synced -- " + ChatColor.UNDERLINE.toString()
2834 + "wait a few seconds" + ChatColor.GRAY.toString() + " before reconnecting.");
2835 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2836 return;
2837 }
2838
2839 boolean VIP = false;
2840 String rank = getServerRank(p_name);
2841
2842 if (!rank.equalsIgnoreCase("default")) {
2843 VIP = true;
2844 }
2845
2846 /*
2847 * if(group == 75 || group == 76 || group == 79 || group == 6 || group == 7 || group == 5 || group == 10 || group == 11 || group == 72){ VIP = true; //
2848 * Let them in no matter the slots! }
2849 */
2850
2851 int server_num = Integer.parseInt(Bukkit.getMotd().substring(Bukkit.getMotd().indexOf("-") + 1, Bukkit.getMotd().indexOf(" ")));
2852 if (server_num == 9 || server_num == 10) {
2853 // VIP server
2854 boolean op = false;
2855 for (OfflinePlayer pl : Bukkit.getOperators()) {
2856 if (pl.getName().equalsIgnoreCase(p_name)) {
2857 op = true;
2858 break;
2859 }
2860 }
2861 if (!(VIP) && !PermissionMechanics.isGM(p_name) && !op) {
2862 e.setKickMessage(ChatColor.RED + "You are " + ChatColor.UNDERLINE + "not" + ChatColor.RED
2863 + " authorized to connect to subscriber only servers." + "\n\n" + ChatColor.GRAY
2864 + "Subscribe at http://s4scraft.net/shop to gain instant access!");
2865 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2866 }
2867 }
2868
2869 // No longer req. forum account! Woohoo!
2870 /*
2871 * if(group == -1){ e.setKickMessage(ChatColor.RED.toString() + "You " + ChatColor.UNDERLINE.toString() + "MUST" + ChatColor.RED.toString() +
2872 * " have an active forum account to login to Dungeon Realms." + "\n" + "\n" + ChatColor.GRAY.toString() + ChatColor.BOLD.toString() + "REGISTER:" +
2873 * ChatColor.UNDERLINE.toString() + " http://s4scraft.net/forum/register.php"); e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST);
2874 * return; }
2875 */
2876
2877 int players_online = Main.plugin.getServer().getOnlinePlayers().length;
2878 if (players_online >= Bukkit.getMaxPlayers()) {
2879 if (VIP == false) {
2880 e.setKickMessage(ChatColor.RED.toString() + "This Dungeon Realms server is currently FULL." + "\n" + ChatColor.GRAY.toString()
2881 + "You can subscribe at http://s4scraft.net/buy/ to get instant access.");
2882 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2883 return;
2884 } else if (VIP == true) {
2885 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.ALLOWED);
2886 }
2887 }
2888
2889 remote_player_data.remove(p_name);
2890 RealmMechanics.player_god_mode.remove(p_name); // Remove any remnant god mode data.
2891
2892 local_player_ip.put(p_name, e.getAddress().getHostAddress());
2893
2894 int server_num_on = -1;
2895 Object result = downloadPlayerDatabaseData(p_name);
2896 if (result instanceof Exception) {
2897 // Something went wrong, an exception was thrown.
2898 no_upload.add(p_name);
2899 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD player data from database." + "\n" + ChatColor.GRAY.toString()
2900 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 015");
2901 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2902 return;
2903 }
2904 if (result instanceof Integer) {
2905 // The result is the server_num they're on.
2906 server_num_on = (Integer) result;
2907 }
2908 if (result instanceof Boolean) {
2909 Boolean bresult = (Boolean) result;
2910 if (bresult == false) {
2911 server_num_on = -2;
2912 }
2913 }
2914
2915 if (server_num_on >= 0) {
2916 // They're online a server.
2917 // int oserver_num_on = server_num_on;
2918
2919 // String motd = Bukkit.getMotd();
2920 String prefix = "US-";
2921
2922 if (server_num_on > 1000 && server_num_on < 2000) {
2923 // EU server. 1001, 1002, etc.
2924 server_num_on -= 1000;
2925 prefix = "EU-";
2926 }
2927
2928 if (server_num_on > 2000 && server_num_on < 3000) {
2929 server_num_on -= 2000;
2930 prefix = "BR-";
2931 }
2932
2933 if (server_num_on > 3000) {
2934 // EU server. 1001, 1002, etc.
2935 server_num_on -= 3000;
2936 prefix = "US-YT";
2937 }
2938
2939 e.setKickMessage(ChatColor.YELLOW.toString() + "The account " + ChatColor.BOLD.toString() + p_name + ChatColor.YELLOW.toString()
2940 + " is already logged in on " + ChatColor.UNDERLINE.toString() + prefix + server_num_on + "." + "\n\n" + ChatColor.GRAY.toString()
2941 + "If you have just recently changed servers, your character data is being synced -- " + ChatColor.UNDERLINE.toString()
2942 + "wait a few seconds" + ChatColor.GRAY.toString() + " before reconnecting.");
2943 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2944 return;
2945 }
2946
2947 if (server_num_on == -2) {
2948 // This just means that they have no data in player_database, not that they've never logged in.
2949 // Let's check to make sure they don't have any player_data.
2950 if (!hasAccountData(p_name)) {
2951 first_login.add(p_name);
2952 setFirstLoginSQL(p_name);
2953 player_first_login.put(p_name, System.currentTimeMillis());
2954
2955 // Setup all variables that downloadPlayerDatabaseData didn't get cause it returned -2.
2956 HealthMechanics.noob_players.add(p_name);
2957 KarmaMechanics.align_map.put(p_name, "good");
2958 HealthMechanics.health_data.put(p_name, 50);
2959 PermissionMechanics.rank_map.put(p_name, "default");
2960 RealmMechanics.realm_tier.put(p_name, 1); // was 0
2961 PetMechanics.pet_map.put(p_name, new ArrayList<Entity>());
2962 PetMechanics.player_pets.put(p_name, PetMechanics.downloadPetData(p_name));
2963 } else {
2964 // A value of -2 means that the function returned false on downloadPlayerDatabase(), so there could be some issues going on here if account data
2965 // EXISTS and it returned -2.
2966 no_upload.add(p_name);
2967 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD player data from database." + "\n" + ChatColor.GRAY.toString()
2968 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 019");
2969 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2970 return;
2971 }
2972 }
2973
2974 if (PlayerManager.getPlayerModel(p_name).getLastLocalLogin() > 0)
2975 PlayerManager.getPlayerModel(p_name).setLastLocalLogin(0);
2976
2977 try {
2978 setPlayerServer(p_name);
2979
2980 if (MoneyMechanics.downloadBankDatabaseData(p_name) == false) {
2981 // Either new player or failed to download. Let's see.
2982 if (server_num_on != -2) {
2983 // Not a new player!
2984 no_upload.add(p_name);
2985 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD bank data from database." + "\n" + ChatColor.GRAY.toString()
2986 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 013D");
2987 log.info("Problematic server: " + server_num_on);
2988 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
2989 setPlayerOffline(p_name, 1);
2990 return;
2991 } else {
2992 MoneyMechanics.bank_map.put(p_name, 0);
2993 MoneyMechanics.bank_level.put(p_name, 0);
2994 MoneyMechanics.bank_contents.put(p_name, new ArrayList<Inventory>(Arrays.asList(Bukkit.createInventory(null, 9, "Bank Chest"))));
2995 }
2996 }
2997
2998 if (ShopMechanics.downloadShopDatabaseData(p_name) == false) {
2999 // Either new player or failed to download. Let's see.
3000 if (server_num_on != -2) {
3001 // Not a new player!
3002 no_upload.add(p_name);
3003 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD shop data from database." + "\n" + ChatColor.GRAY.toString()
3004 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 014");
3005 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
3006 setPlayerOffline(p_name, 1);
3007 return;
3008 } else {
3009 ShopMechanics.shop_level.put(p_name, 0);
3010 }
3011 }
3012
3013 GuildMechanics.setupGuildData(p_name, GuildMechanics.getPlayerGuildSQL(p_name));
3014
3015 /*
3016 * if(VIP && PermissionMechanics.getRank(p_name).equalsIgnoreCase("default")){ // Set permissions. if(group == 75){
3017 * PermissionMechanics.setRank(p_name, "sub", true); } if(group == 76){ PermissionMechanics.setRank(p_name, "sub+", true); } if(group == 79){
3018 * PermissionMechanics.setRank(p_name, "sub++", true); } } else if(!VIP && (PermissionMechanics.getRank(p_name).equalsIgnoreCase("sub") ||
3019 * PermissionMechanics.getRank(p_name).equalsIgnoreCase("sub+") || PermissionMechanics.getRank(p_name).equalsIgnoreCase("sub++"))){ // Take away
3020 * subscriber rank. PermissionMechanics.setRank(p_name, "default", true); }
3021 */
3022
3023 if (!(player_ecash.containsKey(p_name))) {
3024 // They have none, set to 0.
3025 player_ecash.put(p_name, 0);
3026 }
3027
3028 log.info(Ansi.ansi().fg(Ansi.Color.YELLOW).boldOff().toString() + "[HIVE (SLAVE Edition)] Player data for " + p_name + " downloaded."
3029 + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
3030
3031 } catch (Exception err) {
3032 err.printStackTrace();
3033 no_upload.add(p_name);
3034 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD player data from database." + "\n" + ChatColor.GRAY.toString()
3035 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 003");
3036 e.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
3037 new File(main_world_name + "/players/" + p_name + ".dat").delete();
3038 setPlayerOffline(p_name, 2);
3039 return;
3040
3041 }
3042 }
3043
3044 public static String getRandomString(int length) {
3045 char[] chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
3046 StringBuilder sb = new StringBuilder();
3047 Random random = new Random();
3048 for (int i = 0; i < length; i++) {
3049 char c = chars[random.nextInt(chars.length)];
3050 sb.append(c);
3051 }
3052 return sb.toString();
3053 }
3054
3055 public static String generateProfileCode(String player) {
3056 String code = Hive.getRandomString(10);
3057 sql_query.add("UPDATE player_database SET playercode='" + code + "' WHERE p_name='" + player + "' LIMIT 1");
3058 return code;
3059 }
3060
3061 public boolean canTheyLogin(String name) {
3062 try (PreparedStatement pst = ConnectionPool.getConnection().prepareStatement("SELECT login_delay FROM player_database WHERE p_name = ?")) {
3063 pst.setString(1, name);
3064 ResultSet rst = pst.executeQuery();
3065 if (!rst.first()) {
3066 try (PreparedStatement prest = ConnectionPool.getConnection().prepareStatement(
3067 "INSERT IGNORE INTO player_database (p_name, login_delay) VALUES (?, 0) ON DUPLICATE KEY UPDATE login_delay = 0;")) {
3068 prest.setString(1, name);
3069 prest.executeUpdate();
3070 prest.close();
3071 return true;
3072 } catch (Exception e) {
3073 e.printStackTrace();
3074 }
3075 } else {
3076 return rst.getLong("login_delay") <= System.currentTimeMillis();
3077 }
3078 } catch (Exception e) {
3079 e.printStackTrace();
3080 }
3081 return true;
3082 }
3083
3084 public static int getTimeToLogin(String p_name) {
3085 try (PreparedStatement pst = ConnectionPool.getConnection()
3086 .prepareStatement("SELECT login_delay FROM player_database WHERE p_name = '" + p_name + "';")) {
3087 ResultSet rst = pst.executeQuery();
3088 if (!rst.first()) {
3089 return 0;
3090 } else {
3091 long delay = rst.getLong("login_delay");
3092 int in_seconds = (int) ((delay - System.currentTimeMillis()) / 1000);
3093 return in_seconds;
3094 }
3095 } catch (SQLException e) {
3096 e.printStackTrace();
3097 return 0;
3098 }
3099 }
3100
3101 @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
3102 public void onPlayerTeleport(PlayerTeleportEvent e) {
3103 // final Player pl = e.getPlayer();
3104 if (e.getTo().getWorld() == null)
3105 return;
3106 if (e.getTo().getWorld().getName().equalsIgnoreCase(main_world_name)
3107 && !(e.getFrom().getWorld().getName().equalsIgnoreCase(e.getTo().getWorld().getName()))) {
3108 // Set dimension.
3109 /*
3110 * this.getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable() { public void run() { InstanceMechanics.setPlayerEnvironment(pl,
3111 * Environment.NETHER); } }, 2L);
3112 */
3113 }
3114 }
3115
3116 @EventHandler(priority = EventPriority.HIGH)
3117 public void onPlayerLogin(PlayerLoginEvent e) throws IOException {
3118 final Player p = e.getPlayer();
3119 final String p_name = p.getName();
3120
3121 if (remote_player_data.containsKey(p_name)) {
3122 /*
3123 * data.set(0, loc); data.set(1, inventory_s); data.set(2, level); data.set(3, hp); data.set(4, food_level);
3124 */
3125
3126 List<Object> data = remote_player_data.get(p_name);
3127 final Location loc = (Location) data.get(0);
3128 p.getInventory().clear();
3129 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3130 public void run() {
3131 p.teleport(loc.add(0, 1, 0));
3132 // Run TP after a second.
3133 }
3134 }, 10L);
3135
3136 String inventory_s = (String) data.get(1);
3137 convertStringToInventory(p, inventory_s, null, 0);
3138
3139 final int level = (Integer) data.get(2);
3140 Double hp = (Double) data.get(3);
3141 int food_level = (Integer) data.get(4);
3142
3143 // p.setLevel(level);
3144
3145 p.setFoodLevel(food_level);
3146 p.setExp(1.0F);
3147
3148 if (hp < 0) {
3149 hp = 0.0D;
3150 }
3151
3152 final double f_hp = hp;
3153
3154 player_inventory.put(p_name, p.getInventory());
3155 player_location.put(p_name, loc);
3156 player_hp.put(p_name, hp);
3157 player_level.put(p_name, level);
3158 player_food_level.put(p_name, food_level);
3159
3160 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3161 public void run() {
3162 p.setHealth((int) f_hp);
3163 if (f_hp > 0) {
3164 HealthMechanics.setPlayerHP(p.getName(), level);
3165 }
3166 }
3167 }, 1L);
3168
3169 /*
3170 * this.getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable() { public void run() { InstanceMechanics.setPlayerEnvironment(p,
3171 * Environment.NETHER); } }, 2L);
3172 */
3173
3174 // Depreciated.
3175 // This hack fixes issues with the game thinking it's their first login ever.
3176 /*
3177 * p.saveData(); p.loadData();
3178 */
3179 // ^
3180 } else if (!(first_login.contains(p.getName()))) {
3181 e.setResult(Result.KICK_OTHER);
3182 e.setKickMessage(ChatColor.RED.toString() + "Failed to LOAD player data from database." + "\n" + ChatColor.GRAY.toString()
3183 + "Please try again later. " + "\n\n" + ChatColor.BOLD.toString() + "ERROR CODE: 065");
3184 return;
3185 }
3186
3187 for (Player p_online : Bukkit.getOnlinePlayers()) {
3188 p_online.showPlayer(p);
3189 }
3190
3191 log.info(Ansi.ansi().fg(Ansi.Color.YELLOW).boldOff().toString() + "[HIVE (SLAVE Edition)] Player data for " + p.getName() + " LOADED."
3192 + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
3193
3194 if (first_login.contains(p.getName())) {
3195 log.info("[HIVE (SLAVE Edition)] " + p.getName() + " has logged in for the first time. No data downloaded.");
3196 // p.setLevel(50);
3197 HealthMechanics.setPlayerHP(p.getName(), 50);
3198 p.teleport(TutorialMechanics.tutorialSpawn);
3199
3200 /*
3201 * Integer groupID = forum_usergroup.get(p_name);
3202 *
3203 * if(groupID == 9){ // Premium user. PetMechanics.addPetToPlayer(p.getName(), "baby_zombie"); }
3204 */
3205
3206 return;
3207 }
3208 }
3209
3210 @EventHandler(priority = EventPriority.LOWEST)
3211 public void onPlayerLoginLoaded(PlayerJoinEvent e) {
3212 final Player p = e.getPlayer();
3213 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3214 public void run() {
3215 if (!(loaded_players.contains(p.getName()))) {
3216 loaded_players.add(p.getName());
3217 }
3218 }
3219 }, 10L);
3220 }
3221
3222 public void removeGemIcons(Player pl) {
3223 int index = -1;
3224 for (ItemStack is : pl.getInventory()) {
3225 index++;
3226 if (is == null) {
3227 continue;
3228 }
3229 if (is.getType() == Material.EMERALD && is.hasItemMeta() && is.getItemMeta().hasDisplayName()) {
3230 String name = is.getItemMeta().getDisplayName();
3231 if (name.toLowerCase().contains("gem(s)")) {
3232 pl.getInventory().setItem(index, new ItemStack(Material.AIR));
3233 log.info("(FLAG) Player " + pl.getName() + " has illegal time (bank statis cash) in inventory.");
3234 }
3235 }
3236 }
3237 }
3238
3239 @EventHandler(priority = EventPriority.LOW, ignoreCancelled = false)
3240 public void onPlayerFirstJoin(PlayerJoinEvent e) {
3241 final Player p = e.getPlayer();
3242 final String p_name = p.getName();
3243 e.setJoinMessage("");
3244 removeGemIcons(p);
3245 if (first_login.contains(p.getName())) {
3246 // p.teleport(TutorialMechanics.tutorialSpawn, TeleportCause.PLUGIN);
3247 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3248 public void run() {
3249 p.teleport(TutorialMechanics.tutorialSpawn, TeleportCause.PLUGIN);
3250 }
3251 }, 10L);
3252 return;
3253 } else if (remote_player_data.containsKey(p.getName())) {
3254 // p.teleport(((Location)remote_player_data.get(p.getName()).get(0)).add(0, 1, 0), TeleportCause.PLUGIN);
3255 }
3256
3257 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3258 public void run() {
3259 Player p = Bukkit.getPlayer(p_name);
3260 if (p != null) {
3261 Location l = p.getLocation();
3262
3263 if (l.distanceSquared((new Location(Bukkit.getWorlds().get(0), -981, 163, -292))) <= 100) { // 50 blocks from the bugged mountain spawn.
3264 // They're in debug plains somehow. This isn't good!
3265 if (HealthMechanics.getPlayerHP(p.getName()) < 50) {
3266 p.teleport(TutorialMechanics.tutorialSpawn, TeleportCause.PLUGIN);
3267 } else {
3268 p.teleport(SpawnMechanics.getRandomSpawnPoint(p.getName()), TeleportCause.PLUGIN);
3269 }
3270 }
3271
3272 l.setY(0);
3273 if (l.distanceSquared((new Location(Bukkit.getWorlds().get(0), 0, 0, 0))) <= 2500) { // 50 blocks from the bugged mountain spawn.
3274 // They're in debug plains somehow. This isn't good!
3275 p.teleport(SpawnMechanics.getRandomSpawnPoint(p.getName()), TeleportCause.PLUGIN);
3276 }
3277 }
3278 }
3279 }, 20L);
3280
3281 // Depreciated, is this even possible with the new shard system?
3282 Thread t = new Thread(new Runnable() {
3283 public void run() {
3284 try {
3285 Thread.sleep(5000);
3286 } catch (InterruptedException e) {
3287 e.printStackTrace();
3288 }
3289
3290 if (Bukkit.getPlayer(p.getName()) == null) {
3291 return; // No need to ban, they're offline!
3292 }
3293
3294 int server_num_reported = getPlayerServer(p.getName(), true);
3295 String motd = Bukkit.getMotd();
3296 int server_num_local = 1;
3297
3298 if (motd.contains("US-YT")) {
3299 server_num_local = server_num_local + 3000;
3300 }
3301 try {
3302 server_num_local = Integer.parseInt(motd.substring(motd.indexOf("-") + 1, motd.indexOf(" ")));
3303 } catch (NumberFormatException nfe) {
3304 // Thrown on non- CC-## format.
3305 }
3306 if (motd.contains("EU-")) {
3307 // It's a european server, so add 1000. 1 = 1001.
3308 server_num_local = server_num_local + 1000;
3309 }
3310 if (motd.contains("BR-")) {
3311 // It's a brazillian server, so add 2000. 1 = 2001.
3312 server_num_local = server_num_local + 2000;
3313 }
3314
3315 if (server_num_reported != -1 && server_num_reported != server_num_local) {
3316 // They're on two servers at once. Ban for 72 hours.
3317 long unban_date = -1L; // (System.currentTimeMillis() + (1000 * (72 * 3600)));
3318 String reason = "[AUTO] Dupe Exploit";
3319 ModerationMechanics.BanPlayer(p.getName(), unban_date, reason, "Console", false);
3320 if (Bukkit.getPlayer(p_name) != null) {
3321 Player banned = Bukkit.getPlayer(p_name);
3322 if (reason == "") {
3323 to_kick.put(banned.getName(), ChatColor.RED.toString() + "Your account has been " + ChatColor.UNDERLINE + "TEMPORARILY"
3324 + ChatColor.RED + " locked due to suspisious activity." + "\n" + ChatColor.GRAY.toString()
3325 + "For further information about this suspension, please visit " + ChatColor.UNDERLINE.toString()
3326 + "http://www.s4scraft.net/bans");
3327 } else if (reason.length() > 0) {
3328 to_kick.put(banned.getName(), ChatColor.RED.toString() + "Your account has been " + ChatColor.UNDERLINE + "TEMPORARILY"
3329 + ChatColor.RED + " locked due to " + reason + "\n" + ChatColor.GRAY.toString()
3330 + "For further information about this suspension, please visit " + ChatColor.UNDERLINE.toString()
3331 + "http://www.s4scraft.net/bans");
3332 }
3333 }
3334
3335 CommunityMechanics.sendPacketCrossServer("@ban@" + p_name, server_num_reported, false);
3336 log.info("[HIVE (SLAVE Edition)] Detected a player trying to dupe by multiple logging. Banned: " + p.getName());
3337 }
3338 }
3339
3340 });
3341
3342 t.start();
3343
3344 if (!(TutorialMechanics.onTutorialIsland(p))) {
3345 p.sendMessage("");
3346 p.sendMessage("");
3347 p.sendMessage("");
3348 p.sendMessage("");
3349 p.sendMessage("");
3350 p.sendMessage("");
3351 p.sendMessage("");
3352 p.sendMessage("");
3353 p.sendMessage("");
3354 p.sendMessage("");
3355 p.sendMessage("");
3356 p.sendMessage("");
3357 p.sendMessage("");
3358 p.sendMessage("");
3359 p.sendMessage("");
3360 p.sendMessage("");
3361 p.sendMessage(ChatColor.WHITE + "" + ChatColor.BOLD + " Dungeon Realms Patch " + Config.version);
3362 // p.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + " Dungeon Realms Halloween Patch");
3363 p.sendMessage(ChatColor.GRAY + " " + "http://www.s4scraft.net/");
3364 p.sendMessage("");
3365 p.sendMessage(ChatColor.YELLOW + " " + "You are on the " + ChatColor.BOLD + MOTD.substring(0, MOTD.indexOf(" ")) + ChatColor.YELLOW
3366 + " shard.");
3367 p.sendMessage(ChatColor.GRAY.toString() + ChatColor.ITALIC.toString() + " Use " + ChatColor.YELLOW + "/shard" + ChatColor.GRAY.toString()
3368 + ChatColor.ITALIC.toString() + " to change your server instance at any time.");
3369
3370 if (MOTD.contains("RP")) {
3371 p.sendMessage("");
3372 p.sendMessage(ChatColor.DARK_AQUA + "This is a " + ChatColor.UNDERLINE + "ROLEPLAY" + ChatColor.DARK_AQUA
3373 + " server. Local chat should always be in character, Global/Trade chat may be OOC.");
3374 p.sendMessage(ChatColor.GRAY + "Please be respectful to those who want to roleplay. You " + ChatColor.UNDERLINE + "will" + ChatColor.GRAY
3375 + " be banned for trolling / local OOC.");
3376 }
3377
3378 if (MOTD.contains("BR")) {
3379 p.sendMessage("");
3380 p.sendMessage(ChatColor.DARK_AQUA + "This is a " + ChatColor.UNDERLINE + "Brazillian" + ChatColor.DARK_AQUA + " server.");
3381 p.sendMessage(ChatColor.GRAY + "The official language of this server is " + ChatColor.UNDERLINE + "Portuguese.");
3382 }
3383
3384 if (MOTD.contains("US-100") || MOTD.contains("US-101") || MOTD.contains("US-102") || MOTD.contains("US-103") || MOTD.contains("US-104")
3385 || MOTD.contains("US-105") || MOTD.contains("US-106") || MOTD.contains("US-107") || MOTD.contains("US-108") || MOTD.contains("US-109")
3386 || MOTD.contains("US-110")) {
3387 p.sendMessage("");
3388 p.sendMessage(ChatColor.GOLD + "This is a " + ChatColor.UNDERLINE + "BETA" + ChatColor.GOLD
3389 + " server. This server uses seperate data from your live server character!");
3390 p.sendMessage(ChatColor.GRAY + "You will be testing " + ChatColor.UNDERLINE + "new" + ChatColor.GRAY + " and " + ChatColor.UNDERLINE
3391 + "unfinished" + ChatColor.GRAY + " versions of Dungeon Realms.");
3392 p.sendMessage(ChatColor.GRAY.toString() + ChatColor.ITALIC + "Beta servers are intended to be " + ChatColor.UNDERLINE + "reset"
3393 + ChatColor.GRAY + ChatColor.ITALIC + " periodically to accommodate new updates.");
3394 }
3395 }
3396
3397 p.addAttachment(Main.plugin).setPermission("citizens.npc.talk", true);
3398
3399 if (Utils.isBeta()) {
3400 String currentRank = PermissionMechanics.getRank(p_name);
3401 if (currentRank.equalsIgnoreCase("default")) {
3402 PermissionMechanics.setRank(p_name, "sub++", true);
3403 }
3404 }
3405
3406 if (player_sdays_left.containsKey(p.getName()) || PermissionMechanics.rank_map.get(p.getName()).equalsIgnoreCase("sub++")) {
3407 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3408 public void run() {
3409 if (!PermissionMechanics.rank_map.get(p.getName()).equalsIgnoreCase("sub++")) {
3410 p.sendMessage(ChatColor.GOLD + "You have " + ChatColor.UNDERLINE.toString() + player_sdays_left.get(p.getName()) + " day(s)"
3411 + ChatColor.GOLD + " left until your subscription expires.");
3412 } else {
3413 p.sendMessage(ChatColor.GOLD + "You have " + ChatColor.UNDERLINE.toString() + "UNLIMITED" + " day(s)" + ChatColor.GOLD
3414 + " left until your subscription expires.");
3415 }
3416 }
3417 }, 10L);
3418 }
3419
3420 if (p.isOp()) {
3421 RealmMechanics.player_god_mode.put(p.getName(), System.currentTimeMillis());
3422 // p.setLevel(9999);
3423 HealthMechanics.setPlayerHP(p.getName(), 9999);
3424 p.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + " GM INVINSIBILITY (infinite)");
3425 ModerationMechanics.vanish_list.add(p.getName());
3426 p.sendMessage(ChatColor.GREEN + "You are now " + ChatColor.BOLD + "invisible.");
3427 }
3428
3429 if (online_today.contains(p.getName()) && !first_login.contains(p.getName())) {
3430 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3431 public void run() {
3432 // if(forum_usergroup.containsKey(p.getName()) && forum_usergroup.get(p.getName()) != -1){
3433 int amount_to_give = new Random().nextInt(5) + 10;
3434 p.sendMessage("");
3435 p.sendMessage(ChatColor.GOLD + "You have gained " + ChatColor.BOLD + amount_to_give + "EC" + ChatColor.GOLD
3436 + " for logging into Dungeon Realms today!");
3437 p.sendMessage(ChatColor.GRAY + "Use /ecash to spend your EC, you can obtain more e-cash by logging in daily or by visiting "
3438 + ChatColor.GOLD + ChatColor.UNDERLINE + "http://s4scraft.net/shop");
3439 p.playSound(p.getLocation(), Sound.ORB_PICKUP, 1F, 0.25F);
3440
3441 if (Hive.player_ecash.containsKey(p.getName())) {
3442 int current = Hive.player_ecash.get(p.getName());
3443 current += amount_to_give;
3444 Hive.player_ecash.put(p.getName(), current);
3445 } else {
3446 Hive.player_ecash.put(p.getName(), amount_to_give);
3447 }
3448
3449 Hive.sql_query.add("INSERT INTO player_database(p_name,online_today) values('" + p.getName()
3450 + "', 1) on duplicate key update online_today=1");
3451 online_today.remove(p.getName());
3452
3453 EcashMechanics.setECASH_SQL(p_name, Hive.player_ecash.get(p.getName()));
3454 // }
3455 /*
3456 * else{ // No forum account! int amount_to_give = new Random().nextInt(5) + 10; p.sendMessage(""); p.sendMessage(ChatColor.RED + "You " +
3457 * ChatColor.UNDERLINE + "could" + ChatColor.RED + " have gained " + ChatColor.BOLD + amount_to_give + "EC" + ChatColor.RED +
3458 * " for logging into Dungeon Realms today!"); p.sendMessage(ChatColor.GRAY + "To claim this free /ecash, register at " +
3459 * ChatColor.UNDERLINE + "http://s4scraft.net/login/do/register");
3460 *
3461 * }
3462 */
3463 }
3464 }, 30L);
3465
3466 }
3467 }
3468
3469 @EventHandler(priority = EventPriority.HIGHEST)
3470 public void onPlayerKickEvent(PlayerKickEvent e) {
3471 e.setLeaveMessage("");
3472 }
3473
3474 @EventHandler
3475 public void onPlayerMove(PlayerMoveEvent e) {
3476 Player p = e.getPlayer();
3477 if (safe_logout.containsKey(p.getName())) {
3478 if (!safe_logout_location.get(p.getName()).getWorld().getName().equalsIgnoreCase(p.getLocation().getWorld().getName())
3479 || safe_logout_location.get(p.getName()).distanceSquared(p.getLocation()) > 2.0D) {
3480 safe_logout.remove(p.getName());
3481 safe_logout_location.remove(p.getName());
3482 p.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Logout - CANCELLED");
3483 }
3484 }
3485 if (server_swap_location.containsKey(p.getName())) {
3486 e.setCancelled(true);
3487 p.teleport(server_swap_location.get(p.getName()));
3488 }
3489 }
3490
3491 @EventHandler(priority = EventPriority.LOW, ignoreCancelled = false)
3492 public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
3493 if (e.getEntity() instanceof Player) {
3494 Player hurt = (Player) e.getEntity();
3495 if (player_to_npc.containsKey(hurt.getName())) {
3496 /*
3497 * e.setCancelled(false); e.setDamage(1);
3498 */
3499 hurt.damage(hurt.getHealth());
3500 hurt.playEffect(EntityEffect.DEATH);
3501 }
3502 if (safe_logout.containsKey(hurt.getName())) {
3503 safe_logout.remove(hurt.getName());
3504 safe_logout_location.remove(hurt.getName());
3505 hurt.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Logout - CANCELLED");
3506 }
3507 if (server_swap.containsKey(hurt.getName())) {
3508 e.setCancelled(true);
3509 e.setDamage(0);
3510 }
3511 }
3512 if (e.getDamager() instanceof Player) {
3513 Player damager = (Player) e.getDamager();
3514 if (server_swap.containsKey(damager.getName())) {
3515 // No damage for server hoppers!
3516 e.setCancelled(true);
3517 e.setDamage(0);
3518 }
3519 }
3520 }
3521
3522 @EventHandler(priority = EventPriority.LOWEST)
3523 public void setPlayerAsQuitting(PlayerQuitEvent e) {
3524 Player p = e.getPlayer();
3525
3526 if (!(Hive.server_frozen)) {
3527 p.saveData();
3528 }
3529
3530 first_login.remove(p.getName());
3531
3532 if (!(loaded_players.contains(p.getName()))) {
3533 return;
3534 }
3535
3536 if (server_swap.containsKey(p.getName())) {
3537 return;
3538 }
3539
3540 pending_upload.add(p.getName());
3541 being_uploaded.add(p.getName());
3542 }
3543
3544 public static void setPlayerCanJoin(String p_name, boolean can_join) {
3545 Hive.sql_query.add("UPDATE player_database SET login_delay = " + (can_join ? 0 : (System.currentTimeMillis() + 300000)) + " WHERE p_name = '" + p_name
3546 + "';");
3547 }
3548
3549 @EventHandler(priority = EventPriority.HIGHEST)
3550 public void onCombatLogNPCDamage(EntityDamageByEntityEvent e) {
3551 if (!CitizensAPI.getNPCRegistry().isNPC(e.getEntity())) return;
3552 log.info("yes");
3553
3554 NPC n = CitizensAPI.getNPCRegistry().getNPC(e.getEntity());
3555 Player p = (Player) n.getEntity();
3556
3557 if (n.data().get("combat_log_npc") == null || ((boolean) n.data().get("combat_log_npc")) == false) return;
3558
3559 p.damage(0);
3560 //HealthMechanics.setPlayerHP(p.getName(), (int) (HealthMechanics.getPlayerHP(p.getName()) - e.getDamage()));
3561 e.setDamage(0);
3562 log.info("yes1");
3563
3564 e.setCancelled(true);
3565 }
3566
3567 @EventHandler(priority = EventPriority.HIGHEST)
3568 public void onPlayerQuit(PlayerQuitEvent e) throws IOException {
3569 String pname = "";
3570 e.setQuitMessage("");
3571 final Player p = e.getPlayer();
3572
3573 if (server_swap.containsKey(p.getName())) {
3574 setPlayerCanJoin(p.getName(), true);
3575 new BukkitRunnable() {
3576 @Override
3577 public void run() {
3578 Hive.server_swap.remove(p.getName());
3579 Hive.server_swap_location.remove(p.getName());
3580 File data = new File(Hive.rootDir + "/" + Hive.main_world_name + "/players/" + p.getName() + ".dat");
3581 data.delete();
3582 }
3583 }.runTaskLaterAsynchronously(Main.plugin, 20L);
3584 return;
3585 } else {
3586 if (!DuelMechanics.isDamageDisabled(p.getLocation()) && !Hive.get_payload_spoof && !p.isOp()) {
3587 setPlayerCanJoin(p.getName(), false);
3588 new BukkitRunnable() {
3589 public void run() {
3590 setPlayerCanJoin(p.getName(), true);
3591 }
3592 }.runTaskLater(Main.plugin, 20 * (60 * 5));
3593 }
3594 }
3595
3596 if (!(loaded_players.contains(p.getName()))) {
3597 log.info("[Hive] Skipping data upload for " + p.getName() + ", not in loaded_players table.");
3598 /*
3599 * Hive.player_inventory.remove(p.getName()); Hive.player_location.remove(p.getName()); Hive.player_hp.remove(p.getName());
3600 * Hive.player_level.remove(p.getName()); Hive.player_food_level.remove(p.getName()); Hive.player_armor_contents.remove(p.getName());
3601 * Hive.player_ecash.remove(p.getName()); KarmaMechanics.align_map.remove(p.getName()); KarmaMechanics.align_time.remove(p.getName());
3602 * CommunityMechanics.ignore_list.remove(p.getName()); CommunityMechanics.buddy_list.remove(p.getName());
3603 * CommunityMechanics.toggle_list.remove(p.getName()); HealthMechanics.noob_player_warning.remove(p.getName());
3604 * HealthMechanics.noob_players.remove(p.getName()); RealmMechanics.realm_title.remove(p.getName());
3605 * //RealmfdMechanics.reafdslm_tier.remove(p.getName());
3606 */
3607 return;
3608 }
3609
3610 player_inventory.put(p.getName(), p.getInventory());
3611 player_location.put(p.getName(), p.getLocation());
3612 player_hp.put(p.getName(), (double) p.getHealth());
3613 player_level.put(p.getName(), HealthMechanics.getPlayerHP(p.getName()));
3614 player_food_level.put(p.getName(), p.getFoodLevel());
3615 player_armor_contents.put(p.getName(), p.getInventory().getArmorContents());
3616 // Update local data.
3617
3618 if (!(server_swap.containsKey(p.getName())) && !(safe_logout.containsKey(p.getName())) && !(no_upload.contains(p.getName()))
3619 && HealthMechanics.getPlayerHP(p.getName()) > 0 && p.getHealth() > 0 && HealthMechanics.in_combat.containsKey(p.getName())
3620 && !(DuelMechanics.isDamageDisabled(p.getLocation())) && p.getWorld().getName().equalsIgnoreCase(main_world_name)
3621 && (server_lock == false && shutting_down == false)) { // They're in combat, let's spawn an NPC.
3622 logout_time.put(p.getName(), System.currentTimeMillis());
3623 Location loc = p.getLocation();
3624
3625 // spawn the NPC!
3626 NPC combatLogNPC = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, p.getName());
3627 combatLogNPC.addTrait(Equipment.class);
3628 combatLogNPC.getTrait(Equipment.class).set(0, p.getItemInHand());
3629 combatLogNPC.getTrait(Equipment.class).set(1, p.getInventory().getHelmet());
3630 combatLogNPC.getTrait(Equipment.class).set(2, p.getInventory().getChestplate());
3631 combatLogNPC.getTrait(Equipment.class).set(3, p.getInventory().getLeggings());
3632 combatLogNPC.getTrait(Equipment.class).set(4, p.getInventory().getBoots());
3633 combatLogNPC.getTrait(net.citizensnpcs.api.trait.trait.Inventory.class).setContents(p.getInventory().getContents());
3634 combatLogNPC.data().setPersistent("combat_log_npc", true);
3635 combatLogNPC.spawn(loc);
3636
3637 Player playerNPC = (Player) combatLogNPC.getEntity();
3638 log.info("" + HealthMechanics.getPlayerHP(p.getName()));
3639 HealthMechanics.setOverheadHP(playerNPC, HealthMechanics.getPlayerHP(p.getName()));
3640 HealthMechanics.setPlayerHP(playerNPC.getName(), HealthMechanics.getPlayerHP(p.getName()));
3641 playerNPC.setLevel(LevelMechanics.getPlayerLevel(p));
3642 playerNPC.setExp(1.0F);
3643 playerNPC.setGameMode(GameMode.SURVIVAL);
3644 playerNPC.getInventory().setContents(p.getInventory().getContents());
3645 playerNPC.getInventory().setArmorContents(p.getInventory().getArmorContents());
3646 playerNPC.setItemInHand(p.getItemInHand());
3647
3648 ScoreboardMechanics.cloneScoreboard(playerNPC);
3649
3650 // refresh packets
3651 for (Entity ent : playerNPC.getNearbyEntities(50, 50, 50)) {
3652 if (ent instanceof Player && ((Player) ent).canSee(playerNPC))
3653 Utils.refreshPlayerEquipment(playerNPC, (Player) ent);
3654 }
3655
3656 player_to_npc.put(p.getName(), combatLogNPC);
3657 player_to_npc_align.put(p.getName(), KarmaMechanics.getRawAlignment(p.getName()));
3658 player_item_in_hand.put(p.getName(), p.getItemInHand());
3659
3660 if (MountMechanics.mule_inventory.containsKey(p.getName())) {
3661 // They have a mule inventory, store it incase we need it later.
3662 boolean has_mule = false;
3663 for (ItemStack is : p.getInventory().getContents()) {
3664 if (MountMechanics.isMule(is)) {
3665 has_mule = true;
3666 }
3667 break;
3668 }
3669
3670 if (has_mule) {
3671 player_mule_inventory.put(p.getName(), MountMechanics.mule_inventory.get(p.getName()));
3672 }
3673 }
3674
3675 List<Player> lpnear = new ArrayList<Player>();
3676 for (Entity ent : p.getNearbyEntities(48, 48, 48)) {
3677 if (ent instanceof Player) {
3678 lpnear.add((Player) ent);
3679 }
3680 }
3681
3682 KarmaMechanics.sendAlignColor(playerNPC, playerNPC);
3683
3684 final List<Player> safe_lpnear = new ArrayList<Player>(lpnear);
3685 List<ItemStack> l_is = new ArrayList<ItemStack>();
3686 List<ItemStack> armor_list = new ArrayList<ItemStack>();
3687
3688 for (ItemStack is : p.getInventory().getContents()) {
3689 if (is == null || is.getType() == Material.AIR || is.getType() == Material.NETHER_STAR || CommunityMechanics.isSocialBook(is)
3690 || !RealmMechanics.isItemTradeable(is)) {
3691 continue;
3692 }
3693 l_is.add(is);
3694 }
3695
3696 for (ItemStack is : p.getInventory().getArmorContents()) {
3697 if (is == null || is.getType() == Material.AIR) {
3698 continue;
3699 }
3700 armor_list.add(is);
3701 }
3702
3703 log.info(Ansi.ansi().fg(Ansi.Color.CYAN).boldOff().toString() + "[HIVE (SLAVE Edition)] Player " + p.getName()
3704 + " logged out in combat, NPC spawned." + Ansi.ansi().fg(Ansi.Color.WHITE).boldOff().toString());
3705
3706 final Entity ent = combatLogNPC.getBukkitEntity();
3707
3708 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
3709 public void run() {
3710 Player playerNPC = ((Player) ent);
3711
3712 EntityPlayer origin_p = ((CraftPlayer) p).getHandle();
3713 net.minecraft.server.v1_7_R2.ItemStack weapon = null, boots = null, legs = null, chest = null, head = null;
3714
3715 if (origin_p.getEquipment(0) != null) {
3716 weapon = origin_p.getEquipment(0);
3717 }
3718 if (origin_p.getEquipment(1) != null) {
3719 boots = origin_p.getEquipment(1);
3720 }
3721 if (origin_p.getEquipment(2) != null) {
3722 legs = origin_p.getEquipment(2);
3723 }
3724 if (origin_p.getEquipment(3) != null) {
3725 chest = origin_p.getEquipment(3);
3726 }
3727 if (origin_p.getEquipment(4) != null) {
3728 head = origin_p.getEquipment(4);
3729 }
3730
3731 EntityPlayer ent_p_edited = ((CraftPlayer) playerNPC).getHandle();
3732
3733 List<Packet> pack_list = new ArrayList<Packet>();
3734 if (weapon != null) {
3735 pack_list.add(new PacketPlayOutEntityEquipment(ent_p_edited.getId(), 0, weapon));
3736 }
3737 if (boots != null) {
3738 pack_list.add(new PacketPlayOutEntityEquipment(ent_p_edited.getId(), 1, boots));
3739 }
3740 if (legs != null) {
3741 pack_list.add(new PacketPlayOutEntityEquipment(ent_p_edited.getId(), 2, legs));
3742 }
3743 if (chest != null) {
3744 pack_list.add(new PacketPlayOutEntityEquipment(ent_p_edited.getId(), 3, chest));
3745 }
3746 if (head != null) {
3747 pack_list.add(new PacketPlayOutEntityEquipment(ent_p_edited.getId(), 4, head));
3748 }
3749
3750 for (Player pl : safe_lpnear) {
3751 if (pl != null) {
3752 for (Packet pa : pack_list) {
3753 ((CraftPlayer) pl).getHandle().playerConnection.sendPacket(pa);
3754 }
3755 }
3756 }
3757
3758 try {
3759 Field underlyingEntityField = CraftEntity.class.getDeclaredField("entity");
3760 underlyingEntityField.setAccessible(true);
3761 Object underlyingPlayerObj = underlyingEntityField.get(playerNPC);
3762 if (underlyingPlayerObj instanceof EntityPlayer) {
3763 EntityPlayer underlyingPlayer = (EntityPlayer) underlyingPlayerObj;
3764 underlyingPlayer.invulnerableTicks = 1;
3765 }
3766 } catch (Exception e) {
3767 log.info("LoginInvulnerabilityFix exception: " + e.getMessage());
3768 e.printStackTrace();
3769 }
3770
3771 }
3772 }, 4L);
3773
3774 }
3775
3776 safe_logout.remove(p.getName());
3777 safe_logout_location.remove(p.getName());
3778
3779 pname = p.getName();
3780 final String safe_pname = pname;
3781
3782 /*
3783 * this.getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){ public void run() { UploadPlayerData.uploadData(safe_pname); } }, 0L);
3784 */
3785
3786 Thread t = new UploadPlayerData(safe_pname);
3787 t.start();
3788 }
3789
3790 public String addPatchVersion(String motd) {
3791 // It's 48 characters to get to where we need to be. (from 0)
3792 String motd_with_space = motd + "";
3793 String patch_string = ChatColor.GRAY + "Patch " + Config.version;
3794 int needed_space = (int) (58 - ((ChatColor.stripColor(motd).length()) * 1.25));
3795 while (needed_space > 0) {
3796 needed_space--;
3797 motd_with_space += " ";
3798 }
3799 motd_with_space += patch_string;
3800 return motd_with_space;
3801 }
3802
3803 public int getLoadPercent() {
3804 double percent = (uptime * (6.6 / 4));
3805 if (percent > 100) {
3806 percent = 100;
3807 }
3808 return (int) Math.round(percent);
3809 }
3810
3811 public int getTimeToReboot() {
3812 return (int) seconds_to_reboot;
3813 }
3814
3815 @EventHandler(priority = EventPriority.MONITOR)
3816 public void onServerListPingEvent(ServerListPingEvent e) {
3817 if (local_ddos == true || hive_ddos == true) {
3818 String motd = ChatColor.RED.toString() + "[DESYNC] " + ChatColor.WHITE.toString() + e.getMotd();
3819 motd = addPatchVersion(motd);
3820
3821 e.setMotd(motd);
3822 return;
3823 }
3824 if (loading_server == true) {
3825 String motd = ChatColor.AQUA.toString() + "LOADING " + getLoadPercent() + "% " + ChatColor.WHITE.toString() + e.getMotd();
3826 motd = addPatchVersion(motd);
3827
3828 e.setMotd(motd);
3829 return;
3830 }
3831 if (restart_inc == true) {
3832 String motd = ChatColor.RED.toString() + "REBOOT " + (int) seconds_to_reboot + ChatColor.BOLD + "s" + ChatColor.RED + " "
3833 + ChatColor.WHITE.toString() + e.getMotd();
3834 motd = addPatchVersion(motd);
3835
3836 e.setMotd(motd);
3837 return;
3838 }
3839 if (server_lock == true) {
3840 String motd = ChatColor.DARK_GRAY.toString() + "[LOCKED] " + ChatColor.WHITE.toString() + e.getMotd();
3841 motd = addPatchVersion(motd);
3842
3843 e.setMotd(motd);
3844 return;
3845 } else {
3846 String motd = ChatColor.WHITE.toString() + e.getMotd();
3847 motd = addPatchVersion(motd);
3848
3849 e.setMotd(motd);
3850 }
3851 }
3852
3853 public static boolean hasConnection() {
3854 Socket socket = null;
3855 boolean reachable = false;
3856 try {
3857 socket = new Socket("google.com", 80);
3858 reachable = true;
3859 } catch (Exception err) {
3860 } finally {
3861 if (socket != null)
3862 try {
3863 socket.close();
3864 } catch (IOException e) {
3865 }
3866 }
3867
3868 return reachable;
3869 }
3870
3871 public static boolean isHiveOnline() {
3872 Socket socket = null;
3873 try {
3874 socket = new Socket(Config.Hive_IP, Config.SQL_port);
3875 socket.close();
3876 return true;
3877 } catch (Exception err) {
3878 } finally {
3879 if (socket != null)
3880 try {
3881 socket.close();
3882 } catch (Exception e) {
3883 }
3884 }
3885 return false;
3886 }
3887
3888 public void downloadPayload() throws IOException {
3889 new File(rootDir + "/" + "payload.zip").delete();
3890
3891 try {
3892 Thread.sleep(1000);
3893 } catch (InterruptedException e) {
3894 e.printStackTrace();
3895 }
3896
3897 URL url = new URL("ftp://" + Config.ftp_user + ":" + Config.ftp_pass + "@" + Config.Hive_IP + "/sdata/payload.zip");
3898 URLConnection urlc;
3899
3900 try {
3901 urlc = url.openConnection();
3902
3903 InputStream is = urlc.getInputStream();
3904 OutputStream out = new FileOutputStream(rootDir + "/" + "payload.zip");
3905
3906 byte buf[] = new byte[1024];
3907 int len;
3908
3909 while ((len = is.read(buf)) > 0) {
3910 out.write(buf, 0, len);
3911 }
3912
3913 out.close();
3914 is.close();
3915
3916 } catch (Exception err) {
3917 err.printStackTrace();
3918 log.info("[HIVE (SLAVE Edition) An error has occured in attempting to retrieve file payload from hive.");
3919 try {
3920 Thread.sleep(1000);
3921 } catch (InterruptedException e) {
3922 e.printStackTrace();
3923 }
3924 downloadPayload();
3925 return;
3926 }
3927
3928 log.info("[HIVE (SLAVE Edition)] Payload recieved.");
3929
3930 while (!(new File(rootDir + "/" + "payload.zip").exists())) {
3931 try {
3932 Thread.sleep(1000);
3933 } catch (InterruptedException e) {
3934 e.printStackTrace();
3935 }
3936 }
3937
3938 processPayload();
3939 }
3940
3941 public void processPayload() {
3942 log.info("[HIVE (SLAVE Edition)] Payload processing...");
3943
3944 Thread t = new Thread(new Runnable() {
3945 public void run() {
3946 int count = 0;
3947 while (pending_upload.size() > 0 && count <= 200) {
3948 count++;
3949 try {
3950 Thread.sleep(100); // Let all pending multi-thread uploads finish.
3951 } catch (InterruptedException e) {
3952 e.printStackTrace();
3953 }
3954 }
3955
3956 ready_to_die = true;
3957 }
3958 });
3959
3960 t.start();
3961 }
3962
3963 public static void deleteFolder(File folder) {
3964 File[] files = folder.listFiles();
3965 if (files != null) { // some JVMs return null for empty dirs
3966 for (File f : files) {
3967 if (f.isDirectory()) {
3968 deleteFolder(f);
3969 } else {
3970 f.delete();
3971 }
3972 }
3973 }
3974 folder.delete();
3975 }
3976
3977 public static void unzip(String archive, File baseFolder, String[] ignoreExtensions) {
3978 FileInputStream fin;
3979 try {
3980 fin = new FileInputStream(archive);
3981 ZipInputStream zin = new ZipInputStream(fin);
3982 ZipEntry ze = null;
3983 while ((ze = zin.getNextEntry()) != null) {
3984 File destinationFile = new File(baseFolder, ze.getName());
3985 unpackEntry(destinationFile, zin);
3986 }
3987 zin.close();
3988 } catch (IOException e) {
3989 e.printStackTrace();
3990 }
3991 }
3992
3993 private static void unpackEntry(File destinationFile, ZipInputStream zin) {
3994 createParentFolder(destinationFile);
3995 FileOutputStream fout = null;
3996 try {
3997 fout = new FileOutputStream(destinationFile);
3998 for (int c = zin.read(); c != -1; c = zin.read()) {
3999 fout.write(c);
4000 zin.closeEntry();
4001 fout.close();
4002 }
4003 } catch (IOException e) {
4004 e.printStackTrace();
4005 }
4006
4007 }
4008
4009 private static void createParentFolder(File destinationFile) {
4010 File parent = new File(destinationFile.getParent());
4011 parent.mkdirs();
4012 }
4013
4014 public static Inventory getShardInventory() {
4015 if ((System.currentTimeMillis() - last_shard_update) > 10 * 1000) {
4016 ShardMenu = generateShardMenu();
4017 last_shard_update = System.currentTimeMillis();
4018 }
4019 return ShardMenu;
4020 }
4021
4022 public static ItemStack generateShardItem(String server_prefix) {
4023 // TODO: Show where friends/guildies are
4024 int server_num = -1;
4025 ItemStack icon = null;
4026 ChatColor cc = null;
4027 boolean vip_server = false;
4028 boolean rp_server = false;
4029 boolean beta_server = false;
4030
4031 server_num = Integer.parseInt(server_prefix.substring(server_prefix.indexOf("-") + 1, server_prefix.length()));
4032 if (server_prefix.contains("US")) {
4033 }
4034 if (server_prefix.contains("EU")) {
4035 server_num = server_num + 1000;
4036 }
4037 if (server_prefix.contains("BR")) {
4038 server_num = server_num + 2000;
4039 }
4040
4041 if (server_num == 5) {
4042 vip_server = true;
4043 }
4044
4045// if (server_num == 11) {
4046// rp_server = true;
4047// }
4048 if (server_num >= 100 && server_num <= 110) {
4049 beta_server = true;
4050 }
4051
4052 // String IP = CommunityMechanics.server_list.get(server_num);
4053
4054 int online_players = 0;
4055 int max_players = 0;
4056
4057 if (server_population.containsKey(server_num)) {
4058 online_players = server_population.get(server_num).get(0);
4059 max_players = server_population.get(server_num).get(1);
4060 }
4061
4062 // TODO: Ping the server, make sure it's online.
4063 if (server_prefix.equalsIgnoreCase(MOTD.substring(0, MOTD.indexOf(" ")))) {
4064 // This is the server they're on. Green dye to show they're connected.
4065 icon = new ItemStack(Material.WOOL, 1, (short) 5);
4066 cc = ChatColor.GREEN;
4067 online_players = (int) Math.round((double) Bukkit.getOnlinePlayers().length);
4068 max_players = Bukkit.getMaxPlayers();
4069 } else {
4070 boolean server_open = true; // BungeeCord.getInstance().getServerInfo(server_prefix).canAccess((net.md_5.bungee.api.CommandSender) pl);
4071 if ((online_players == 0 && max_players == 0) || offline_servers.contains(server_prefix) || !last_ping.containsKey(server_num)) {
4072 online_players = 0;
4073 max_players = 0;
4074 server_open = false;
4075 }
4076 if (server_open) {
4077 icon = new ItemStack(Material.WOOL, 1, (short) 0);
4078 cc = ChatColor.WHITE;
4079 } else if (!(server_open)) {
4080 icon = new ItemStack(Material.WOOL, 1, (short) 14);
4081 cc = ChatColor.RED;
4082 }
4083 }
4084
4085 ItemMeta im = icon.getItemMeta();
4086
4087 online_players = (int) Math.round(online_players);
4088
4089 if (online_players > max_players) {
4090 // So if the spoofed amount is > the maximum, we're going to take away 5-15 of the online count so more players can join.
4091 online_players = max_players - (new Random().nextInt(15 - 5) + 5);
4092 }
4093
4094 if (online_players > 0 || max_players > 0) {
4095 im.setDisplayName(cc.toString() + server_prefix + ChatColor.GRAY + " " + online_players + "/" + max_players + "");
4096 } else {
4097 im.setDisplayName(cc.toString() + server_prefix);
4098 }
4099 List<String> lore = new ArrayList<String>();
4100
4101 if (vip_server && cc != ChatColor.RED) {
4102 int this_server_num = Integer.parseInt(Bukkit.getMotd().split("-")[1].split(" ")[0]);
4103 if (this_server_num >= 100 && this_server_num <= 110)
4104 icon.setDurability((short) 4);
4105 lore.add(ChatColor.GREEN + "Subscriber Server");
4106 }
4107
4108 if (rp_server && cc != ChatColor.RED) {
4109 lore.add(ChatColor.AQUA + "Roleplay Server");
4110 }
4111
4112 if (server_prefix.contains("BR")) {
4113 lore.add(ChatColor.DARK_AQUA + "Language: Portuguese");
4114 }
4115
4116 if (beta_server && cc != ChatColor.RED) {
4117 lore.add(ChatColor.YELLOW + "Beta Server");
4118 }
4119
4120 if (cc == ChatColor.GREEN) {
4121 lore.add(ChatColor.GRAY.toString() + ChatColor.ITALIC.toString() + "You are currently in this shard.");
4122 } else if (cc == ChatColor.WHITE) {
4123 lore.add(ChatColor.GRAY.toString() + ChatColor.ITALIC.toString() + "Click to join this shard.");
4124 } else if (cc == ChatColor.RED) {
4125 lore.add(ChatColor.RED.toString() + ChatColor.ITALIC + "Shard Offline");
4126 }
4127
4128 im.setLore(lore);
4129 icon.setItemMeta(im);
4130 return icon;
4131 }
4132
4133 public static Inventory generateShardMenu() {
4134 ItemStack divider = ItemMechanics.signCustomItem(Material.THIN_GLASS, (short) 0, " ", "");
4135 ItemStack minecade_lobby = ItemMechanics.signCustomItem(Material.SKULL_ITEM, (short) 3, ChatColor.WHITE + "Lobby", ChatColor.GRAY.toString()
4136 + ChatColor.ITALIC.toString() + "Go back to the lobby.");
4137 Inventory shard_menu = Bukkit.createInventory(null, 18, "Shard Selection");
4138 int index = 0;
4139 for (String s : Config.us_public_servers) {
4140 shard_menu.setItem(index, generateShardItem(s));
4141 index++;
4142 }
4143
4144 // index = 9; // Move to next row for BR servers.
4145 // br servers are no longer used
4146/* for (String s : Config.br_servers) {
4147 shard_menu.setItem(index, generateShardItem(s));
4148 index++;
4149 }*/
4150
4151 // index = 18;
4152
4153 for (String s : Config.us_private_servers) {
4154 shard_menu.setItem(index, generateShardItem(s));
4155 index++;
4156 }
4157
4158 shard_menu.setItem(8, minecade_lobby);
4159 index = 9;
4160
4161 for (String s : Config.us_beta_servers) {
4162 shard_menu.setItem(index, generateShardItem(s));
4163 index++;
4164 }
4165
4166 int x = 0;
4167 for (ItemStack is : shard_menu.getContents()) {
4168 if (is == null || is.getType() == Material.AIR) {
4169 shard_menu.setItem(x, CraftItemStack.asCraftCopy(divider));
4170 }
4171 x++;
4172 }
4173
4174 return shard_menu;
4175 }
4176
4177 public boolean vipServer(ItemStack is) {
4178 if (is != null && is.hasItemMeta() && is.getItemMeta().hasLore()) {
4179 List<String> lore = is.getItemMeta().getLore();
4180 for (String s : lore) {
4181 s = ChatColor.stripColor(s);
4182 if (s.equalsIgnoreCase("Subscriber Server")) {
4183 return true;
4184 }
4185 }
4186 }
4187 return false;
4188 }
4189
4190 public static ItemStack setECASHPrice(ItemStack i, double price) {
4191 boolean rename = false;
4192 String o_name = "";
4193 try {
4194 try {
4195 o_name = CraftItemStack.asNMSCopy(i).getTag().getCompound("display").getString("Name");
4196 rename = true;
4197 // log.info(o_name);
4198 } catch (NullPointerException npe) {
4199 rename = false;
4200 }
4201 } catch (ClassCastException cce) {
4202 rename = false;
4203 }
4204
4205 List<String> old_lore = new ArrayList<String>();
4206 ItemMeta im = i.getItemMeta();
4207
4208 if (i != null && i.hasItemMeta() && i.getItemMeta().hasLore()) {
4209 for (String s : im.getLore()) {
4210 old_lore.add(s);
4211 }
4212
4213 if (rename == true && o_name.length() > 0) {
4214 im.setDisplayName(o_name);
4215 }
4216
4217 old_lore.add(ChatColor.WHITE.toString() + price + ChatColor.GREEN.toString() + " E-CASH");
4218 im.setLore(old_lore);
4219 i.setItemMeta(im);
4220 }
4221
4222 if (i != null && !(i.hasItemMeta())) {
4223 old_lore.add(ChatColor.WHITE.toString() + price + ChatColor.GREEN.toString() + " E-CASH");
4224 im.setLore(old_lore);
4225 i.setItemMeta(im);
4226 }
4227
4228 return i;
4229 }
4230
4231 public static double getECASHPrice(ItemStack is) {
4232 if (is != null && is.hasItemMeta() && is.getItemMeta().hasLore()) {
4233 for (String s : is.getItemMeta().getLore()) {
4234 if (s.contains("E-CASH")) {
4235 return Double.parseDouble(ChatColor.stripColor((s.substring(0, s.indexOf(" ")))));
4236 }
4237 }
4238 }
4239 return 0;
4240 }
4241
4242 public static boolean doTheyHaveEnoughECASH(String p_name, int needed) {
4243 if (player_ecash.containsKey(p_name) && player_ecash.get(p_name) >= needed) {
4244 return true;
4245 }
4246 return false;
4247 }
4248
4249 public void sendConsoleMessage(String message) {
4250 Bukkit.getConsoleSender().sendMessage(message);
4251 }
4252
4253 @EventHandler
4254 public void onInventoryClick(InventoryClickEvent e) {
4255 if (e.getInventory().getName().equalsIgnoreCase("Shard Selection")) {
4256 e.setCancelled(true);
4257 final Player pl = (Player) e.getWhoClicked();
4258 if (e.getRawSlot() >= 27) {
4259 return;
4260 }
4261 if (e.getCurrentItem() == null) {
4262 return;
4263 }
4264
4265 ItemStack cur_item = e.getCurrentItem();
4266
4267 if (cur_item.getType() == Material.SKULL_ITEM
4268 || (cur_item.getType() == Material.WOOL && cur_item.hasItemMeta() && cur_item.getItemMeta().hasDisplayName() && cur_item.getItemMeta()
4269 .hasLore())) {
4270 // Hop servers?
4271 short durability = cur_item.getDurability();
4272 if (durability == 5) {
4273 // Current server, do nothing.
4274 pl.sendMessage(ChatColor.YELLOW + "You are already on the " + ChatColor.BOLD + MOTD.substring(0, MOTD.indexOf(" ")) + ChatColor.YELLOW
4275 + " shard.");
4276 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4277 public void run() {
4278 pl.closeInventory();
4279 }
4280 }, 2L);
4281
4282 }
4283 if (durability == 14) {
4284 // Current server, do nothing.
4285 pl.sendMessage(ChatColor.RED + "This shard is currently " + ChatColor.UNDERLINE + "unavailable.");
4286 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4287 public void run() {
4288 pl.closeInventory();
4289 }
4290 }, 2L);
4291 }
4292
4293 if (durability == 4) {
4294 // Sub Server From Beta Server
4295 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "must" + ChatColor.RED
4296 + " join this shard from a public shard, not a beta shard!");
4297 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4298 public void run() {
4299 pl.closeInventory();
4300 }
4301 }, 2L);
4302 }
4303
4304 if (durability == 0 || cur_item.getType() == Material.SKULL_ITEM) {
4305 // Ok, need to move them to new server.
4306
4307 boolean deny = false;
4308
4309 if (!deny && no_shard) {
4310 pl.sendMessage(ChatColor.RED + "This feature is " + ChatColor.UNDERLINE + "temporarily" + ChatColor.RED
4311 + " disabled while we troubleshoot.");
4312 deny = true;
4313 }
4314 if (!deny && TutorialMechanics.onTutorialIsland(pl)) {
4315 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED
4316 + " change game shards while on Tutorial Island.");
4317 deny = true;
4318 }
4319 if (!deny && HealthMechanics.in_combat.containsKey(pl.getName())) {
4320 double seconds_left = 0;
4321 long dif = ((HealthMechanics.HealthRegenCombatDelay * 1000) + HealthMechanics.in_combat.get(pl.getName())) - System.currentTimeMillis();
4322 seconds_left = (dif / 1000.0D) + 0.5D;
4323 seconds_left = Math.round(seconds_left);
4324
4325 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards while in combat.");
4326 pl.sendMessage(ChatColor.GRAY + "Try again in approx. " + seconds_left + ChatColor.BOLD + "s");
4327 deny = true;
4328 }
4329 if (!deny && !DuelMechanics.isDamageDisabled(pl.getLocation()) && LootMechanics.isMonsterNearPlayer(pl, 16)) {
4330 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards with hostile monsters nearby.");
4331 pl.sendMessage(ChatColor.GRAY + "Eliminate all monsters in a 16x16 area and try again.");
4332 deny = true;
4333 }
4334 if (!deny && (Hive.seconds_to_reboot <= 10 && Hive.restart_inc) || Hive.server_lock || Hive.local_ddos || Hive.hive_ddos) {
4335 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards at the moment.");
4336 pl.sendMessage(ChatColor.GRAY + "The servers are likely preparing to reboot or enter maintenance mode.");
4337 deny = true;
4338 }
4339 if (!deny && DuelMechanics.duel_map.containsKey(pl.getName())) {
4340 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards while in a duel.");
4341 deny = true;
4342 }
4343 if (!deny && InstanceMechanics.isInstance(pl.getWorld().getName())) {
4344 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards while in an instance.");
4345 deny = true;
4346 }
4347 if (!deny && !(pl.getWorld().getName().equalsIgnoreCase(main_world_name))) {
4348 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards while in a realm.");
4349 deny = true;
4350 }
4351 if (!deny && MountMechanics.mount_map.containsKey(pl.getName())) {
4352 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED + " change shards while on a mount.");
4353 deny = true;
4354 }
4355 if (!deny && !pl.isOp() && !DuelMechanics.isDamageDisabled(pl.getLocation()) && Hive.login_time.containsKey(pl.getName())
4356 && (((System.currentTimeMillis() - Hive.login_time.get(pl.getName())) / 1000.0D) <= 300)) {
4357 int seconds_left = 300 - ((int) ((System.currentTimeMillis() - Hive.login_time.get(pl.getName())) / 1000.0D));
4358 pl.sendMessage(ChatColor.RED + "You " + ChatColor.UNDERLINE + "cannot" + ChatColor.RED
4359 + " change shards while in a wilderness / chaotic zone for another " + ChatColor.UNDERLINE + seconds_left + ChatColor.BOLD
4360 + "s");
4361 pl.sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + "This delay is to prevent resource, monster, and treasure farming abuse.");
4362 deny = true;
4363 }
4364
4365 if (deny) {
4366 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4367 public void run() {
4368 pl.closeInventory();
4369 }
4370 }, 2L);
4371 return;
4372 }
4373
4374 if (Hive.restart_inc || Hive.server_lock || Hive.local_ddos || Hive.hive_ddos) {
4375 pl.sendMessage(ChatColor.RED + "This opperation is currently " + ChatColor.UNDERLINE + "unavailable.");
4376 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4377 public void run() {
4378 pl.closeInventory();
4379 }
4380 }, 2L);
4381 return;
4382 }
4383
4384 if (vipServer(cur_item)) {
4385 String rank = PermissionMechanics.getRank(pl.getName());
4386 boolean op = false;
4387 for (OfflinePlayer p : Bukkit.getOperators()) {
4388 if (p.getName().equalsIgnoreCase(pl.getName())) {
4389 op = true;
4390 break;
4391 }
4392 }
4393 if (rank.equalsIgnoreCase("default") && !(pl.isOp()) && !Main.isMaster(pl.getName()) && !op) {
4394 // Don't let them in.
4395 pl.sendMessage(ChatColor.RED + "You are " + ChatColor.UNDERLINE + "not" + ChatColor.RED
4396 + " authorized to connect to subscriber only servers.");
4397 pl.sendMessage(ChatColor.GRAY + "Subscribe at http://s4scraft.net/shop to gain instant access!");
4398 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4399 public void run() {
4400 pl.closeInventory();
4401 }
4402 }, 2L);
4403 return;
4404 }
4405 }
4406
4407 String i_name = ChatColor.stripColor(cur_item.getItemMeta().getDisplayName());
4408 final String server_prefix = !i_name.contains("Minecade") ? i_name.substring(0, i_name.indexOf(" ")) : "lobby1";
4409
4410 if (cur_item.getType() != Material.SKULL_ITEM) {
4411 int online = Integer.parseInt(i_name.substring(i_name.lastIndexOf(" ") + 1, i_name.lastIndexOf("/")));
4412 int max_online = Integer.parseInt(i_name.substring(i_name.lastIndexOf("/") + 1, i_name.length()));
4413
4414 // TODO: The stats on /shard are not in realtime, do we allow overflow or should we use ServerSwitchEvent to catch it?
4415 if (online >= max_online && online != 0) {
4416 // int group = forum_usergroup.get(pl.getName());
4417 String rank = PermissionMechanics.getRank(pl.getName());
4418 if (!pl.isOp() && rank.equalsIgnoreCase("default")) {
4419 pl.sendMessage(ChatColor.RED + "This shard is currently " + ChatColor.UNDERLINE + "FULL.");
4420 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4421 public void run() {
4422 pl.closeInventory();
4423 }
4424 }, 2L);
4425 return;
4426 }
4427 }
4428 }
4429
4430 server_swap.put(pl.getName(), server_prefix);
4431 server_swap_location.put(pl.getName(), pl.getLocation());
4432 server_swap_pending.remove(pl.getName()); // Remove AFTER server_swap has been populated.
4433
4434 if (!(pl.getWorld().getName().equalsIgnoreCase(main_world_name))) {
4435 Location safe = null;
4436 if (RealmMechanics.saved_locations.containsKey(pl.getName())) {
4437 safe = RealmMechanics.saved_locations.get(pl.getName());
4438 if (RealmMechanics.inv_portal_map.containsKey(pl.getName())) {
4439 Location l = RealmMechanics.inv_portal_map.get(pl.getName());
4440 RealmMechanics.inv_portal_map.remove(pl.getName());
4441 RealmMechanics.portal_map.remove(l);
4442 l.getBlock().setType(Material.AIR);
4443 l.subtract(0, 1, 0).getBlock().setType(Material.AIR);
4444 }
4445 } else if (InstanceMechanics.saved_location_instance.containsKey(pl.getName())) {
4446 safe = InstanceMechanics.saved_location_instance.get(pl.getName());
4447 } else {
4448 safe = SpawnMechanics.getRandomSpawnPoint(pl.getName());
4449 }
4450
4451 pl.teleport(safe);
4452 }
4453
4454 // pl.saveData();
4455 player_inventory.put(pl.getName(), pl.getInventory());
4456 player_location.put(pl.getName(), pl.getLocation());
4457 player_hp.put(pl.getName(), (double) pl.getHealth());
4458 player_level.put(pl.getName(), HealthMechanics.getPlayerHP(pl.getName()));
4459 player_food_level.put(pl.getName(), pl.getFoodLevel());
4460 player_armor_contents.put(pl.getName(), pl.getInventory().getArmorContents());
4461 // Update local data.
4462
4463 pl.sendMessage("");
4464 pl.sendMessage(ChatColor.YELLOW + " Loading Shard - " + ChatColor.BOLD + server_prefix + ChatColor.YELLOW + " ... ");
4465 pl.sendMessage(ChatColor.GRAY.toString() + ChatColor.ITALIC.toString()
4466 + "Your current game session has been paused while your data is transferred.");
4467 pl.sendMessage("");
4468
4469 Main.plugin.getServer().getScheduler().runTaskAsynchronously(Main.plugin, new Runnable() {
4470 public void run() {
4471 try {
4472 ParticleEffect.sendToLocation(ParticleEffect.HAPPY_VILLAGER, pl.getLocation(), new Random().nextFloat(),
4473 new Random().nextFloat(), new Random().nextFloat(), 1F, 10);
4474 } catch (Exception e) {
4475 e.printStackTrace();
4476 }
4477 /*
4478 * pl.getWorld().spawnParticle(pl.getLocation().add(0.5, 0.5, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4479 * pl.getWorld().spawnParticle(pl.getLocation().add(0, 0.5, 0.5), Particle.HAPPY_VILLAGER, 0.5F, 1);
4480 *
4481 * pl.getWorld().spawnParticle(pl.getLocation().add(0, 0.75, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4482 * pl.getWorld().spawnParticle(pl.getLocation().add(0.25, 0.75, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4483 *
4484 * pl.getWorld().spawnParticle(pl.getLocation().add(0, 1, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4485 * pl.getWorld().spawnParticle(pl.getLocation().add(0.25, 1, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4486 *
4487 * pl.getWorld().spawnParticle(pl.getLocation().add(0, 1.50, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4488 * pl.getWorld().spawnParticle(pl.getLocation().add(0.25, 1.50, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4489 *
4490 * pl.getWorld().spawnParticle(pl.getLocation().add(0, 2, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4491 * pl.getWorld().spawnParticle(pl.getLocation().add(0.25, 2, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4492 *
4493 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0.5, -0.5, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4494 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0, -0.5, 0.5), Particle.HAPPY_VILLAGER, 0.5F, 1);
4495 *
4496 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0, -0.75, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4497 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0.25, -0.75, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4498 *
4499 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0, -1, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4500 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0.25, -1, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4501 *
4502 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0, -1.50, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4503 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0.25, -1.50, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4504 *
4505 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0, -2, 0.25), Particle.HAPPY_VILLAGER, 0.5F, 1);
4506 * pl.getWorld().spawnParticle(pl.getLocation().subtract(0.25, -2, 0), Particle.HAPPY_VILLAGER, 0.5F, 1);
4507 */
4508 }
4509 });
4510
4511 for (Player p_online : Bukkit.getServer().getOnlinePlayers()) {
4512 p_online.hidePlayer(pl);
4513 }
4514
4515 // We should give them god mode so they can't die which would cause dupe issues.
4516 // pl.setPlayerListName(""); // So server treats them like NPC, no trading, etc.
4517 RealmMechanics.player_god_mode.put(pl.getName(), System.currentTimeMillis());
4518
4519 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4520 public void run() {
4521 pl.closeInventory();
4522 }
4523 }, 2L);
4524
4525 new BukkitRunnable() {
4526 @Override
4527 public void run() {
4528 // UploadPlayerData.uploadData(pl.getName());
4529 Thread t = new UploadPlayerData(pl.getName());
4530 t.start();
4531 }
4532 }.runTaskLaterAsynchronously(Main.plugin, 4L);
4533
4534 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4535 public void run() {
4536 // 30 second timeout, if they're still online then d/c them.
4537 if (Main.plugin.getServer().getPlayer(pl.getName()) != null && server_swap.containsKey(pl.getName())) {
4538 Player upl = Main.plugin.getServer().getPlayer(pl.getName());
4539 upl.kickPlayer("Connection Timeout");
4540 }
4541 }
4542 }, 10 * 20L);
4543 // TODO: We might need to do some extra data transfer stuff, upload data first then move.
4544 }
4545 }
4546 }
4547 }
4548
4549 @EventHandler(priority = EventPriority.LOWEST)
4550 public void onPlayerInteract(PlayerInteractEvent e) {
4551 Player pl = e.getPlayer();
4552 if (server_swap.containsKey(pl.getName())) {
4553 e.setCancelled(true);
4554 e.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
4555 e.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
4556 }
4557 }
4558
4559 @EventHandler(priority = EventPriority.LOWEST)
4560 public void onPlayerAnimation(PlayerAnimationEvent e) {
4561 Player pl = e.getPlayer();
4562
4563 Player ply = TradeMechanics.getTarget(pl);
4564 /*
4565 * if(ply != null && EcashMechanics.personal_clones.containsKey(pl.getName())){ RemoteEntity npc = EcashMechanics.personal_clones.get(pl.getName());
4566 * String pl_name = pl.getName();
4567 *
4568 * if(pl_name.length() > 14){ pl_name = pl_name.substring(0, 14); }
4569 *
4570 * if(ChatColor.stripColor(ply.getName()).equalsIgnoreCase(pl_name)){ List<Player> lpl = new ArrayList<Player>(); for(Entity ent :
4571 * npc.getBukkitEntity().getNearbyEntities(32, 32, 32)){ if(ent instanceof Player){ lpl.add((Player)ent); } }
4572 *
4573 * npc.getBukkitEntity().remove(); //ShopMechanics.updateEntity(npc.getBukkitEntity(), lpl); //EcashMechanics.personal_clones.remove(pl.getName());
4574 * EcashMechanics.personal_clones_msg.remove(pl.getName()); try { ParticleEffect.sendToLocation(ParticleEffect.CRIT,
4575 * npc.getBukkitEntity().getLocation().add(0, 1, 0), new Random().nextFloat(), new Random().nextFloat(), new Random().nextFloat(), 1, 10); } catch
4576 * (Exception e1) { e1.printStackTrace(); } return; } }
4577 */
4578
4579 if (ply != null && Hive.player_to_npc.containsKey(ply.getName())) {
4580 // ply.damage(ply.getHealth());
4581 // ply.playEffect(EntityEffect.DEATH);
4582
4583 if (Hive.player_to_npc.containsKey(ply.getName())) { // It was an NPC that died!
4584 NPC n = player_to_npc.get(ply.getName());
4585 ply.playEffect(EntityEffect.DEATH);
4586
4587 String align = null;
4588 if (Hive.player_to_npc_align.containsKey(ply.getName())) {
4589 align = Hive.player_to_npc_align.get(ply.getName());
4590 }
4591
4592 boolean neutral_boots = false, neutral_legs = false, neutral_chest = false, neutral_helmet = false, neutral_weapon = false;
4593
4594 /*
4595 * if(align != null && align.equalsIgnoreCase("neutral")){ align = "evil"; Temp. fix -- just drop everything if they combat log as neutrals. }
4596 */
4597
4598 if (align != null && align.equalsIgnoreCase("neutral")) {
4599 // 50% of weapon dropping, 25% for every piece of equipped armor.
4600 String lost_gear_s = "";
4601 if (new Random().nextInt(100) <= 50) {
4602 neutral_weapon = true;
4603 lost_gear_s += "0" + ",";
4604 }
4605
4606 if (new Random().nextInt(100) <= 25) {
4607 int index = new Random().nextInt(4);
4608 if (index == 0) {
4609 neutral_boots = true;
4610 lost_gear_s += "1" + ",";
4611 }
4612 if (index == 1) {
4613 neutral_legs = true;
4614 lost_gear_s += "2" + ",";
4615 }
4616 if (index == 2) {
4617 neutral_chest = true;
4618 lost_gear_s += "3" + ",";
4619 }
4620 if (index == 3) {
4621 neutral_helmet = true;
4622 lost_gear_s += "4" + ",";
4623 }
4624 }
4625
4626 if (lost_gear_s.length() > 0) {
4627 Hive.sql_query.add("INSERT INTO player_database(p_name, lost_gear) VALUES('" + ply.getName() + "', '" + lost_gear_s
4628 + "') ON DUPLICATE KEY UPDATE lost_gear='" + lost_gear_s + "'");
4629 // Now when the player logs in, the server will know exactly which items to take away.
4630 }
4631 }
4632
4633 List<ItemStack> p_inv = new ArrayList<ItemStack>(Arrays.asList(ply.getInventory().getContents()));
4634 if (align != null && !align.equalsIgnoreCase("evil")) {
4635 if (!neutral_weapon && !ProfessionMechanics.isSkillItem(p_inv.get(0)) && p_inv.get(0) != null
4636 && !ItemMechanics.getDamageData(p_inv.get(0)).equalsIgnoreCase("no")) {
4637 try {
4638 p_inv.remove(0); // Remove first hand weapon drop.
4639 } catch (IndexOutOfBoundsException ioobe) {
4640 // Why is this even thrown?
4641 }
4642 }
4643 }
4644
4645 for (ItemStack is : p_inv) {
4646 if (align != null && !align.equalsIgnoreCase("evil")) {
4647 // They're not chaotic.
4648 if (ProfessionMechanics.isSkillItem(is)) {
4649 // Do not drop pickaxes, fishingrods.
4650 continue;
4651 }
4652 }
4653 Entity item = ply.getWorld().dropItemNaturally(ply.getLocation(), is);
4654 item.setMetadata("player_drop", new FixedMetadataValue(Main.plugin, ""));
4655 }
4656
4657 if (align != null && (align.equalsIgnoreCase("evil") || align.equalsIgnoreCase("neutral"))) {
4658 // Drop armor as well if chaotic.
4659 for (ItemStack is : ply.getInventory().getArmorContents()) {
4660 if (is == null || is.getType() == Material.AIR) {
4661 continue;
4662 }
4663 if (align.equalsIgnoreCase("neutral")) {
4664 if (is.getType().name().toLowerCase().contains("helmet") && !neutral_helmet) {
4665 continue;
4666 }
4667 if (is.getType().name().toLowerCase().contains("leggings") && !neutral_legs) {
4668 continue;
4669 }
4670 if (is.getType().name().toLowerCase().contains("chestplate") && !neutral_chest) {
4671 continue;
4672 }
4673 if (is.getType().name().toLowerCase().contains("boots") && !neutral_boots) {
4674 continue;
4675 }
4676 }
4677 Entity item = ply.getWorld().dropItemNaturally(ply.getLocation(), is);
4678 item.setMetadata("player_drop", new FixedMetadataValue(Main.plugin, ""));
4679 }
4680 }
4681
4682 if (Hive.player_mule_inventory.containsKey(ply.getName())) {
4683 // They have a mule in their inventory whose items need to be dropped.
4684 for (ItemStack is : Hive.player_mule_inventory.get(ply.getName())) {
4685 if (is == null || is.getType() == Material.AIR) {
4686 continue;
4687 }
4688 Entity item = ply.getWorld().dropItemNaturally(ply.getLocation(), is);
4689 item.setMetadata("player_drop", new FixedMetadataValue(Main.plugin, ""));
4690 }
4691 }
4692
4693 Hive.player_to_npc.remove(ply.getName());
4694 Hive.player_to_npc_align.remove(ply.getName());
4695 Hive.player_item_in_hand.remove(ply.getName());
4696 Hive.player_mule_inventory.remove(ply.getName());
4697 List<Player> lpl = new ArrayList<Player>();
4698 for (Entity ent : n.getBukkitEntity().getNearbyEntities(32, 32, 32)) {
4699 if (ent instanceof Player) {
4700 lpl.add((Player) ent);
4701 }
4702 }
4703
4704 n.despawn();
4705 n.destroy();
4706 }
4707
4708 }
4709 if (server_swap.containsKey(pl.getName())) {
4710 e.setCancelled(true);
4711 }
4712 }
4713
4714 @EventHandler(priority = EventPriority.LOWEST)
4715 public void onPlayerDropItem(PlayerDropItemEvent e) {
4716 Player pl = e.getPlayer();
4717 if (server_swap.containsKey(pl.getName()) || (System.currentTimeMillis() - login_time.get(pl.getName())) <= 5000) {
4718 e.setCancelled(true);
4719 return;
4720 }
4721 if (InstanceMechanics.isInstance(e.getItemDrop().getWorld().getName())) {
4722 if (ItemMechanics.isArmor(e.getItemDrop().getItemStack()) || ItemMechanics.isWeapon(e.getItemDrop().getItemStack())) {
4723 // They are dropping armor so dont remove it >.>
4724 e.getItemDrop().setMetadata("player_drop", new FixedMetadataValue(Main.plugin, ""));
4725 }
4726 }
4727 }
4728
4729 @EventHandler(priority = EventPriority.LOWEST)
4730 public void onCommandPreProcessPrevent(PlayerCommandPreprocessEvent e) {
4731 Player pl = e.getPlayer();
4732 if (server_swap.containsKey(pl.getName())) {
4733 log.info("Cancelled command due to server_swap!");
4734 e.setCancelled(true);
4735 }
4736 }
4737
4738 @EventHandler(priority = EventPriority.LOWEST)
4739 public void onPlayerChatEvent(AsyncPlayerChatEvent e) {
4740 Player pl = e.getPlayer();
4741 if (server_swap_pending.containsKey(pl.getName()) || server_swap.containsKey(pl.getName())) {
4742 e.setCancelled(true);
4743 }
4744 }
4745
4746 @EventHandler(priority = EventPriority.LOWEST)
4747 public void onInventoryOpen(InventoryOpenEvent e) {
4748 Player pl = (Player) e.getPlayer();
4749 if (server_swap.containsKey(pl.getName())) {
4750 e.setCancelled(true);
4751 }
4752 }
4753
4754 @EventHandler(priority = EventPriority.LOWEST)
4755 public void onInventoryClickPrevent(InventoryClickEvent e) {
4756 Player pl = (Player) e.getWhoClicked();
4757 if (server_swap.containsKey(pl.getName())) {
4758 e.setCancelled(true);
4759 }
4760 }
4761
4762 @EventHandler
4763 public void onInventoryClose(InventoryCloseEvent e) {
4764 final Player pl = (Player) e.getPlayer();
4765 if (server_swap_pending.containsKey(pl.getName())) {
4766 // Remove in 2 ticks.
4767 Main.plugin.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
4768 public void run() {
4769 server_swap_pending.remove(pl.getName());
4770 }
4771 }, 2L);
4772 }
4773 }
4774
4775}