1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
|
package com.earth2me.essentials;
import com.earth2me.essentials.commands.EssentialsCommand;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.commands.IEssentialsCommand;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.command.PluginCommand;
import org.bukkit.craftbukkit.scheduler.CraftScheduler;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.*;
import org.yaml.snakeyaml.*;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class Essentials extends JavaPlugin
{
public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans.";
public static final int minBukkitBuildVersion = 556;
private static final Logger logger = Logger.getLogger("Minecraft");
private static final Yaml yaml = new Yaml(new SafeConstructor());
private static Map<String, Object> users;
private static Settings settings;
private static final Object usersLock = new Object();
public static Object permissions = null;
public final Map<User, User> tpcRequests = new HashMap<User, User>();
public final Map<User, Boolean> tpcHere = new HashMap<User, Boolean>();
public final List<User> away = new ArrayList<User>();
private EssentialsPlayerListener playerListener;
private EssentialsBlockListener blockListener;
private EssentialsEntityListener entityListener;
private JailPlayerListener jailPlayerListener;
private static Essentials staticThis = null;
public Spawn spawn;
private Jail jail;
private Warps warps;
private List<IConf> confList;
public ArrayList bans = new ArrayList();
public ArrayList bannedIps = new ArrayList();
public Backup backup;
public Essentials() throws IOException
{
loadClasses();
}
public static void ensureEnabled(Server server)
{
PluginManager pm = server.getPluginManager();
Essentials ess = (Essentials)pm.getPlugin("Essentials");
if (!ess.isEnabled())
pm.enablePlugin(ess);
loadClasses();
}
@SuppressWarnings("CallToThreadDumpStack")
public static void loadClasses()
{
final String[] classes = new String[]
{
"commands.IEssentialsCommand",
"commands.EssentialsCommand",
"User",
"TargetBlock",
"Spawn",
"Settings",
"OfflinePlayer",
"ItemDb",
"Mob"
};
try
{
for (String c : classes)
Essentials.class.getClassLoader().loadClass("com.earth2me.essentials." + c);
}
catch (Throwable ex)
{
ex.printStackTrace();
}
}
public static Essentials getStatic()
{
return staticThis;
}
public static Settings getSettings()
{
return settings;
}
public void setupPermissions()
{
Plugin permPlugin = this.getServer().getPluginManager().getPlugin("Permissions");
if (permissions == null && permPlugin != null) permissions = permPlugin;
}
public Player getPlayer(String[] args, int pos)
throws IndexOutOfBoundsException, NoSuchFieldException
{
if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?");
List<Player> matches = getServer().matchPlayer(args[0]);
if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found.");
return matches.get(0);
}
public void setStatic()
{
staticThis = this;
}
@SuppressWarnings("LoggerStringConcat")
public void onEnable()
{
setStatic();
confList = new ArrayList<IConf>();
settings = new Settings(this.getDataFolder());
confList.add(settings);
this.spawn = new Spawn(getServer(), this.getDataFolder());
confList.add(spawn);
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
reload();
this.backup = new Backup();
PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins()) {
if (plugin.getDescription().getName().startsWith("Essentials")) {
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) {
logger.log(Level.WARNING, "Version mismatch! Please update "+plugin.getDescription().getName()+" to the same version.");
}
}
}
Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches()) {
int versionNumber = Integer.parseInt(versionMatch.group(4));
if (versionNumber < minBukkitBuildVersion) {
logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials.");
}
} else {
logger.log(Level.INFO, "Bukkit version format changed. Version not checked.");
}
playerListener = new EssentialsPlayerListener(this);
pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Monitor, this);
if (getSettings().getNetherPortalsEnabled())
pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this);
blockListener = new EssentialsBlockListener(this);
pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Monitor, this);
pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Monitor, this);
pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Monitor, this);
entityListener = new EssentialsEntityListener(this);
pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this);
jail = new Jail(this.getDataFolder());
jailPlayerListener = new JailPlayerListener(this);
confList.add(jail);
pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this);
pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.High, this);
pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, jailPlayerListener, Priority.High, this);
attachEcoListeners();
if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2)
{
getServer().createWorld(settings.getNetherName(), World.Environment.NETHER);
}
logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS);
}
public void onDisable()
{
staticThis = null;
}
public void reload()
{
loadData();
loadBanList();
for (IConf iConf : confList)
{
iConf.reloadConfig();
}
try
{
ItemDb.load(getDataFolder(), "items.csv");
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Could not load items.csv.", ex);
}
}
public static Map<String, Object> getData(User player)
{
return getData(player.getName());
}
public static Map<String, Object> getData(String player)
{
try
{
Map<String, Object> retval;
synchronized (usersLock)
{
retval = (Map<String, Object>)users.get(player.toLowerCase());
}
return retval == null ? new HashMap<String, Object>() : retval;
}
catch (Throwable ex)
{
return new HashMap<String, Object>();
}
}
public static void flushData()
{
Thread run = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists())
Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists())
file.createNewFile();
FileWriter tx = new FileWriter(file);
synchronized (usersLock)
{
tx.write(yaml.dump(users));
}
tx.flush();
tx.close();
}
catch (Throwable ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
run.setDaemon(false);
run.start();
}
public static void loadData()
{
try
{
if (!Essentials.getStatic().getDataFolder().exists()) Essentials.getStatic().getDataFolder().mkdirs();
File file = new File(Essentials.getStatic().getDataFolder(), "users.yml");
if (!file.exists()) file.createNewFile();
FileInputStream rx = new FileInputStream(file);
synchronized (usersLock)
{
users = (Map<String, Object>)yaml.load(new UnicodeReader(rx));
}
rx.close();
}
catch (Exception ex)
{
Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex);
synchronized (usersLock)
{
users = new HashMap<String, Object>();
}
}
finally
{
synchronized (usersLock)
{
if (users == null) users = new HashMap<String, Object>();
}
}
}
public static void setData(User player, Map<String, Object> data)
{
setData(player.getName(), data);
}
public static void setData(String player, Map<String, Object> data)
{
synchronized (usersLock)
{
users.put(player.toLowerCase(), data);
}
}
public static List<String> readMail(User player)
{
return readMail(player.getName());
}
public static List<String> readMail(String player)
{
try
{
Map<String, Object> data = getData(player);
List<String> retval = (List<String>)data.get("mail");
return retval == null ? new ArrayList<String>() : retval;
}
catch (Throwable ex)
{
return new ArrayList<String>();
}
}
public static void clearMail(User player)
{
try
{
Map<String, Object> data = getData(player);
data.put("mail", new ArrayList<String>());
setData(player, data);
flushData();
}
catch (Throwable ex)
{
}
}
public static void sendMail(User from, String to, String message)
throws Exception
{
try
{
Map<String, Object> data = getData(ChatColor.stripColor(to));
List<String> mail = readMail(to);
mail.add(ChatColor.stripColor(from.getDisplayName()) + ": " + message);
data.put("mail", mail);
setData(to, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while sending the mail.", ex);
}
}
public String readNickname(User player)
{
try
{
Map<String, Object> data = getData(player);
String nick = (String)data.get("nickname");
if (nick == null)
return player.getName();
if (nick.equals(player.getName()))
return player.getName();
return getSettings().getNicknamePrefix() + nick;
}
catch (Exception ex)
{
return player.getName();
}
}
public void saveNickname(User player, String nickname) throws Exception
{
try
{
Map<String, Object> data = getData(player);
data.put("nickname", nickname);
setData(player, data);
flushData();
}
catch (Throwable ex)
{
throw new Exception("An error was encountered while saving the nickname.", ex);
}
}
public String[] getMotd(CommandSender sender, String def)
{
return getLines(sender, "motd", def);
}
public String[] getLines(CommandSender sender, String node, String def)
{
List<String> lines = (List<String>)getConfiguration().getProperty(node);
if (lines == null) return new String[0];
String[] retval = new String[lines.size()];
if (lines == null || lines.isEmpty() || lines.get(0) == null)
{
try
{
lines = new ArrayList<String>();
// "[]" in YaML indicates empty array, so respect that
if (!getConfiguration().getString(node, def).equals("[]"))
{
lines.add(getConfiguration().getString(node, def));
retval = new String[lines.size()];
}
}
catch (Throwable ex2)
{
System.out.println(ChatColor.DARK_RED + "Notice: Your configuration file has a corrupt " + node + " node.");
return new String[0];
}
}
// if still empty, call it a day
if (lines == null || lines.isEmpty() || lines.get(0) == null)
return new String[0];
for (int i = 0; i < lines.size(); i++)
{
String m = lines.get(i);
if (m == null)
continue;
m = m.replace('&', '§').replace("§§", "&");
if (sender instanceof User || sender instanceof Player)
{
User user = User.get(sender);
m = m.replace("{PLAYER}", user.getDisplayName());
m = m.replace("{IP}", user.getAddress().toString());
m = m.replace("{BALANCE}", Double.toString(user.getMoney()));
}
m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length));
if (m.matches(".*\\{PLAYERLIST\\}.*"))
{
StringBuilder online = new StringBuilder();
for (Player p : getServer().getOnlinePlayers())
{
if (online.length() > 0)
online.append(", ");
online.append(p.getDisplayName());
}
m = m.replace("{PLAYERLIST}", online.toString());
}
if (sender instanceof Player)
{
try
{
Class User = getClassLoader().loadClass("bukkit.Vandolis.User");
Object vuser = User.getConstructor(User.class).newInstance((Player)sender);
m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString());
m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString());
m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString());
}
catch (Throwable ex)
{
m = m.replace("{RED:BALANCE}", "N/A");
m = m.replace("{RED:BUYS}", "N/A");
m = m.replace("{RED:SELLS}", "N/A");
}
}
retval[i] = m + " ";
}
return retval;
}
public static String FormatTime(long Milliseconds)
{ // format time into a string showing hours, minutes, or seconds
if (Milliseconds > 3600000)
{
double val = Math.round((double)Milliseconds / 360000D) / 10D;
return val + " hour" + (val > 1 ? "s" : "");
}
else if (Milliseconds > 60000)
{
double val = Math.round((double)Milliseconds / 6000D) / 10D;
return val + " minute" + (val > 1 ? "s" : "");
}
else if (Milliseconds <= 1000)
return "1 second";
else
return (Milliseconds / 1000L) + " seconds";
}
@SuppressWarnings("LoggerStringConcat")
public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
if (sender instanceof Player)
logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0));
}
@Override
@SuppressWarnings(
{
"LoggerStringConcat", "CallToThreadDumpStack"
})
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
// Allow plugins to override the command via onCommand
for (Plugin p : getServer().getPluginManager().getPlugins())
{
if (p == this)
continue;
PluginDescriptionFile desc = p.getDescription();
if (desc == null)
continue;
if (desc.getName() == null)
continue;
if (!(desc.getCommands() instanceof Map))
continue;
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName()))
continue;
PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel);
if (pcmd == null)
continue;
return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args);
}
try
{
previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? User.get(sender) : null;
// New mail notification
if (user != null && !Essentials.getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail"))
{
List<String> mail = Essentials.readMail(user);
if (!mail.isEmpty()) user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail.");
}
// Check for disabled commands
if (Essentials.getSettings().isCommandDisabled(commandLabel)) return true;
IEssentialsCommand cmd;
try
{
cmd = (IEssentialsCommand)Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command.getName()).newInstance();
}
catch (Exception ex)
{
sender.sendMessage(ChatColor.RED + "That command is improperly loaded.");
ex.printStackTrace();
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd))
{
logger.warning(user.getName() + " was denied access to command.");
user.sendMessage(ChatColor.RED + "You do not have access to that command.");
return true;
}
// Run the command
try
{
if (user == null)
cmd.run(getServer(), this, sender, commandLabel, command, args);
else
cmd.run(getServer(), this, user, commandLabel, command, args);
return true;
}
catch (Throwable ex)
{
sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage());
return true;
}
}
catch (Throwable ex)
{
ex.printStackTrace();
return true;
}
}
public void loadBanList()
{
//I don't like this but it needs to be done until CB fixors
File file = new File("banned-players.txt");
File ipFile = new File("banned-ips.txt");
try
{
if (!file.exists()) throw new FileNotFoundException("banned-players.txt not found");
BufferedReader rx = new BufferedReader(new FileReader(file));
bans.clear();
try
{
for (int i = 0; rx.ready(); i++)
{
String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue;
bans.add(line);
}
}
catch (IOException io)
{
logger.log(Level.SEVERE, "Error reading banned-players.txt", io);
}
}
catch (FileNotFoundException ex)
{
logger.log(Level.SEVERE, "Error reading banned-players.txt", ex);
}
try
{
if (!ipFile.exists()) throw new FileNotFoundException("banned-ips.txt not found");
BufferedReader rx = new BufferedReader(new FileReader(ipFile));
bannedIps.clear();
try
{
for (int i = 0; rx.ready(); i++)
{
String line = rx.readLine().trim().toLowerCase();
if (line.startsWith("#")) continue;
bannedIps.add(line);
}
}
catch (IOException io)
{
logger.log(Level.SEVERE, "Error reading banned-ips.txt", io);
}
}
catch (FileNotFoundException ex)
{
logger.log(Level.SEVERE, "Error reading banned-ips.txt", ex);
}
}
private void attachEcoListeners()
{
PluginManager pm = getServer().getPluginManager();
EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener();
EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener();
pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this);
pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this);
pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this);
}
public CraftScheduler getScheduler()
{
return (CraftScheduler)this.getServer().getScheduler();
}
public static Jail getJail()
{
return getStatic().jail;
}
public static Warps getWarps()
{
return getStatic().warps;
}
}
|