Merge branch '2.x' into final_mute_reason_issue#385

This commit is contained in:
md678685 2019-03-15 11:52:50 +00:00
commit f5c21d1089
234 changed files with 30712 additions and 7570 deletions

View File

@ -1,29 +0,0 @@
<!--
Don't put anything inside this block, as it won't be included in the issue.
If you have a question about EssentialsX, it may be more useful to join our
Discord server: https://discord.gg/F7gexAQ
You can ignore the template if suggesting a feature; otherwise, read on:
1. Fill out the template, running the commands either in the console or
as a player. Don't simply put "latest" or we will ignore it.
2. When linking files, do not attach them to the post! Paste them on
https://gist.github.com/, then paste a link to them in the relevant parts
of the template. Avoid using Hastebin or Pastebin, as files are deleted
after a period of time.
3. If you are reporting an issue with lag, please include a timings report.
4. If you are reporting an issue with messages or in-game behaviour, please
include screenshots detailing the problem.
5. Include a description and any other details that may be helpful under
"Details:".
6. Delete this line and all above lines before posting your issue. -->
EssentialsX version (run `/essentials`):
Server software (run `/version`):
Server (`logs/latest.log`):
EssentialsX config (`plugins/Essentials/config.yml`):
Details:

45
.github/ISSUE_TEMPLATE/help.md vendored Normal file
View File

@ -0,0 +1,45 @@
---
name: Help!
about: Encountered a problem with EssentialsX? Not sure how to fix it?
---
<!-- EssentialsX help guide
Don't write inside the arrows as they will be hidden when you post your issue.
Want faster support? Come join our Discord server to get help sooner:
https://discord.gg/F7gexAQ
If you're happy to wait (or you were sent here from Discord), read on:
1. Fill out the template.
This will help us understand what problem you've encountered and help us
find a solution.
2. Check the Common Issues page.
Read through the wiki page to see if you've encountered a regular issue:
https://essentialsx.github.io/#/Common-Issues
3. Delete this line and all above lines before posting your issue! -->
### Information
Full output of `/ess version`:
<!-- Replace this with the command output -->
**Server log:** <!-- Upload `logs/latest.log` to https://gist.github.com/ -->
**EssentialsX config** <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/ -->
### Help request
**Problem**
<!-- What problem did you encounter? -->
**What I have tried**
<!-- What have you tried so far? -->
**Screenshots**
<!-- If relevant, include any screenshots here. -->

58
.github/ISSUE_TEMPLATE/report-a-bug.md vendored Normal file
View File

@ -0,0 +1,58 @@
---
name: Report a bug
about: Report an EssentialsX bug. Only use this if you're 100% sure there's something wrong with EssentialsX - otherwise, try "Help!".
---
<!-- EssentialsX bug reporting guide
Don't put anything inside this block, as it won't be included in the issue.
If you are reporting a bug, please follow the following steps:
1. Fill out the template in full.
Run the commands in the console. Don't just put "latest" as a version,
or we will ignore it.
2. When linking files, do not attach them to the post!
Copy and paste any logs into https://gist.github.com/, then paste a
link to them in the relevant parts of the template. Avoid using
Hastebin or Pastebin, as this makes providing support more difficult.
**DO NOT drag files into this box!**
3. If you are reporting a performance issue, please include a link to a
Timings and/or profiler report.
4. If you are reporting a bug with commands or something else in-game,
please include screenshots to help us diagnose the problem.
5. Make sure not to write between the arrows, as anything there will be
hidden.
6. Delete this line and all above lines before posting your issue! -->
### Information
**Full output of `/ess version`**:
```
<!-- Run the command in your console, and copy and paste the whole output here -->
```
**Server log**: <!-- Upload `logs/latest.log` to https://gist.github.com/, replace this with link -->
**EssentialsX config**: <!-- Upload `plugins/Essentials/config.yml` to https://gist.github.com/, replace this with link -->
### Details
**Description**
<!-- Replace this with a brief summary of the bug. -->
**Steps to reproduce**
<!-- Replace this with exactly what you did to cause the bug. -->
**Expected behavior**
<!-- Replace this with what you expected to happen. -->
**Screenshots**
<!-- Replace this with screenshots, if necessary. -->

View File

@ -0,0 +1,45 @@
---
name: Request a feature
about: Suggest a feature you want to see in EssentialsX!
---
<!-- EssentialsX feature request guide
Fill out the template. Don't write inside the arrows as they will be hidden
when you post your issue.
Not sure if your feature fits in EssentialsX? Feel free to ask on our Discord
server: https://discord.gg/F7gexAQ
If you have a feature suggestion for EssentialsX, read the following tips:
1. Fill out the template.
This will help us understand what you're requesting and why you want us
to add it.
2. Keep it simple.
Make sure it's easy to understand what you're requesting. A good way is
to keep it to one request per GitHub issue, as we can then easily track
feature requests.
3. Check whether it has already been asked or added.
You can search the issue tracker to see if your feature has already been
requested at https://github.com/EssentialsX/Essentials/issues. You can
also check the wiki at https://essentialsx.github.io/ to see if the
feature was recently added.
4. Ask yourself: "Does this belong in EssentialsX?"
There are lots of features that we reject because most servers won't
need or use them. If your feature is very specific or already exists in
another plugin, it might not be a good fit for EssentialsX.
5. Delete this line and all above lines before posting your issue! -->
### Feature request
**Feature description**
<!-- What feature are you suggesting? -->
**How the feature is useful**
<!-- How is the feature useful to players, server owners and/or developers? -->

70
.gitignore vendored
View File

@ -1,52 +1,18 @@
.DS_Store
/BuildAll/nbproject/private/
/EssentialsProtect/nbproject/private/
/EssentialsChat/nbproject/private/
/EssentialsGroupBridge/nbproject/private/
/EssentialsGeoIP/nbproject/private/
/EssentialsSpawn/nbproject/private/
/EssentialsXMPP/nbproject/private/
/BuildAll/build/
/EssentialsGroupBridge/dist/
/EssentialsGroupBridge/build/
/EssentialsGeoIP/dist/
/EssentialsGeoIP/build/
/BuildAll/dist/
/EssentialsChat/build/
/EssentialsChat/dist/
/EssentialsSpawn/build/
/EssentialsSpawn/dist/
/EssentialsXMPP/dist/
/EssentialsXMPP/build/
/EssentialsProtect/dist/
/EssentialsProtect/build/
/EssentialsPermissionsCommands/nbproject/private/
/EssentialsPermissionsCommands/build/
/EssentialsPermissionsCommands/dist/
/Essentials/nbproject/private/
/Essentials/dist/
/Essentials/build/
/YamlAnnotations/
/EssentialsUpdate/nbproject/private/
/EssentialsRelease/
/EssentialsUpdate/dist/
/EssentialsUpdate/build/
/WebPush/apikey.php
/WebPush/nbproject/private
/EssentialsAntiBuild/nbproject/private/
/EssentialsAntiBuild/dist/
/EssentialsAntiBuild/build/
/jars
/out
.idea/
*.iml
*.classpath
*.project
*.settings/
target/
dependency-reduced-pom.xml
/Essentials/config.yml
/Essentials/userdata/testplayer1.yml
/Essentials/usermap.csv
/Essentials/userdata
/EssentialsGroupManager/target/
# IDE files
*.classpath
*.project
*.settings/
.idea/
*.iml
.DS_Store
# Essentials files
/Essentials/userdata
/Essentials/config.yml
/Essentials/kits.yml
/Essentials/userdata/testplayer1.yml
/Essentials/usermap.csv
# Build files
target/
jars/

10
.travis.yml Normal file
View File

@ -0,0 +1,10 @@
language: java
cache:
directories:
- .buildtools
- $HOME/.m2
before_install:
- chmod +x scripts/buildtools.sh
- scripts/buildtools.sh

View File

@ -6,24 +6,18 @@
<parent>
<groupId>net.ess3</groupId>
<artifactId>EssentialsXParent</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
</parent>
<artifactId>EssentialsX</artifactId>
<licenses>
<license>
<name>GPLv3</name>
<url>http://www.gnu.org/copyleft/gpl.html</url>
</license>
</licenses>
<build>
<finalName>EssentialsX-${full.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.8.0</version>
<configuration>
<showDeprecation>false</showDeprecation>
</configuration>
@ -31,7 +25,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
@ -40,61 +34,48 @@
</goals>
</execution>
</executions>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>com.earth2me.essentials.paperlib</shadedPattern>
</relocation>
</relocations>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>BOSEconomy</groupId>
<artifactId>BOSEconomy</artifactId>
<version>v0.7.8.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/BOSEconomy.jar</systemPath>
</dependency>
<dependency>
<groupId>iConomy</groupId>
<artifactId>iConomy5</artifactId>
<version>5</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/iCo5.jar</systemPath>
</dependency>
<dependency>
<groupId>iConomy</groupId>
<artifactId>iConomy6</artifactId>
<version>6</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/iCo6.jar</systemPath>
</dependency>
<dependency>
<groupId>MultiCurrency</groupId>
<artifactId>MultiCurrency</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/MultiCurrency.jar</systemPath>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>1.5.6</version>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>NMSProvider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>UpdatedMetaProvider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8_R1Provider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@ -106,7 +87,7 @@
<dependency>
<groupId>net.ess3</groupId>
<artifactId>1_8_R2Provider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
@ -118,26 +99,20 @@
<dependency>
<groupId>net.ess3</groupId>
<artifactId>LegacyProvider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>ReflectionProvider</artifactId>
<version>2.0.1</version>
<version>2.16.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.ess3</groupId>
<artifactId>FlattenedProvider</artifactId>
<version>2.16.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
</repositories>
</project>

View File

@ -1,6 +1,6 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import java.util.HashMap;
@ -13,6 +13,7 @@ import java.util.Set;
public class Enchantments {
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
private static final Map<String, Enchantment> ALIASENCHANTMENTS = new HashMap<String, Enchantment>();
private static boolean isFlat;
static {
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
@ -197,14 +198,57 @@ public class Enchantments {
ALIASENCHANTMENTS.put("sweeping", sweeping);
}
} catch (IllegalArgumentException ignored) {}
try { // 1.13
Enchantment loyalty = Enchantment.getByName("LOYALTY");
if (loyalty != null) {
ENCHANTMENTS.put("loyalty", loyalty);
ALIASENCHANTMENTS.put("loyal", loyalty);
ALIASENCHANTMENTS.put("return", loyalty);
}
Enchantment impaling = Enchantment.getByName("IMPALING");
if (impaling != null) {
ENCHANTMENTS.put("impaling", impaling);
ALIASENCHANTMENTS.put("impale", impaling);
ALIASENCHANTMENTS.put("oceandamage", impaling);
ALIASENCHANTMENTS.put("oceandmg", impaling);
}
Enchantment riptide = Enchantment.getByName("RIPTIDE");
if (riptide != null) {
ENCHANTMENTS.put("riptide", riptide);
ALIASENCHANTMENTS.put("rip", riptide);
ALIASENCHANTMENTS.put("tide", riptide);
ALIASENCHANTMENTS.put("launch", riptide);
}
Enchantment channelling = Enchantment.getByName("CHANNELING");
if (channelling != null) {
ENCHANTMENTS.put("channelling", channelling);
ALIASENCHANTMENTS.put("chanelling", channelling);
ALIASENCHANTMENTS.put("channeling", channelling);
ALIASENCHANTMENTS.put("chaneling", channelling);
ALIASENCHANTMENTS.put("channel", channelling);
}
} catch (IllegalArgumentException ignored) {}
try {
Class<?> namespacedKeyClass = Class.forName("org.bukkit.NamespacedKey");
Class<?> enchantmentClass = Class.forName("org.bukkit.enchantments.Enchantment");
enchantmentClass.getDeclaredMethod("getByKey", namespacedKeyClass);
isFlat = true;
} catch (ClassNotFoundException | NoSuchMethodException e) {
isFlat = false;
}
}
public static Enchantment getByName(String name) {
Enchantment enchantment;
if (NumberUtil.isInt(name)) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
Enchantment enchantment = null;
if (isFlat) { // 1.13+ only
enchantment = Enchantment.getByKey(NamespacedKey.minecraft(name.toLowerCase()));
}
if (enchantment == null) {
enchantment = Enchantment.getByName(name.toUpperCase());
}
if (enchantment == null) {
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));

View File

@ -18,6 +18,9 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.*;
import com.earth2me.essentials.items.AbstractItemDb;
import com.earth2me.essentials.items.FlatItemDb;
import com.earth2me.essentials.items.LegacyItemDb;
import com.earth2me.essentials.metrics.Metrics;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
@ -28,6 +31,7 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
@ -37,17 +41,17 @@ import net.ess3.api.ISettings;
import net.ess3.nms.PotionMetaProvider;
import net.ess3.nms.SpawnEggProvider;
import net.ess3.nms.SpawnerProvider;
import net.ess3.nms.flattened.FlatSpawnEggProvider;
import net.ess3.nms.legacy.LegacyPotionMetaProvider;
import net.ess3.nms.legacy.LegacySpawnEggProvider;
import net.ess3.nms.legacy.LegacySpawnerProvider;
import net.ess3.nms.refl.ReflSpawnEggProvider;
import net.ess3.nms.updatedmeta.BasePotionDataProvider;
import net.ess3.nms.updatedmeta.BlockMetaSpawnerProvider;
import net.ess3.nms.legacy.LegacySpawnEggProvider;
import net.ess3.nms.legacy.LegacySpawnerProvider;
import net.ess3.nms.v1_8_R1.v1_8_R1SpawnerProvider;
import net.ess3.nms.v1_8_R2.v1_8_R2SpawnerProvider;
import net.ess3.providers.ProviderFactory;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
@ -60,19 +64,19 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -92,7 +96,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient Worth worth;
private transient List<IConf> confList;
private transient Backup backup;
private transient ItemDb itemDb;
private transient AbstractItemDb itemDb;
private transient final Methods paymentMethod = new Methods();
private transient PermissionsHandler permissionsHandler;
private transient AlternativeCommandsHandler alternativeCommandsHandler;
@ -101,11 +105,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient I18n i18n;
private transient Metrics metrics;
private transient EssentialsTimer timer;
private final transient List<String> vanishedPlayers = new ArrayList<>();
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private transient Method oldGetOnlinePlayers;
private transient SpawnerProvider spawnerProvider;
private transient SpawnEggProvider spawnEggProvider;
private transient PotionMetaProvider potionMetaProvider;
private transient Kits kits;
public Essentials() {
}
@ -150,6 +155,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
confList = new ArrayList<>();
jails = new Jails(this);
registerListeners(server.getPluginManager());
kits = new Kits(this);
}
@Override
@ -166,6 +172,10 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
Console.setInstance(this);
if (!VersionUtil.isServerSupported()) {
getLogger().severe(tl("serverUnsupported"));
}
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins()) {
if (plugin.getDescription().getName().startsWith("Essentials") && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) {
@ -186,25 +196,38 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
kits = new Kits(this);
confList.add(kits);
upgrade.convertKits();
execTimer.mark("Kits");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
itemDb = getItemDbFromConfig();
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
jails = new Jails(this);
confList.add(jails);
execTimer.mark("Init(Jails)");
spawnerProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
BlockMetaSpawnerProvider.class,
@ -214,6 +237,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
), "mob spawner").getProvider();
spawnEggProvider = new ProviderFactory<>(getLogger(),
Arrays.asList(
FlatSpawnEggProvider.class,
ReflSpawnEggProvider.class,
LegacySpawnEggProvider.class
), "spawn egg").getProvider();
@ -222,7 +246,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
BasePotionDataProvider.class,
LegacyPotionMetaProvider.class
), "potion meta").getProvider();
execTimer.mark("Init(Providers)");
reload();
// The item spawn blacklist is loaded with all other settings, before the item
// DB, but it depends on the item DB, so we need to reload it again here:
((Settings) settings)._lateLoadItemSpawnBlacklist();
} catch (YAMLException exception) {
if (pm.getPlugin("EssentialsUpdate") != null) {
LOGGER.log(Level.SEVERE, tl("essentialsHelp2"));
@ -242,8 +271,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
Economy.setEss(this);
execTimer.mark("RegHandler");
for (World w : Bukkit.getWorlds())
addDefaultBackPermissionsToWorld(w);
metrics = new Metrics(this);
if (!metrics.isOptOut()) {
if (metrics.isEnabled()) {
getLogger().info("Starting Metrics. Opt-out using the global bStats config.");
} else {
getLogger().info("Metrics disabled per bStats config.");
@ -437,7 +469,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return pc.execute(cSender, commandLabel, args);
} catch (final Exception ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
cSender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
cSender.sendMessage(tl("internalError"));
return true;
}
}
@ -585,6 +617,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return backup;
}
@Override
public Kits getKits() {
return kits;
}
@Override
public Metrics getMetrics() {
return metrics;
@ -809,6 +846,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override
public List<String> getVanishedPlayers() {
return Collections.unmodifiableList(new ArrayList<>(vanishedPlayers));
}
@Override
public Collection<String> getVanishedPlayersNew() {
return vanishedPlayers;
}
@ -853,6 +895,18 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return potionMetaProvider;
}
private static void addDefaultBackPermissionsToWorld(World w) {
String permName = "essentials.back.into." + w.getName();
Permission p = Bukkit.getPluginManager().getPermission(permName);
if (p == null) {
p = new Permission(permName,
"Allows access to /back when the destination location is within world " + w.getName(),
PermissionDefault.TRUE);
Bukkit.getPluginManager().addPermission(p);
}
}
private static class EssentialsWorldListener implements Listener, Runnable {
private transient final IEssentials ess;
@ -862,6 +916,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@EventHandler(priority = EventPriority.LOW)
public void onWorldLoad(final WorldLoadEvent event) {
addDefaultBackPermissionsToWorld(event.getWorld());
ess.getJails().onReload();
ess.getWarps().reloadConfig();
for (IConf iConf : ((Essentials) ess).confList) {
@ -887,4 +943,22 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
ess.reload();
}
}
private AbstractItemDb getItemDbFromConfig() {
final String setting = settings.getItemDbType();
if (setting.equalsIgnoreCase("json")) {
return new FlatItemDb(this);
} else if (setting.equalsIgnoreCase("csv")) {
return new LegacyItemDb(this);
} else {
VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion();
if (version.isHigherThanOrEqualTo(VersionUtil.v1_13_0_R01)) {
return new FlatItemDb(this);
} else {
return new LegacyItemDb(this);
}
}
}
}

View File

@ -1,6 +1,8 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import net.ess3.api.IEssentials;
import org.bukkit.GameMode;
import org.bukkit.Material;
@ -28,11 +30,12 @@ public class EssentialsBlockListener implements Listener {
// Do not rely on getItemInHand();
// http://leaky.bukkit.org/issues/663
final ItemStack is = LocationUtil.convertBlockToItem(event.getBlockPlaced());
if (is == null) {
return;
}
if (is.getType() == Material.MOB_SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == Material.MOB_SPAWNER) {
if (is.getType() == MaterialUtil.SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == MaterialUtil.SPAWNER) {
final BlockState blockState = event.getBlockPlaced().getState();
if (blockState instanceof CreatureSpawner) {
final CreatureSpawner spawner = (CreatureSpawner) blockState;

View File

@ -47,7 +47,7 @@ public class EssentialsEntityListener implements Listener {
event.setCancelled(true);
}
}
attacker.updateActivity(true);
attacker.updateActivityOnInteract(true);
} else if (eAttack instanceof Projectile && eDefend instanceof Player) {
final Projectile projectile = (Projectile) event.getDamager();
//This should return a ProjectileSource on 1.7.3 beta +
@ -55,7 +55,7 @@ public class EssentialsEntityListener implements Listener {
if (shooter instanceof Player) {
final User attacker = ess.getUser((Player) shooter);
onPlayerVsPlayerDamage(event, (Player) eDefend, attacker);
attacker.updateActivity(true);
attacker.updateActivityOnInteract(true);
}
}
}
@ -124,7 +124,7 @@ public class EssentialsEntityListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityCombustByEntity(final EntityCombustByEntityEvent event) {
if (event.getCombuster() instanceof Arrow) {
if (event.getCombuster() instanceof Arrow && event.getEntity() instanceof Player) {
Arrow combuster = (Arrow) event.getCombuster();
if (combuster.getShooter() instanceof Player) {
final User srcCombuster = ess.getUser(((Player) combuster.getShooter()).getUniqueId());
@ -194,7 +194,17 @@ public class EssentialsEntityListener implements Listener {
if (event.getEntity() instanceof Player) {
final User user = ess.getUser((Player) event.getEntity());
if (user.isAfk()) {
user.updateActivity(true);
user.updateActivityOnInteract(true);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityTarget(EntityTargetEvent event) {
if (event.getTarget() instanceof Player) {
final User user = ess.getUser((Player) event.getTarget());
if (user.isVanished()) {
event.setCancelled(true);
}
}
}

View File

@ -6,14 +6,16 @@ import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.BanEntry;
import org.bukkit.BanList;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
@ -57,10 +59,10 @@ public class EssentialsPlayerListener implements Listener {
public void registerEvents() {
ess.getServer().getPluginManager().registerEvents(this, ess);
if (ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_12_R1)) {
ess.getServer().getPluginManager().registerEvents(new PlayerListenerPre1_12(), ess);
} else {
if (isEntityPickupEvent()) {
ess.getServer().getPluginManager().registerEvents(new PlayerListener1_12(), ess);
} else {
ess.getServer().getPluginManager().registerEvents(new PlayerListenerPre1_12(), ess);
}
}
@ -101,7 +103,7 @@ public class EssentialsPlayerListener implements Listener {
}
}
user.updateActivity(true);
user.updateActivityOnInteract(true);
user.setDisplayNick();
}
@ -126,8 +128,8 @@ public class EssentialsPlayerListener implements Listener {
final Location from = event.getFrom();
final Location origTo = event.getTo();
final Location to = origTo.clone();
if (ess.getSettings().cancelAfkOnMove() && origTo.getY() >= from.getBlockY() + 1) {
user.updateActivity(true);
if (origTo.getY() >= from.getBlockY() + 1) {
user.updateActivityOnMove(true);
return;
}
to.setX(from.getX());
@ -142,7 +144,7 @@ public class EssentialsPlayerListener implements Listener {
}
final Location afk = user.getAfkPosition();
if (afk == null || !event.getTo().getWorld().equals(afk.getWorld()) || afk.distanceSquared(event.getTo()) > 9) {
user.updateActivity(true);
user.updateActivityOnMove(true);
}
}
@ -154,7 +156,12 @@ public class EssentialsPlayerListener implements Listener {
event.setQuitMessage(null);
} else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) {
final Player player = event.getPlayer();
event.setQuitMessage(ess.getSettings().getCustomQuitMessage().replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName()));
final String msg = ess.getSettings().getCustomQuitMessage()
.replace("{PLAYER}", player.getDisplayName())
.replace("{USERNAME}", player.getName())
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()));
event.setQuitMessage(msg.isEmpty() ? null : msg);
}
user.startTransaction();
@ -178,7 +185,7 @@ public class EssentialsPlayerListener implements Listener {
}
}
user.updateActivity(false);
user.updateActivityOnInteract(false);
if (!user.isHidden()) {
user.setLastLogout(System.currentTimeMillis());
}
@ -216,7 +223,7 @@ public class EssentialsPlayerListener implements Listener {
final long currentTime = System.currentTimeMillis();
dUser.checkMuteTimeout(currentTime);
dUser.updateActivity(false);
dUser.updateActivityOnInteract(false);
dUser.stopTransaction();
class DelayJoinTask implements Runnable {
@ -235,11 +242,14 @@ public class EssentialsPlayerListener implements Listener {
user.setDisplayNick();
updateCompass(user);
if (!ess.getVanishedPlayers().isEmpty() && !user.isAuthorized("essentials.vanish.see")) {
for (String p : ess.getVanishedPlayers()) {
if (!ess.getVanishedPlayersNew().isEmpty() && !user.isAuthorized("essentials.vanish.see")) {
for (String p : ess.getVanishedPlayersNew()) {
Player toVanish = ess.getServer().getPlayerExact(p);
if (toVanish != null && toVanish.isOnline()) {
user.getBase().hidePlayer(toVanish);
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Hiding vanished player: " + p);
}
}
}
}
@ -257,8 +267,11 @@ public class EssentialsPlayerListener implements Listener {
} else if (ess.getSettings().isCustomJoinMessage()) {
String msg = ess.getSettings().getCustomJoinMessage()
.replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())
.replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers()));
ess.getServer().broadcastMessage(msg);
.replace("{UNIQUE}", NumberFormat.getInstance().format(ess.getUserMap().getUniqueUsers()))
.replace("{ONLINE}", NumberFormat.getInstance().format(ess.getOnlinePlayers().size()));
if (!msg.isEmpty()) {
ess.getServer().broadcastMessage(msg);
}
} else if (ess.getSettings().allowSilentJoinQuit()) {
ess.getServer().broadcastMessage(message);
}
@ -307,6 +320,9 @@ public class EssentialsPlayerListener implements Listener {
user.setGodModeEnabled(false);
ess.getLogger().log(Level.INFO, "Set god mode to false for {0} because they had it enabled without permission.", user.getName());
}
user.setConfirmingClearCommand(null);
user.getConfirmingPayments().clear();
user.stopTransaction();
}
@ -336,7 +352,7 @@ public class EssentialsPlayerListener implements Listener {
final IText input = tempInput;
if (input != null && user.isAuthorized("essentials.motd")) {
if (input != null && !input.getLines().isEmpty() && user.isAuthorized("essentials.motd")) {
final IText output = new KeywordReplacer(input, user.getSource(), ess);
final TextPager pager = new TextPager(output, true);
pager.showPage("1", null, "motd", user.getSource());
@ -349,7 +365,10 @@ public class EssentialsPlayerListener implements Listener {
}
// Makes the compass item ingame always point to the first essentials home. #EasterEgg
// EssentialsX: This can now optionally require a permission to enable, if set in the config.
private void updateCompass(final User user) {
if (ess.getSettings().isCompassTowardsHomePerm() && !user.isAuthorized("essentials.home.compass")) return;
Location loc = user.getHome(user.getLocation());
if (loc == null) {
loc = user.getBase().getBedSpawnLocation();
@ -456,8 +475,7 @@ public class EssentialsPlayerListener implements Listener {
if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) {
if (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers()) {
spyer.sendMessage(tl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage());
}
else {
} else {
spyer.sendMessage(tl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage());
}
}
@ -487,7 +505,7 @@ public class EssentialsPlayerListener implements Listener {
}
final User user = ess.getUser(player);
if (update) {
user.updateActivity(broadcast);
user.updateActivityOnInteract(broadcast);
}
if (ess.getSettings().isCommandCooldownsEnabled() && pluginCommand != null
@ -585,9 +603,9 @@ public class EssentialsPlayerListener implements Listener {
public void onPlayerInteract(final PlayerInteractEvent event) {
switch (event.getAction()) {
case RIGHT_CLICK_BLOCK:
if (!event.isCancelled() && event.getClickedBlock().getType() == Material.BED_BLOCK && ess.getSettings().getUpdateBedAtDaytime()) {
if (!event.isCancelled() && MaterialUtil.isBed(event.getClickedBlock().getType()) && ess.getSettings().getUpdateBedAtDaytime()) {
User player = ess.getUser(event.getPlayer());
if (player.isAuthorized("essentials.sethome.bed")) {
if (player.isAuthorized("essentials.sethome.bed") && player.getWorld().getEnvironment().equals(World.Environment.NORMAL)) {
player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation());
player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()));
}
@ -604,13 +622,13 @@ public class EssentialsPlayerListener implements Listener {
case LEFT_CLICK_BLOCK:
if (event.getItem() != null && event.getItem().getType() != Material.AIR) {
final User user = ess.getUser(event.getPlayer());
if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getTypeId())) {
if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getType())) {
event.setCancelled(true);
}
}
break;
}
ess.getUser(event.getPlayer()).updateActivity(true);
ess.getUser(event.getPlayer()).updateActivityOnInteract(true);
}
// This method allows the /jump lock feature to work, allows teleporting while flying #EasterEgg
@ -627,7 +645,7 @@ public class EssentialsPlayerListener implements Listener {
while (LocationUtil.isBlockDamaging(loc.getWorld(), loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())) {
loc.setY(loc.getY() + 1d);
}
user.getBase().teleport(loc, TeleportCause.PLUGIN);
PaperLib.teleportAsync(user.getBase(), loc, TeleportCause.PLUGIN);
}
}
ess.scheduleSyncDelayedTask(new DelayedClickJumpTask());
@ -638,8 +656,8 @@ public class EssentialsPlayerListener implements Listener {
}
}
private boolean usePowertools(final User user, final int id) {
final List<String> commandList = user.getPowertool(id);
private boolean usePowertools(final User user, final Material material) {
final List<String> commandList = user.getPowertool(material);
if (commandList == null || commandList.isEmpty()) {
return false;
}
@ -713,6 +731,7 @@ public class EssentialsPlayerListener implements Listener {
} else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER) {
if (ess.getSettings().isDirectHatAllowed() && event.getClick() == ClickType.LEFT && event.getSlot() == 39
&& event.getCursor().getType() != Material.AIR && event.getCursor().getType().getMaxDurability() == 0
&& !MaterialUtil.isSkull(event.getCursor().getType())
&& ess.getUser(event.getWhoClicked()).isAuthorized("essentials.hat")) {
event.setCancelled(true);
final PlayerInventory inv = (PlayerInventory) clickedInventory;
@ -776,9 +795,18 @@ public class EssentialsPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerFishEvent(final PlayerFishEvent event) {
final User user = ess.getUser(event.getPlayer());
user.updateActivity(true);
user.updateActivityOnInteract(true);
}
private static boolean isEntityPickupEvent() {
try {
Class.forName("org.bukkit.event.entity.EntityPickupItemEvent");
return true;
} catch (ClassNotFoundException ignored) {
return false;
}
}
private final class PlayerListenerPre1_12 implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
@ -790,7 +818,7 @@ public class EssentialsPlayerListener implements Listener {
}
}
}
private final class PlayerListener1_12 implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)

View File

@ -10,12 +10,17 @@ import org.bukkit.event.server.ServerListPingEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
public class EssentialsServerListener implements Listener {
private static List<String> ignoredSLPECallers = Arrays.asList(
".LegacyPingHandler.channelRead(" // CB responding to pings from pre-Netty clients
);
private final transient IEssentials ess;
private boolean unsupportedLogged = false;
private boolean npeWarned = false;
@ -25,15 +30,20 @@ public class EssentialsServerListener implements Listener {
public EssentialsServerListener(final IEssentials ess) {
this.ess = ess;
setSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "setSampleText", List.class);
getSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "getSampleText");
if (setSampleText != null && getSampleText != null) {
ess.getLogger().info("Using Paper 1.12+ ServerListPingEvent methods");
isPaperSample = true;
} else {
ess.getLogger().info("Using Spigot 1.7.10+ ServerListPingEvent iterator");
isPaperSample = false;
if (ReflUtil.getClassCached("com.destroystokyo.paper.event.server.PaperServerListPingEvent") == null) {
// This workaround is only necessary for older Paper builds
setSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "setSampleText", List.class);
getSampleText = ReflUtil.getMethodCached(ServerListPingEvent.class, "getSampleText");
if (setSampleText != null && getSampleText != null) {
ess.getLogger().info("ServerListPingEvent: Paper 1.12.2 setSampleText API");
isPaperSample = true;
return;
}
}
ess.getLogger().info("ServerListPingEvent: Spigot iterator API");
isPaperSample = false;
}
@EventHandler(priority = EventPriority.LOWEST)
@ -41,22 +51,16 @@ public class EssentialsServerListener implements Listener {
if (isPaperSample) {
try {
List<String> playerNames = (List<String>) getSampleText.invoke(event, null);
Iterator<String> iterator = playerNames.iterator();
while (iterator.hasNext()) {
String player = iterator.next();
if (ess.getUser(player).isVanished()) {
iterator.remove();
}
}
playerNames.removeIf(player -> ess.getUser(player).isVanished());
setSampleText.invoke(event, playerNames);
} catch (IllegalAccessException | InvocationTargetException | ClassCastException e) {
if (!unsupportedLogged) {
if (!unsupportedLogged && shouldWarnSLPECaller(e)) {
ess.getLogger().log(Level.WARNING, "Unable to hide players from server list ping "
+ "using Paper 1.12+ method!", e);
+ "using Paper 1.12 method!", e);
unsupportedLogged = true;
}
} catch (NullPointerException e) {
if (!npeWarned) {
if (!npeWarned && shouldWarnSLPECaller(e)) {
npeWarned = true;
Exception ex = new Exception("A plugin has fired a ServerListPingEvent "
+ "without implementing Paper's methods. Point the author to https://git.io/v7Xzl.");
@ -74,12 +78,38 @@ public class EssentialsServerListener implements Listener {
}
}
} catch (UnsupportedOperationException e) {
if (!unsupportedLogged) {
ess.getLogger().warning("Current server implementation does not support "
+ "hiding players from server list ping. Update or contact the maintainers.");
if (!unsupportedLogged && shouldWarnSLPECaller(e)) {
ess.getLogger().log(Level.WARNING, "Could not hide vanished players while handling " + event.getClass().getName(), e);
unsupportedLogged = true;
}
}
}
}
/**
* Should we warn about this SLPE caller, or should we silently ignore it?
* This checks against the ignoredSLPECallers strings, and if it matches one of those, we
* return false.
*
* @param throwable A throwable caught by a catch block
* @return Whether or not to send a warning about this particular caller
*/
private boolean shouldWarnSLPECaller(Throwable throwable) {
final int maxStackDepth = 20; // Limit the depth when searching through the stack trace
int depth = 0;
for (StackTraceElement element : throwable.getStackTrace()) {
depth++;
if (depth > maxStackDepth) {
break;
}
for (String ignoredString : ignoredSLPECallers) {
if (element.toString().contains(ignoredString)) {
return false; // We know about this error and should ignore it, so don't warn
}
}
}
return true; // We don't know for certain that we can ignore this, so warn just to be safe
}
}

View File

@ -12,6 +12,7 @@ import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import java.io.*;
import java.math.BigInteger;
@ -41,6 +42,34 @@ public class EssentialsUpgrade {
doneFile.load();
}
public void convertKits() {
Kits kits = ess.getKits();
EssentialsConf config = kits.getConfig();
if (doneFile.getBoolean("kitsyml", false)) {
return;
}
LOGGER.info("Attempting to convert old kits in config.yml to new kits.yml");
ConfigurationSection section = ess.getSettings().getKitSection();
if (section == null) {
LOGGER.info("No kits found to migrate.");
return;
}
Map<String, Object> legacyKits = ess.getSettings().getKitSection().getValues(true);
for (Map.Entry<String, Object> entry : legacyKits.entrySet()) {
LOGGER.info("Converting " + entry.getKey());
config.set("kits." + entry.getKey(), entry.getValue());
}
config.save();
doneFile.setProperty("kitsyml", true);
doneFile.save();
LOGGER.info("Done converting kits.");
}
private void moveMotdRulesToFile(String name) {
if (doneFile.getBoolean("move" + name + "ToFile", false)) {
return;

View File

@ -93,7 +93,7 @@ public class I18n implements net.ess3.api.II18n {
}
messageFormatCache.put(format, messageFormat);
}
return messageFormat.format(objects);
return messageFormat.format(objects).replace(' ', ' '); // replace nbsp with a space
}
public void updateLocale(final String loc) {

View File

@ -19,7 +19,6 @@ import java.util.Collection;
import java.util.List;
import java.util.UUID;
public interface IEssentials extends Plugin {
void addReloadListener(IConf listener);
@ -62,6 +61,8 @@ public interface IEssentials extends Plugin {
Backup getBackup();
Kits getKits();
Methods getPaymentMethod();
BukkitTask runTaskAsynchronously(Runnable run);
@ -94,6 +95,7 @@ public interface IEssentials extends Plugin {
EssentialsTimer getTimer();
@Deprecated
List<String> getVanishedPlayers();
Collection<Player> getOnlinePlayers();

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.textreader.IText;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventPriority;
@ -58,12 +59,27 @@ public interface ISettings extends IConf {
Set<String> getMuteCommands();
Map<String, Object> getKit(String name);
/**
* @Deprecated in favor of {@link Kits#getKits()}
*/
@Deprecated
ConfigurationSection getKits();
/**
* @Deprecated in favor of {@link Kits#getKit(String)}
*/
@Deprecated
Map<String, Object> getKit(String kit);
/**
* @Deprecated in favor of {@link Kits#addKit(String, List, long)}}
*/
@Deprecated
void addKit(String name, List<String> lines, long delay);
@Deprecated
ConfigurationSection getKitSection();
boolean isSkippingUsedOneTimeKitsFromKitList();
String getLocale();
@ -80,7 +96,7 @@ public interface ISettings extends IConf {
int getProtectCreeperMaxHeight();
List<Integer> getProtectList(final String configName);
List<Material> getProtectList(final String configName);
boolean getProtectPreventSpawn(final String creatureName);
@ -118,9 +134,12 @@ public interface ISettings extends IConf {
boolean isEcoDisabled();
@Deprecated
boolean isTradeInStacks(int id);
List<Integer> itemSpawnBlacklist();
boolean isTradeInStacks(Material type);
List<Material> itemSpawnBlacklist();
List<EssentialsSign> enabledSigns();
@ -166,6 +185,8 @@ public interface ISettings extends IConf {
boolean cancelAfkOnInteract();
boolean sleepIgnoresAfkPlayers();
boolean isAfkListName();
String getAfkListName();
@ -224,6 +245,8 @@ public interface ISettings extends IConf {
boolean ignoreColorsInMaxLength();
boolean hideDisplayNameInVanish();
int getMaxUserCacheCount();
boolean allowSilentJoinQuit();
@ -243,7 +266,7 @@ public interface ISettings extends IConf {
boolean isLastMessageReplyRecipient();
BigDecimal getMinimumPayAmount();
long getLastMessageReplyRecipientTimeout();
boolean isMilkBucketEasterEggEnabled();
@ -255,13 +278,13 @@ public interface ISettings extends IConf {
boolean isSpawnOnJoin();
List<String> getSpawnOnJoinGroups();
boolean isUserInSpawnOnJoinGroup(IUser user);
boolean isTeleportToCenterLocation();
boolean isCommandCooldownsEnabled();
long getCommandCooldownMs(String label);
Entry<Pattern, Long> getCommandCooldownEntry(String label);
@ -273,11 +296,11 @@ public interface ISettings extends IConf {
NumberFormat getCurrencyFormat();
List<EssentialsSign> getUnprotectedSignNames();
boolean isPastebinCreateKit();
boolean isAllowBulkBuySell();
boolean isAddingPrefixInPlayerlist();
boolean isAddingSuffixInPlayerlist();
@ -287,4 +310,18 @@ public interface ISettings extends IConf {
int getMotdDelay();
boolean isDirectHatAllowed();
List<String> getDefaultEnabledConfirmCommands();
boolean isConfirmCommandEnabledByDefault(String commandName);
boolean isCompassTowardsHomePerm();
boolean isAllowWorldInBroadcastworld();
String getItemDbType();
boolean isForceEnableRecipe();
boolean allowOldIdSigns();
}

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.commands.IEssentialsCommand;
import net.ess3.api.ITeleport;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
@ -35,7 +36,7 @@ public interface IUser {
boolean canAfford(BigDecimal value);
Boolean canSpawnItem(final int itemId);
Boolean canSpawnItem(final Material material);
void setLastLocation();

View File

@ -1,472 +0,0 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.nms.refl.ReflUtil;
import net.ess3.nms.updatedmeta.BasePotionDataProvider;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.IEssentials;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.block.Banner;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class ItemDb implements IConf, net.ess3.api.IItemDb {
private final transient IEssentials ess;
private final transient Map<String, Integer> items = new HashMap<>();
private final transient Map<ItemData, List<String>> names = new HashMap<>();
private final transient Map<ItemData, String> primaryName = new HashMap<>();
private final transient Map<String, Short> durabilities = new HashMap<>();
private final transient Map<String, String> nbtData = new HashMap<>();
private final transient ManagedFile file;
private final transient Pattern splitPattern = Pattern.compile("((.*)[:+',;.](\\d+))");
private final transient Pattern csvSplitPattern = Pattern.compile("(\"([^\"]*)\"|[^,]*)(,|$)");
public ItemDb(final IEssentials ess) {
this.ess = ess;
file = new ManagedFile("items.csv", ess);
}
@Override
public void reloadConfig() {
final List<String> lines = file.getLines();
if (lines.isEmpty()) {
return;
}
durabilities.clear();
items.clear();
names.clear();
primaryName.clear();
for (String line : lines) {
if (line.length() > 0 && line.charAt(0) == '#') {
continue;
}
String itemName = null;
int numeric = -1;
short data = 0;
String nbt = null;
int col = 0;
Matcher matcher = csvSplitPattern.matcher(line);
while (matcher.find()) {
String match = matcher.group(1);
if (StringUtils.stripToNull(match) == null) {
continue;
}
match = StringUtils.strip(match.trim(), "\"");
switch (col) {
case 0:
itemName = match.toLowerCase(Locale.ENGLISH);
break;
case 1:
numeric = Integer.parseInt(match);
break;
case 2:
data = Short.parseShort(match);
break;
case 3:
nbt = StringUtils.stripToNull(match);
break;
default:
continue;
}
col++;
}
// Invalid row
if (itemName == null || numeric < 0) {
continue;
}
durabilities.put(itemName, data);
items.put(itemName, numeric);
if (nbt != null) {
nbtData.put(itemName, nbt);
}
ItemData itemData = new ItemData(numeric, data);
if (names.containsKey(itemData)) {
List<String> nameList = names.get(itemData);
nameList.add(itemName);
} else {
List<String> nameList = new ArrayList<>();
nameList.add(itemName);
names.put(itemData, nameList);
primaryName.put(itemData, itemName);
}
}
for (List<String> nameList : names.values()) {
Collections.sort(nameList, LengthCompare.INSTANCE);
}
}
@Override
public ItemStack get(final String id, final int quantity) throws Exception {
final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH));
retval.setAmount(quantity);
return retval;
}
@Override
public ItemStack get(final String id) throws Exception {
int itemid = 0;
String itemname;
short metaData = 0;
Matcher parts = splitPattern.matcher(id);
if (parts.matches()) {
itemname = parts.group(2);
metaData = Short.parseShort(parts.group(3));
} else {
itemname = id;
}
if (NumberUtil.isInt(itemname)) {
itemid = Integer.parseInt(itemname);
} else if (NumberUtil.isInt(id)) {
itemid = Integer.parseInt(id);
} else {
itemname = itemname.toLowerCase(Locale.ENGLISH);
}
if (itemid < 1) {
if (items.containsKey(itemname)) {
itemid = items.get(itemname);
if (durabilities.containsKey(itemname) && metaData == 0) {
metaData = durabilities.get(itemname);
}
} else if (Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)) != null) {
Material bMaterial = Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH));
itemid = bMaterial.getId();
} else {
try {
Material bMaterial = Bukkit.getUnsafe().getMaterialFromInternalName(itemname.toLowerCase(Locale.ENGLISH));
itemid = bMaterial.getId();
} catch (Throwable throwable) {
throw new Exception(tl("unknownItemName", itemname), throwable);
}
}
}
if (itemid < 1) {
throw new Exception(tl("unknownItemName", itemname));
}
final Material mat = Material.getMaterial(itemid);
if (mat == null) {
throw new Exception(tl("unknownItemId", itemid));
}
ItemStack retval = new ItemStack(mat);
if (nbtData.containsKey(itemname)) {
String nbt = nbtData.get(itemname);
if (nbt.startsWith("*")) {
nbt = nbtData.get(nbt.substring(1));
}
retval = ess.getServer().getUnsafe().modifyItemStack(retval, nbt);
}
if (mat == Material.MOB_SPAWNER) {
if (metaData == 0) metaData = EntityType.PIG.getTypeId();
try {
retval = ess.getSpawnerProvider().setEntityType(retval, EntityType.fromId(metaData));
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from mob spawners.");
}
} else if (mat == Material.MONSTER_EGG) {
EntityType type;
try {
type = EntityType.fromId(metaData);
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from spawn eggs.");
}
retval = ess.getSpawnEggProvider().createEggItem(type);
} else if (mat.name().endsWith("POTION")
&& ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_11_R1)) { // Only apply this to pre-1.11 as items.csv might only work in 1.11
retval = ess.getPotionMetaProvider().createPotionItem(mat, metaData);
} else {
retval.setDurability(metaData);
}
retval.setAmount(mat.getMaxStackSize());
return retval;
}
@Override
public List<ItemStack> getMatching(User user, String[] args) throws Exception {
List<ItemStack> is = new ArrayList<>();
if (args.length < 1) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("hand")) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else if (args[0].equalsIgnoreCase("blocks")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else {
is.add(get(args[0]));
}
if (is.isEmpty() || is.get(0).getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
}
return is;
}
@Override
public String names(ItemStack item) {
ItemData itemData = new ItemData(item.getTypeId(), item.getDurability());
List<String> nameList = names.get(itemData);
if (nameList == null) {
itemData = new ItemData(item.getTypeId(), (short) 0);
nameList = names.get(itemData);
if (nameList == null) {
return null;
}
}
if (nameList.size() > 15) {
nameList = nameList.subList(0, 14);
}
return StringUtil.joinList(", ", nameList);
}
@Override
public String name(ItemStack item) {
ItemData itemData = new ItemData(item.getTypeId(), item.getDurability());
String name = primaryName.get(itemData);
if (name == null) {
itemData = new ItemData(item.getTypeId(), (short) 0);
name = primaryName.get(itemData);
if (name == null) {
return null;
}
}
return name;
}
@Override
public String serialize(ItemStack is) {
String mat = is.getType().name();
if (is.getData().getData() != 0) {
mat = mat + ":" + is.getData().getData();
}
int quantity = is.getAmount();
StringBuilder sb = new StringBuilder(); // Add space AFTER you add something. We can trim at end.
sb.append(mat).append(" ").append(quantity).append(" ");
// ItemMeta applies to anything.
if (is.hasItemMeta()) {
ItemMeta meta = is.getItemMeta();
if (meta.hasDisplayName()) {
sb.append("name:").append(meta.getDisplayName().replaceAll(" ", "_")).append(" ");
}
if (meta.hasLore()) {
sb.append("lore:");
boolean first = true;
for (String s : meta.getLore()) {
// Add | before the line if it's not the first one. Easy but weird way
// to do this since we need each line separated by |
if (!first) {
sb.append("|");
}
first = false;
sb.append(s.replaceAll(" ", "_"));
}
sb.append(" ");
}
if (meta.hasEnchants()) {
for (Enchantment e : meta.getEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(meta.getEnchantLevel(e)).append(" ");
}
}
}
switch (is.getType()) {
case WRITTEN_BOOK:
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Books in that order.
// Interesting as I didn't see a way to do pages or chapters.
BookMeta bookMeta = (BookMeta) is.getItemMeta();
if (bookMeta.hasTitle()) {
sb.append("title:").append(bookMeta.getTitle()).append(" ");
}
if (bookMeta.hasAuthor()) {
sb.append("author:").append(bookMeta.getAuthor()).append(" ");
}
// Only other thing it could have is lore but that's done up there ^^^
break;
case ENCHANTED_BOOK:
EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) is.getItemMeta();
for (Enchantment e : enchantmentStorageMeta.getStoredEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(enchantmentStorageMeta.getStoredEnchantLevel(e)).append(" ");
}
break;
case FIREWORK:
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Fireworks in that order.
FireworkMeta fireworkMeta = (FireworkMeta) is.getItemMeta();
if (fireworkMeta.hasEffects()) {
for (FireworkEffect effect : fireworkMeta.getEffects()) {
if (effect.getColors() != null && !effect.getColors().isEmpty()) {
sb.append("color:");
boolean first = true;
for (Color c : effect.getColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
sb.append("shape: ").append(effect.getType().name()).append(" ");
if (effect.getFadeColors() != null && !effect.getFadeColors().isEmpty()) {
sb.append("fade:");
boolean first = true;
for (Color c : effect.getFadeColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
}
sb.append("power: ").append(fireworkMeta.getPower()).append(" ");
}
break;
case POTION:
Potion potion = Potion.fromItemStack(is);
for (PotionEffect e : potion.getEffects()) {
// long but needs to be effect:speed power:2 duration:120 in that order.
sb.append("splash:").append(potion.isSplash()).append(" ").append("effect:").append(e.getType().getName().toLowerCase()).append(" ").append("power:").append(e.getAmplifier()).append(" ").append("duration:").append(e.getDuration() / 20).append(" ");
}
break;
case SKULL_ITEM:
// item stack with meta
SkullMeta skullMeta = (SkullMeta) is.getItemMeta();
if (skullMeta != null && skullMeta.hasOwner()) {
sb.append("player:").append(skullMeta.getOwner()).append(" ");
}
break;
case LEATHER_HELMET:
case LEATHER_CHESTPLATE:
case LEATHER_LEGGINGS:
case LEATHER_BOOTS:
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) is.getItemMeta();
int rgb = leatherArmorMeta.getColor().asRGB();
sb.append("color:").append(rgb).append(" ");
break;
case BANNER:
BannerMeta bannerMeta = (BannerMeta) is.getItemMeta();
if (bannerMeta != null) {
int basecolor = bannerMeta.getBaseColor().getColor().asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
for (org.bukkit.block.banner.Pattern p : bannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
}
break;
case SHIELD:
// Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795
BlockStateMeta shieldMeta = (BlockStateMeta) is.getItemMeta();
Banner shieldBannerMeta = (Banner) shieldMeta.getBlockState();
int basecolor = shieldBannerMeta.getBaseColor().getColor().asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
for (org.bukkit.block.banner.Pattern p : shieldBannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
break;
}
return sb.toString().trim().replaceAll("§", "&");
}
@Override
public Collection<String> listNames() {
return primaryName.values();
}
static class ItemData {
final private int itemNo;
final private short itemData;
ItemData(final int itemNo, final short itemData) {
this.itemNo = itemNo;
this.itemData = itemData;
}
public int getItemNo() {
return itemNo;
}
public short getItemData() {
return itemData;
}
@Override
public int hashCode() {
return (31 * itemNo) ^ itemData;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof ItemData)) {
return false;
}
ItemData pairo = (ItemData) o;
return this.itemNo == pairo.getItemNo() && this.itemData == pairo.getItemData();
}
}
static class LengthCompare implements java.util.Comparator<String> {
private static final LengthCompare INSTANCE = new LengthCompare();
public LengthCompare() {
super();
}
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
}

View File

@ -7,18 +7,15 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
import java.util.*;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.capitalCase;
import static com.earth2me.essentials.I18n.tl;
@ -31,7 +28,7 @@ public class Kit {
public Kit(final String kitName, final IEssentials ess) throws Exception {
this.kitName = kitName;
this.ess = ess;
this.kit = ess.getSettings().getKit(kitName);
this.kit = ess.getKits().getKit(kitName);
this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess);
if (kit == null) {
@ -39,40 +36,6 @@ public class Kit {
}
}
//TODO: Convert this to use one of the new text classes?
public static String listKits(final IEssentials ess, final User user) throws Exception {
try {
final ConfigurationSection kits = ess.getSettings().getKits();
final StringBuilder list = new StringBuilder();
for (String kitItem : kits.getKeys(false)) {
if (user == null) {
list.append(" ").append(capitalCase(kitItem));
} else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) {
String cost = "";
String name = capitalCase(kitItem);
BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
if (costPrice.signum() > 0) {
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
}
Kit kit = new Kit(kitItem, ess);
double nextUse = kit.getNextUse(user);
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
continue;
} else if (nextUse != 0) {
name = tl("kitDelay", name);
}
list.append(" ").append(name).append(cost);
}
}
return list.toString().trim();
} catch (Exception ex) {
throw new Exception(tl("kitError"), ex);
}
}
public String getName() {
return kitName;
}
@ -185,7 +148,7 @@ public class Kit {
public void expandItems(final User user, final List<String> items) throws Exception {
try {
IText input = new SimpleTextInput(items);
IText output = new KeywordReplacer(input, user.getSource(), ess);
IText output = new KeywordReplacer(input, user.getSource(), ess, true, true);
boolean spew = false;
final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments();

View File

@ -0,0 +1,114 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.earth2me.essentials.I18n.capitalCase;
import static com.earth2me.essentials.I18n.tl;
public class Kits implements IConf {
private final EssentialsConf config;
private ConfigurationSection kits;
public Kits(final IEssentials essentials) {
config = new EssentialsConf(new File(essentials.getDataFolder(), "kits.yml"));
config.setTemplateName("/kits.yml");
reloadConfig();
}
@Override
public void reloadConfig() {
config.load();
kits = _getKits();
}
private ConfigurationSection _getKits() {
if (config.isConfigurationSection("kits")) {
final ConfigurationSection section = config.getConfigurationSection("kits");
final ConfigurationSection newSection = new MemoryConfiguration();
for (String kitItem : section.getKeys(false)) {
if (section.isConfigurationSection(kitItem)) {
newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem));
}
}
return newSection;
}
return null;
}
public EssentialsConf getConfig() {
return config;
}
public ConfigurationSection getKits() {
return kits;
}
public Map<String, Object> getKit(String name) {
name = name.replace('.', '_').replace('/', '_');
if (getKits() != null) {
final ConfigurationSection kits = getKits();
// For some reason, YAML doesn't sees keys as always lowercase even if they aren't defined like that.
// Workaround is to toLowercase when getting from the config, but showing normally elsewhere.
// ODDLY ENOUGH when you get the configuration section for ALL kits, it will return the proper
// case of each kit. But when you check for each kit's configuration section, it won't return the kit
// you just found if you don't toLowercase it.
if (kits.isConfigurationSection(name.toLowerCase())) {
return kits.getConfigurationSection(name.toLowerCase()).getValues(true);
} else {
}
}
return null;
}
public void addKit(String name, List<String> lines, long delay) {
// Will overwrite but w/e
config.set("kits." + name + ".delay", delay);
config.set("kits." + name + ".items", lines);
kits = _getKits();
config.save();
}
public String listKits(final net.ess3.api.IEssentials ess, final User user) throws Exception {
try {
final ConfigurationSection kits = config.getConfigurationSection("kits");
final StringBuilder list = new StringBuilder();
for (String kitItem : kits.getKeys(false)) {
if (user == null) {
list.append(" ").append(capitalCase(kitItem));
} else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) {
String cost = "";
String name = capitalCase(kitItem);
BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
if (costPrice.signum() > 0) {
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
}
Kit kit = new Kit(kitItem, ess);
double nextUse = kit.getNextUse(user);
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
continue;
} else if (nextUse != 0) {
name = tl("kitDelay", name);
}
list.append(" ").append(name).append(cost);
}
}
return list.toString().trim();
} catch (Exception ex) {
throw new Exception(tl("kitError"), ex);
}
}
}

View File

@ -3,7 +3,9 @@ package com.earth2me.essentials;
import com.earth2me.essentials.textreader.BookInput;
import com.earth2me.essentials.textreader.BookPager;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.base.Joiner;
import net.ess3.api.IEssentials;
@ -17,6 +19,7 @@ import org.bukkit.Material;
import org.bukkit.block.Banner;
import org.bukkit.block.banner.PatternType;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.Potion;
@ -32,8 +35,8 @@ import static com.earth2me.essentials.I18n.tl;
public class MetaItemStack {
private static final Map<String, DyeColor> colorMap = new HashMap<String, DyeColor>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<String, FireworkEffect.Type>();
private static final Map<String, DyeColor> colorMap = new HashMap<>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<>();
static {
for (DyeColor color : DyeColor.values()) {
@ -96,10 +99,6 @@ public class MetaItemStack {
completePotion = true;
}
private boolean isPotion(Material type) {
return type.name().endsWith("POTION");
}
public boolean canSpawn(final IEssentials ess) {
try {
ess.getServer().getUnsafe().modifyItemStack(stack.clone(), "{}");
@ -120,26 +119,6 @@ public class MetaItemStack {
}
public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception {
// Make any entries after lore definition become the lore and not parsed.
{
int loreIndex = -1;
boolean dirty = false;
for (int i = 0; i < string.length; i++) {
String _str = string[i];
if (loreIndex == -1) {
if (_str.matches("^lore" + splitPattern.pattern() + ".*")) {
loreIndex = i;
}
} else {
string[loreIndex] += " " + string[i];
string[i] = null;
dirty = true;
}
}
if (dirty) {
string = (String[]) ArrayUtils.subarray(string, 0, loreIndex + 1);
}
}
if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess)) {
try {
stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length)));
@ -177,16 +156,7 @@ public class MetaItemStack {
return;
}
Material banner = null;
Material shield = null;
try {
// 1.8
banner = Material.valueOf("BANNER");
// 1.9
shield = Material.valueOf("SHIELD");
} catch(IllegalArgumentException ignored){}
Material WRITTEN_BOOK = EnumUtil.getMaterial("WRITTEN_BOOK");
if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess)) {
final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' '));
@ -202,18 +172,18 @@ public class MetaItemStack {
meta.setLore(lore);
stack.setItemMeta(meta);
} else if (split[0].equalsIgnoreCase("unbreakable") && hasMetaPermission(sender, "unbreakable", false, true, ess)) {
boolean value = split.length > 1 ? Boolean.valueOf(split[1]) : true;
boolean value = split.length > 1 ? Boolean.valueOf(split[1]) : true;
setUnbreakable(stack, value);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && stack.getType() == Material.SKULL_ITEM && hasMetaPermission(sender, "head", false, true, ess)) {
if (stack.getDurability() == 3) {
} else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && hasMetaPermission(sender, "head", false, true, ess)) {
if (MaterialUtil.isPlayerHead(stack.getType(), stack.getDurability())) {
final String owner = split[1];
final SkullMeta meta = (SkullMeta) stack.getItemMeta();
meta.setOwner(owner);
meta.setOwningPlayer(ess.getServer().getOfflinePlayer(owner));
stack.setItemMeta(meta);
} else {
throw new Exception(tl("onlyPlayerSkulls"));
}
} else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == WRITTEN_BOOK && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) {
final BookMeta meta = (BookMeta) stack.getItemMeta();
final IText input = new BookInput("book", true, ess);
final BookPager pager = new BookPager(input);
@ -221,40 +191,42 @@ public class MetaItemStack {
List<String> pages = pager.getPages(split[1]);
meta.setPages(pages);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) {
final String author = FormatUtil.replaceFormat(split[1]);
final BookMeta meta = (BookMeta) stack.getItemMeta();
meta.setAuthor(author);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) {
final String title = FormatUtil.replaceFormat(split[1].replace('_', ' '));
final BookMeta meta = (BookMeta) stack.getItemMeta();
meta.setTitle(title);
stack.setItemMeta(meta);
} else if (split.length > 1 && split[0].equalsIgnoreCase("power") && stack.getType() == Material.FIREWORK && hasMetaPermission(sender, "firework-power", false, true, ess)) {
} else if (split.length > 1 && split[0].equalsIgnoreCase("power") && (MaterialUtil.isFirework(stack.getType()))&& hasMetaPermission(sender, "firework-power", false, true, ess)) {
final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0;
final FireworkMeta meta = (FireworkMeta) stack.getItemMeta();
meta.setPower(power > 3 ? 4 : power);
stack.setItemMeta(meta);
} else if (stack.getType() == Material.FIREWORK) {//WARNING - Meta for fireworks will be ignored after this point.
} else if (split.length > 1 && split[0].equalsIgnoreCase("itemflags") && hasMetaPermission(sender, "itemflags", false, true, ess)) {
addItemFlags(string);
} else if (MaterialUtil.isFirework(stack.getType())) {//WARNING - Meta for fireworks will be ignored after this point.
addFireworkMeta(sender, false, string, ess);
} else if (isPotion(stack.getType())) { //WARNING - Meta for potions will be ignored after this point.
} else if (MaterialUtil.isPotion(stack.getType())) { //WARNING - Meta for potions will be ignored after this point.
addPotionMeta(sender, false, string, ess);
} else if (banner != null && stack.getType() == banner) { //WARNING - Meta for banners will be ignored after this point.
} else if (MaterialUtil.isBanner(stack.getType())) {
//WARNING - Meta for banners will be ignored after this point.
addBannerMeta(sender, false, string, ess);
} else if (shield != null && stack.getType() == shield) { //WARNING - Meta for shields will be ignored after this point.
addBannerMeta(sender, false, string, ess);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) && (stack.getType() == Material.LEATHER_BOOTS || stack.getType() == Material.LEATHER_CHESTPLATE || stack.getType() == Material.LEATHER_HELMET || stack.getType() == Material.LEATHER_LEGGINGS)) {
} else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) && MaterialUtil.isLeatherArmor(stack.getType())) {
final String[] color = split[1].split("(\\||,)");
if(color.length == 1 && (NumberUtil.isInt(color[0]) || color[0].startsWith("#"))) { // int rgb and hex
if (color.length == 1 && (NumberUtil.isInt(color[0]) || color[0].startsWith("#"))) {
// Either integer or hexadecimal
final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta();
String input = color[0];
if(input.startsWith("#")) {
if (input.startsWith("#")) { // Hex
meta.setColor(Color.fromRGB(
Integer.valueOf(input.substring(1, 3), 16),
Integer.valueOf(input.substring(3, 5), 16),
Integer.valueOf(input.substring(5, 7), 16)));
} else {
} else { // Int
meta.setColor(Color.fromRGB(Integer.parseInt(input)));
}
stack.setItemMeta(meta);
@ -273,8 +245,32 @@ public class MetaItemStack {
}
}
public void addItemFlags(final String string) throws Exception {
String[] separate = splitPattern.split(string, 2);
if (separate.length != 2) {
throw new Exception(tl("invalidItemFlagMeta", string));
}
String[] split = separate[1].split(",");
ItemMeta meta = stack.getItemMeta();
for (String s : split) {
for (ItemFlag flag : ItemFlag.values()) {
if (s.equalsIgnoreCase(flag.name())) {
meta.addItemFlags(flag);
}
}
}
if (meta.getItemFlags().isEmpty()) {
throw new Exception(tl("invalidItemFlagMeta", string));
}
stack.setItemMeta(meta);
}
public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (stack.getType() == Material.FIREWORK) {
if (MaterialUtil.isFirework(stack.getType())) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
return;
@ -346,7 +342,7 @@ public class MetaItemStack {
}
public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (isPotion(stack.getType())) {
if (MaterialUtil.isPotion(stack.getType())) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
@ -475,13 +471,13 @@ public class MetaItemStack {
}
public void addBannerMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception {
if (stack.getType() == Material.BANNER && string != null) {
if (MaterialUtil.isBanner(stack.getType()) && !stack.getType().toString().equals("SHIELD") && string != null) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
throw new Exception(tl("invalidBanner", split[1]));
}
PatternType patternType = null;
try {
patternType = PatternType.valueOf(split[0]);
@ -499,7 +495,7 @@ public class MetaItemStack {
}
stack.setItemMeta(meta);
} else if (stack.getType() == Material.SHIELD && string != null) {
} else if (stack.getType().toString().equals("SHIELD") && string != null) {
final String[] split = splitPattern.split(string, 2);
if (split.length < 2) {
@ -547,22 +543,36 @@ public class MetaItemStack {
}
}
private static int bukkitUnbreakableSupport = -1;
private static Method spigotMethod;
private static Method setUnbreakableMethod;
private void setUnbreakable(ItemStack is, boolean unbreakable) {
ItemMeta meta = is.getItemMeta();
try {
if (spigotMethod == null) {
spigotMethod = meta.getClass().getDeclaredMethod("spigot");
spigotMethod.setAccessible(true);
if (bukkitUnbreakableSupport == -1) {
try {
ItemMeta.class.getDeclaredMethod("setUnbreakable", boolean.class);
bukkitUnbreakableSupport = 1;
} catch (NoSuchMethodException | SecurityException ex) {
bukkitUnbreakableSupport = 0;
}
}
Object itemStackSpigot = spigotMethod.invoke(meta);
if (setUnbreakableMethod == null) {
setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE);
setUnbreakableMethod.setAccessible(true);
if (bukkitUnbreakableSupport == 1) {
meta.setUnbreakable(unbreakable);
} else {
if (spigotMethod == null) {
spigotMethod = meta.getClass().getDeclaredMethod("spigot");
spigotMethod.setAccessible(true);
}
Object itemStackSpigot = spigotMethod.invoke(meta);
if (setUnbreakableMethod == null) {
setUnbreakableMethod = itemStackSpigot.getClass().getDeclaredMethod("setUnbreakable", Boolean.TYPE);
setUnbreakableMethod.setAccessible(true);
}
setUnbreakableMethod.invoke(itemStackSpigot, unbreakable);
}
setUnbreakableMethod.invoke(itemStackSpigot, unbreakable);
is.setItemMeta(meta);
} catch (Throwable t) {
t.printStackTrace();

View File

@ -75,6 +75,14 @@ public enum Mob {
HUSK("Husk", Enemies.ENEMY, "HUSK"),
ILLUSIONER("Illusioner", Enemies.ENEMY, "ILLUSIONER"),
PARROT("Parrot", Enemies.NEUTRAL, "PARROT"),
TURTLE("Turtle", Enemies.NEUTRAL, "TURTLE"),
PHANTOM("Phantom", Enemies.ENEMY, "PHANTOM"),
COD("Cod", Enemies.NEUTRAL, "COD"),
SALMON("Salmon", Enemies.NEUTRAL, "SALMON"),
PUFFERFISH("Pufferfish", Enemies.NEUTRAL, "PUFFERFISH"),
TROPICAL_FISH("TropicalFish", Enemies.NEUTRAL, "TROPICAL_FISH"),
DROWNED("Drowned", Enemies.ENEMY, "DROWNED"),
DOLPHIN("Dolphin", Enemies.NEUTRAL, "DOLPHIN"),
;
public static final Logger logger = Logger.getLogger("Essentials");

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.DyeColor;
import org.bukkit.Material;
@ -53,9 +54,9 @@ public enum MobData {
BAY_HORSE("bay", EntityType.HORSE, Horse.Color.BROWN, true),
BROWN_HORSE("brown", EntityType.HORSE, Horse.Color.BROWN, false),
SADDLE_HORSE("saddle", EntityType.HORSE, Data.HORSESADDLE, true),
GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, Material.GOLD_BARDING, true),
DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, Material.DIAMOND_BARDING, true),
ARMOR_HORSE("armor", EntityType.HORSE, Material.IRON_BARDING, true),
GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, EnumUtil.getMaterial("GOLDEN_HORSE_ARMOR", "GOLD_BARDING"), true),
DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, EnumUtil.getMaterial("DIAMOND_HORSE_ARMOR", "DIAMOND_BARDING"), true),
ARMOR_HORSE("armor", EntityType.HORSE, EnumUtil.getMaterial("IRON_HORSE_ARMOR", "IRON_BARDING"), true),
SIAMESE_CAT("siamese", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, true),
WHITE_CAT("white", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, false),
RED_CAT("red", EntityType.OCELOT, Ocelot.Type.RED_CAT, true),
@ -66,12 +67,12 @@ public enum MobData {
BABY_ZOMBIE("baby", EntityType.ZOMBIE.getEntityClass(), Data.BABYZOMBIE, true),
ADULT_ZOMBIE("adult", EntityType.ZOMBIE.getEntityClass(), Data.ADULTZOMBIE, true),
DIAMOND_SWORD_ZOMBIE("diamondsword", EntityType.ZOMBIE.getEntityClass(), Material.DIAMOND_SWORD, true),
GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), Material.GOLD_SWORD, true),
GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD"), true),
IRON_SWORD_ZOMBIE("ironsword", EntityType.ZOMBIE.getEntityClass(), Material.IRON_SWORD, true),
STONE_SWORD_ZOMBIE("stonesword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, false),
SWORD_ZOMBIE("sword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, true),
DIAMOND_SWORD_SKELETON("diamondsword", EntityType.SKELETON, Material.DIAMOND_SWORD, true),
GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, Material.GOLD_SWORD, true),
GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD"), true),
IRON_SWORD_SKELETON("ironsword", EntityType.SKELETON, Material.IRON_SWORD, true),
STONE_SWORD_SKELETON("stonesword", EntityType.SKELETON, Material.STONE_SWORD, false),
SWORD_SKELETON("sword", EntityType.SKELETON, Material.STONE_SWORD, true),
@ -95,6 +96,18 @@ public enum MobData {
BLUE_PARROT("blue", EntityType.PARROT, Parrot.Variant.BLUE, true),
CYAN_PARROT("cyan", EntityType.PARROT, Parrot.Variant.CYAN, true),
GRAY_PARROT("gray", EntityType.PARROT, Parrot.Variant.GRAY, true),
KOB_TROPICAL_FISH("kob", EntityType.TROPICAL_FISH, TropicalFish.Pattern.KOB, true),
SUNSTREAK_TROPICAL_FISH("sunstreak", EntityType.TROPICAL_FISH, TropicalFish.Pattern.SUNSTREAK, true),
SNOOPER_TROPICAL_FISH("snooper", EntityType.TROPICAL_FISH, TropicalFish.Pattern.SNOOPER, true),
DASHER_TROPICAL_FISH("dasher", EntityType.TROPICAL_FISH, TropicalFish.Pattern.DASHER, true),
BRINELY_TROPICAL_FISH("brinely", EntityType.TROPICAL_FISH, TropicalFish.Pattern.BRINELY, true),
SPOTTY_TROPICAL_FISH("spotty", EntityType.TROPICAL_FISH, TropicalFish.Pattern.SPOTTY, true),
FLOPPER_TROPICAL_FISH("flopper", EntityType.TROPICAL_FISH, TropicalFish.Pattern.FLOPPER, true),
STRIPEY_TROPICAL_FISH("stripey", EntityType.TROPICAL_FISH, TropicalFish.Pattern.STRIPEY, true),
GLITTER_TROPICAL_FISH("glitter", EntityType.TROPICAL_FISH, TropicalFish.Pattern.GLITTER, true),
BLOCKFISH_TROPICAL_FISH("blockfish", EntityType.TROPICAL_FISH, TropicalFish.Pattern.BLOCKFISH, true),
BETTY_TROPICAL_FISH("betty", EntityType.TROPICAL_FISH, TropicalFish.Pattern.BETTY, true),
CLAYFISH_TROPICAL_FISH("clayfish", EntityType.TROPICAL_FISH, TropicalFish.Pattern.CLAYFISH, true);
;
@ -252,6 +265,8 @@ public enum MobData {
}
} else if (this.value instanceof Parrot.Variant) {
((Parrot) spawned).setVariant((Parrot.Variant) this.value);
} else if (this.value instanceof TropicalFish.Pattern) {
((TropicalFish) spawned).setPattern((TropicalFish.Pattern) this.value);
}
}
}

View File

@ -8,7 +8,9 @@ import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.PistonMoveReaction;
import org.bukkit.block.data.BlockData;
import org.bukkit.conversations.Conversation;
import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.entity.*;
@ -25,6 +27,8 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import java.lang.reflect.InvocationTargetException;
@ -145,6 +149,10 @@ public class OfflinePlayer implements Player {
return -1;
}
public BlockFace getFacing() {
return null;
}
@Override
public boolean performCommand(String string) {
return false;
@ -200,24 +208,34 @@ public class OfflinePlayer implements Player {
return Collections.emptyList();
}
@Override
public Block getTargetBlock(HashSet<Byte> hs, int i) {
return null;
}
@Override
public Block getTargetBlock(Set<Material> mat, int i) {
return null;
}
@Override
public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i) {
public List<Block> getLastTwoTargetBlocks(Set<Material> mat, int i) {
return Collections.emptyList();
}
@Override
public List<Block> getLastTwoTargetBlocks(Set<Material> mat, int i) {
return Collections.emptyList();
public Block getTargetBlockExact(int maxDistance) {
return null;
}
@Override
public Block getTargetBlockExact(int maxDistance, FluidCollisionMode fluidCollisionMode) {
return null;
}
@Override
public RayTraceResult rayTraceBlocks(double maxDistance) {
return null;
}
@Override
public RayTraceResult rayTraceBlocks(double maxDistance, FluidCollisionMode fluidCollisionMode) {
return null;
}
@Override
@ -243,6 +261,15 @@ public class OfflinePlayer implements Player {
return server;
}
@Override
public boolean isPersistent() {
return false;
}
@Override
public void setPersistent(boolean persistent) {
}
public Vector getMomentum() {
return getVelocity();
}
@ -481,7 +508,8 @@ public class OfflinePlayer implements Player {
}
@Override
public void sendBlockChange(Location lctn, int i, byte b) {
public void sendBlockChange(Location loc, BlockData block) {
}
@Override
@ -653,6 +681,31 @@ public class OfflinePlayer implements Player {
public void setPlayerListName(String name) {
}
@Override
public String getPlayerListHeader() {
return null;
}
@Override
public String getPlayerListFooter() {
return null;
}
@Override
public void setPlayerListHeader(String header) {
}
@Override
public void setPlayerListFooter(String footer) {
}
@Override
public void setPlayerListHeaderFooter(String header, String footer) {
}
@Override
public String getPlayerListName() {
return name;
@ -734,6 +787,21 @@ public class OfflinePlayer implements Player {
public void setBedSpawnLocation(Location lctn, boolean force) {
}
@Override
public boolean sleep(Location location, boolean force) {
return false;
}
@Override
public void wakeup(boolean setSpawnLocation) {
}
@Override
public Location getBedLocation() {
return null;
}
@Override
public void playEffect(EntityEffect ee) {
}
@ -742,10 +810,20 @@ public class OfflinePlayer implements Player {
public void hidePlayer(Player player) {
}
@Override
public void hidePlayer(Plugin plugin, Player player) {
}
@Override
public void showPlayer(Player player) {
}
@Override
public void showPlayer(Plugin plugin, Player player) {
}
@Override
public boolean canSee(Player player) {
return false;
@ -920,6 +998,26 @@ public class OfflinePlayer implements Player {
return 0;
}
@Override
public boolean discoverRecipe(NamespacedKey recipe) {
return false;
}
@Override
public int discoverRecipes(Collection<NamespacedKey> recipes) {
return 0;
}
@Override
public boolean undiscoverRecipe(NamespacedKey recipe) {
return false;
}
@Override
public int undiscoverRecipes(Collection<NamespacedKey> recipes) {
return 0;
}
@Override
public boolean hasLineOfSight(Entity entity) {
return false;
@ -1195,6 +1293,21 @@ public class OfflinePlayer implements Player {
public void setGliding(boolean b) {
}
@Override
public boolean isSwimming() {
return false;
}
@Override
public void setSwimming(boolean swimming) {
}
@Override
public boolean isRiptiding() {
return false;
}
@Override
public void setAI(boolean b) {
}
@ -1412,6 +1525,11 @@ public class OfflinePlayer implements Player {
return null;
}
@Override
public int getClientViewDistance() {
return 0;
}
@Override
public String getLocale() {
return null;
@ -1459,6 +1577,11 @@ public class OfflinePlayer implements Player {
return 0;
}
@Override
public BoundingBox getBoundingBox() {
return null;
}
@Override
public List<Entity> getPassengers() {
return null;
@ -1478,4 +1601,8 @@ public class OfflinePlayer implements Player {
public PistonMoveReaction getPistonMoveReaction() {
return null;
}
@Override
public void updateCommands() {
}
}

View File

@ -11,8 +11,8 @@ import java.util.Set;
public class Potions {
private static final Map<String, PotionEffectType> POTIONS = new HashMap<String, PotionEffectType>();
private static final Map<String, PotionEffectType> ALIASPOTIONS = new HashMap<String, PotionEffectType>();
private static final Map<String, PotionEffectType> POTIONS = new HashMap<>();
private static final Map<String, PotionEffectType> ALIASPOTIONS = new HashMap<>();
static {

View File

@ -1,23 +1,24 @@
package com.earth2me.essentials;
import com.earth2me.essentials.api.IItemDb;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.signs.Signs;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.event.EventPriority;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
@ -37,7 +38,6 @@ public class Settings implements net.ess3.api.ISettings {
private final transient EssentialsConf config;
private static final Logger logger = Logger.getLogger("Essentials");
private final transient IEssentials ess;
private boolean metricsEnabled = true;
public Settings(IEssentials ess) {
this.ess = ess;
@ -325,46 +325,24 @@ public class Settings implements net.ess3.api.ISettings {
return config.getDouble("heal-cooldown", 0);
}
private ConfigurationSection kits;
private ConfigurationSection _getKits() {
if (config.isConfigurationSection("kits")) {
final ConfigurationSection section = config.getConfigurationSection("kits");
final ConfigurationSection newSection = new MemoryConfiguration();
for (String kitItem : section.getKeys(false)) {
if (section.isConfigurationSection(kitItem)) {
newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem));
}
}
return newSection;
}
return null;
}
@Override
public ConfigurationSection getKits() {
return kits;
return ess.getKits().getKits();
}
@Override
public Map<String, Object> getKit(String name) {
name = name.replace('.', '_').replace('/', '_');
if (getKits() != null) {
final ConfigurationSection kits = getKits();
if (kits.isConfigurationSection(name)) {
return kits.getConfigurationSection(name).getValues(true);
}
}
return null;
return ess.getKits().getKit(name);
}
@Override
public void addKit(String name, List<String> lines, long delay) {
// Will overwrite but w/e
config.set("kits." + name + ".delay", delay);
config.set("kits." + name + ".items", lines);
kits = _getKits();
config.save();
ess.getKits().addKit(name, lines, delay);
}
@Override
public ConfigurationSection getKitSection() {
return config.getConfigurationSection("kits");
}
@Override
@ -449,9 +427,14 @@ public class Settings implements net.ess3.api.ISettings {
mFormat = mFormat.replace("{TEAMPREFIX}", "{3}");
mFormat = mFormat.replace("{TEAMSUFFIX}", "{4}");
mFormat = mFormat.replace("{TEAMNAME}", "{5}");
mFormat = mFormat.replace("{PREFIX}", "{6}");
mFormat = mFormat.replace("{SUFFIX}", "{7}");
mFormat = "§r".concat(mFormat);
chatFormats.put(group, mFormat);
}
if (isDebug()) {
ess.getLogger().info(String.format("Found format '%s' for group '%s'", mFormat, group));
}
return mFormat;
}
@ -509,14 +492,14 @@ public class Settings implements net.ess3.api.ISettings {
disableItemPickupWhileAfk = _getDisableItemPickupWhileAfk();
registerBackInListener = _registerBackInListener();
cancelAfkOnInteract = _cancelAfkOnInteract();
cancelAfkOnMove = _cancelAfkOnMove() && cancelAfkOnInteract;
cancelAfkOnMove = _cancelAfkOnMove();
getFreezeAfkPlayers = _getFreezeAfkPlayers();
sleepIgnoresAfkPlayers = _sleepIgnoresAfkPlayers();
afkListName = _getAfkListName();
isAfkListName = !afkListName.equalsIgnoreCase("none");
itemSpawnBl = _getItemSpawnBlacklist();
loginAttackDelay = _getLoginAttackDelay();
signUsePerSecond = _getSignUsePerSecond();
kits = _getKits();
chatFormats.clear();
changeDisplayName = _changeDisplayName();
disabledCommands = getDisabledCommands();
@ -553,19 +536,30 @@ public class Settings implements net.ess3.api.ISettings {
npcsInBalanceRanking = _isNpcsInBalanceRanking();
currencyFormat = _getCurrencyFormat();
unprotectedSigns = _getUnprotectedSign();
defaultEnabledConfirmCommands = _getDefaultEnabledConfirmCommands();
isCompassTowardsHomePerm = _isCompassTowardsHomePerm();
isAllowWorldInBroadcastworld = _isAllowWorldInBroadcastworld();
itemDbType = _getItemDbType();
forceEnableRecipe = _isForceEnableRecipe();
allowOldIdSigns = _allowOldIdSigns();
}
private List<Integer> itemSpawnBl = new ArrayList<Integer>();
void _lateLoadItemSpawnBlacklist() {
itemSpawnBl = _getItemSpawnBlacklist();
}
private List<Material> itemSpawnBl = new ArrayList<>();
@Override
public List<Integer> itemSpawnBlacklist() {
public List<Material> itemSpawnBlacklist() {
return itemSpawnBl;
}
private List<Integer> _getItemSpawnBlacklist() {
final List<Integer> epItemSpwn = new ArrayList<Integer>();
if (ess.getItemDb() == null) {
logger.log(Level.FINE, "Aborting ItemSpawnBL read, itemDB not yet loaded.");
private List<Material> _getItemSpawnBlacklist() {
final List<Material> epItemSpwn = new ArrayList<>();
final IItemDb itemDb = ess.getItemDb();
if (itemDb == null || !itemDb.isReady()) {
logger.log(Level.FINE, "Skipping item spawn blacklist read; item DB not yet loaded.");
return epItemSpwn;
}
for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) {
@ -574,10 +568,10 @@ public class Settings implements net.ess3.api.ISettings {
continue;
}
try {
final ItemStack iStack = ess.getItemDb().get(itemName);
epItemSpwn.add(iStack.getTypeId());
final ItemStack iStack = itemDb.get(itemName);
epItemSpwn.add(iStack.getType());
} catch (Exception ex) {
logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"));
logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex);
}
}
return epItemSpwn;
@ -663,10 +657,17 @@ public class Settings implements net.ess3.api.ISettings {
// #easteregg
@Override
@Deprecated
public boolean isTradeInStacks(int id) {
return config.getBoolean("trade-in-stacks-" + id, false);
}
// #easteregg
@Override
public boolean isTradeInStacks(Material type) {
return config.getBoolean("trade-in-stacks." + type.toString().toLowerCase().replace("_", ""), false);
}
// #easteregg
private boolean economyDisabled = false;
@ -685,19 +686,27 @@ public class Settings implements net.ess3.api.ISettings {
}
@Override
public List<Integer> getProtectList(final String configName) {
final List<Integer> list = new ArrayList<Integer>();
public List<Material> getProtectList(final String configName) {
final List<Material> list = new ArrayList<>();
for (String itemName : config.getString(configName, "").split(",")) {
itemName = itemName.trim();
if (itemName.isEmpty()) {
continue;
}
ItemStack itemStack;
try {
itemStack = ess.getItemDb().get(itemName);
list.add(itemStack.getTypeId());
} catch (Exception ex) {
Material mat = EnumUtil.getMaterial(itemName.toUpperCase());
if (mat == null) {
try {
ItemStack itemStack = ess.getItemDb().get(itemName);
mat = itemStack.getType();
} catch (Exception ignored) {}
}
if (mat == null) {
logger.log(Level.SEVERE, tl("unknownItemInList", itemName, configName));
} else {
list.add(mat);
}
}
return list;
@ -885,6 +894,17 @@ public class Settings implements net.ess3.api.ISettings {
return config.getBoolean("cancel-afk-on-interact", true);
}
private boolean sleepIgnoresAfkPlayers;
@Override
public boolean sleepIgnoresAfkPlayers() {
return sleepIgnoresAfkPlayers;
}
private boolean _sleepIgnoresAfkPlayers() {
return config.getBoolean("sleep-ignores-afk-players", true);
}
private String afkListName;
private boolean isAfkListName;
@ -1111,6 +1131,11 @@ public class Settings implements net.ess3.api.ISettings {
return config.getBoolean("ignore-colors-in-max-nick-length", false);
}
@Override
public boolean hideDisplayNameInVanish() {
return config.getBoolean("hide-displayname-in-vanish", false);
}
private boolean allowSilentJoin;
public boolean _allowSilentJoinQuit() {
@ -1202,7 +1227,7 @@ public class Settings implements net.ess3.api.ISettings {
public boolean isSpawnOnJoin() {
return !this.spawnOnJoinGroups.isEmpty();
}
private List<String> spawnOnJoinGroups;
public List<String> _getSpawnOnJoinGroups() {
@ -1241,7 +1266,7 @@ public class Settings implements net.ess3.api.ISettings {
public boolean isTeleportToCenterLocation() {
return config.getBoolean("teleport-to-center", true);
}
private Map<Pattern, Long> commandCooldowns;
private Map<Pattern, Long> _getCommandCooldowns() {
@ -1268,10 +1293,10 @@ public class Settings implements net.ess3.api.ISettings {
cmdEntry = cmdEntry.substring(1);
}
String cmd = cmdEntry
.replaceAll("\\*", ".*"); // Wildcards are accepted as asterisk * as known universally.
.replaceAll("\\*", ".*"); // Wildcards are accepted as asterisk * as known universally.
pattern = Pattern.compile(cmd + "( .*)?"); // This matches arguments, if present, to "ignore" them from the feature.
}
/* ================================
* >> Process cooldown value
* ================================ */
@ -1312,7 +1337,12 @@ public class Settings implements net.ess3.api.ISettings {
if (isCommandCooldownsEnabled()) {
for (Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) {
// Check if label matches current pattern (command-cooldown in config)
if (entry.getKey().matcher(label).matches()) {
boolean matches = entry.getKey().matcher(label).matches();
if (isDebug()) {
ess.getLogger().info(String.format("Checking command '%s' against cooldown '%s': %s", label, entry.getKey(), matches));
}
if (matches) {
return entry;
}
}
@ -1354,24 +1384,8 @@ public class Settings implements net.ess3.api.ISettings {
DecimalFormat currencyFormat = new DecimalFormat(currencyFormatString, decimalFormatSymbols);
currencyFormat.setRoundingMode(RoundingMode.FLOOR);
// Updates NumberUtil#PRETTY_FORMAT field so that all of Essentials
// can follow a single format.
try {
Field field = NumberUtil.class.getDeclaredField("PRETTY_FORMAT");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, currencyFormat);
modifiersField.setAccessible(false);
field.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException e) {
ess.getLogger().severe("Failed to apply custom currency format: " + e.getMessage());
if (isDebug()) {
e.printStackTrace();
}
}
// Updates NumberUtil#PRETTY_FORMAT field so that all of Essentials can follow a single format.
NumberUtil.internalSetPrettyFormat(currencyFormat);
return currencyFormat;
}
@ -1407,7 +1421,7 @@ public class Settings implements net.ess3.api.ISettings {
@Override
public boolean isPastebinCreateKit() {
return config.getBoolean("pastebin-createkit", true);
return config.getBoolean("pastebin-createkit", false);
}
@Override
@ -1439,4 +1453,79 @@ public class Settings implements net.ess3.api.ISettings {
public boolean isDirectHatAllowed() {
return config.getBoolean("allow-direct-hat", true);
}
private List<String> defaultEnabledConfirmCommands;
private List<String> _getDefaultEnabledConfirmCommands() {
List<String> commands = config.getStringList("default-enabled-confirm-commands");
for (int i = 0; i < commands.size(); i++) {
commands.set(i, commands.get(i).toLowerCase());
}
return commands;
}
@Override
public List<String> getDefaultEnabledConfirmCommands() {
return defaultEnabledConfirmCommands;
}
@Override
public boolean isConfirmCommandEnabledByDefault(String commandName) {
return getDefaultEnabledConfirmCommands().contains(commandName.toLowerCase());
}
private boolean isCompassTowardsHomePerm;
private boolean _isCompassTowardsHomePerm() {
return config.getBoolean("compass-towards-home-perm", false);
}
@Override
public boolean isCompassTowardsHomePerm() {
return isCompassTowardsHomePerm;
}
private boolean isAllowWorldInBroadcastworld;
private boolean _isAllowWorldInBroadcastworld() {
return config.getBoolean("allow-world-in-broadcastworld", false);
}
@Override
public boolean isAllowWorldInBroadcastworld() {
return isAllowWorldInBroadcastworld;
}
private String itemDbType; // #EasterEgg - admins can manually switch items provider if they want
private String _getItemDbType() {
return config.getString("item-db-type", "auto");
}
@Override
public String getItemDbType() {
return itemDbType;
}
private boolean forceEnableRecipe; // https://github.com/EssentialsX/Essentials/issues/1397
private boolean _isForceEnableRecipe() {
return config.getBoolean("force-enable-recipe", false);
}
@Override
public boolean isForceEnableRecipe() {
return forceEnableRecipe;
}
private boolean allowOldIdSigns;
private boolean _allowOldIdSigns() {
return config.getBoolean("allow-old-id-signs", false);
}
@Override
public boolean allowOldIdSigns() {
return allowOldIdSigns;
}
}

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.Mob.MobException;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.IEssentials;
@ -19,6 +20,13 @@ import static com.earth2me.essentials.I18n.tl;
public class SpawnMob {
private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET");
private static final Material GOLDEN_CHESTPLATE = EnumUtil.getMaterial("GOLDEN_CHESTPLATE", "GOLD_CHESTPLATE");
private static final Material GOLDEN_LEGGINGS = EnumUtil.getMaterial("GOLDEN_LEGGINGS", "GOLD_LEGGINGS");
private static final Material GOLDEN_BOOTS = EnumUtil.getMaterial("GOLDEN_BOOTS", "GOLD_BOOTS");
private static final Material GOLDEN_SWORD = EnumUtil.getMaterial("GOLDEN_SWORD", "GOLD_SWORD");
public static String mobList(final User user) {
final Set<String> mobList = Mob.getMobList();
final Set<String> availableList = new HashSet<String>();
@ -191,16 +199,16 @@ public class SpawnMob {
invent.setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.DIAMOND_HELMET, 1));
} else if (inputData.contains("gold")) {
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.GOLD_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.GOLD_HELMET, 1));
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
invent.setLeggings(new ItemStack(GOLDEN_LEGGINGS, 1));
invent.setChestplate(new ItemStack(GOLDEN_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(GOLDEN_HELMET, 1));
} else if (inputData.contains("leather")) {
invent.setBoots(new ItemStack(Material.LEATHER_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.LEATHER_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE, 1));
invent.setHelmet(new ItemStack(Material.LEATHER_HELMET, 1));
} else {
} else if (inputData.contains("iron")) {
invent.setBoots(new ItemStack(Material.IRON_BOOTS, 1));
invent.setLeggings(new ItemStack(Material.IRON_LEGGINGS, 1));
invent.setChestplate(new ItemStack(Material.IRON_CHESTPLATE, 1));
@ -228,7 +236,7 @@ public class SpawnMob {
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(Material.BOW, 1));
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}
@ -237,10 +245,10 @@ public class SpawnMob {
setVillager(zombie, false);
final EntityEquipment invent = zombie.getEquipment();
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(Material.GOLD_SWORD, 1));
InventoryWorkaround.setItemInMainHand(invent, new ItemStack(GOLDEN_SWORD, 1));
InventoryWorkaround.setItemInMainHandDropChance(invent, 0.1f);
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}
@ -249,7 +257,7 @@ public class SpawnMob {
setVillager(zombie, false);
final EntityEquipment invent = zombie.getEquipment();
invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1));
invent.setBoots(new ItemStack(GOLDEN_BOOTS, 1));
invent.setBootsDropChance(0.0f);
}

View File

@ -2,8 +2,12 @@ package com.earth2me.essentials;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.api.ITeleport;
import net.ess3.api.IUser;
import net.ess3.api.events.UserWarpEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerRespawnEvent;
@ -16,7 +20,7 @@ import java.util.GregorianCalendar;
import static com.earth2me.essentials.I18n.tl;
public class Teleport implements net.ess3.api.ITeleport {
public class Teleport implements ITeleport {
private final IUser teleportOwner;
private final IEssentials ess;
private TimedTeleport timedTeleport;
@ -47,7 +51,7 @@ public class Teleport implements net.ess3.api.ITeleport {
final long earliestLong = earliestTime.getTimeInMillis();
// When was the last teleportPlayer used?
final Long lastTime = teleportOwner.getLastTeleportTimestamp();
final long lastTime = teleportOwner.getLastTeleportTimestamp();
if (lastTime > time.getTimeInMillis()) {
// This is to make sure time didn't get messed up on last teleportPlayer use.
@ -122,21 +126,21 @@ public class Teleport implements net.ess3.api.ITeleport {
if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) {
if (ess.getSettings().isTeleportSafetyEnabled()) {
if (ess.getSettings().isForceDisableTeleportSafety()) {
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
} else {
teleportee.getBase().teleport(LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
}
} else {
throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
} else {
if (ess.getSettings().isForceDisableTeleportSafety()) {
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
} else {
if (ess.getSettings().isTeleportToCenterLocation()) {
loc = LocationUtil.getRoundedDestination(loc);
}
teleportee.getBase().teleport(loc, cause);
PaperLib.teleportAsync(teleportee.getBase(), loc, cause);
}
}
}
@ -229,7 +233,7 @@ public class Teleport implements net.ess3.api.ITeleport {
initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true);
}
protected void respawnNow(IUser teleportee, TeleportCause cause) throws Exception {
void respawnNow(IUser teleportee, TeleportCause cause) throws Exception {
final Player player = teleportee.getBase();
Location bed = player.getBedSpawnLocation();
if (bed != null) {
@ -247,6 +251,13 @@ public class Teleport implements net.ess3.api.ITeleport {
//The warp function is a wrapper used to teleportPlayer a player to a /warp
@Override
public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception {
UserWarpEvent event = new UserWarpEvent(teleportee, warp, chargeFor);
Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return;
}
warp = event.getWarp();
Location loc = ess.getWarps().getWarp(warp);
teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
if (!teleportee.equals(teleportOwner)) {

View File

@ -16,9 +16,9 @@ public class TimedTeleport implements Runnable {
private final IEssentials ess;
private final Teleport teleport;
private final UUID timer_teleportee;
private int timer_task = -1;
private final long timer_started; // time this task was initiated
private final long timer_delay; // how long to delay the teleportPlayer
private int timer_task;
private final long timer_started; // time this task was initiated
private final long timer_delay; // how long to delay the teleportPlayer
private double timer_health;
// note that I initially stored a clone of the location for reference, but...
// when comparing locations, I got incorrect mismatches (rounding errors, looked like)
@ -32,8 +32,7 @@ public class TimedTeleport implements Runnable {
private final Trade timer_chargeFor;
private final TeleportCause timer_cause;
public TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) {
TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) {
this.teleportOwner = user;
this.ess = ess;
this.teleport = teleport;
@ -111,8 +110,7 @@ public class TimedTeleport implements Runnable {
if (timer_chargeFor != null) {
timer_chargeFor.charge(teleportOwner);
}
} catch (Exception ex) {
}
} catch (Exception ignored) {}
} catch (Exception ex) {
ess.showError(teleportOwner.getSource(), ex, "\\ teleport");
@ -124,7 +122,7 @@ public class TimedTeleport implements Runnable {
}
//If we need to cancelTimer a pending teleportPlayer call this method
public void cancelTimer(boolean notifyUser) {
void cancelTimer(boolean notifyUser) {
if (timer_task == -1) {
return;
}

View File

@ -8,6 +8,7 @@ import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent;
@ -18,6 +19,7 @@ import net.ess3.nms.refl.ReflUtil;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
@ -26,12 +28,7 @@ import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -222,8 +219,19 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
@Override
public Boolean canSpawnItem(final int itemId) {
return !ess.getSettings().itemSpawnBlacklist().contains(itemId);
public Boolean canSpawnItem(final Material material) {
if (ess.getSettings().permissionBasedItemSpawn()) {
final String name = material.toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (isAuthorized("essentials.itemspawn.item-all") || isAuthorized("essentials.itemspawn.item-" + name)) return true;
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
final int id = material.getId();
if (isAuthorized("essentials.itemspawn.item-" + id)) return true;
}
}
return isAuthorized("essentials.itemspawn.exempt") || !ess.getSettings().itemSpawnBlacklist().contains(material);
}
@Override
@ -359,7 +367,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
public String getDisplayName() {
return super.getBase().getDisplayName() == null ? super.getBase().getName() : super.getBase().getDisplayName();
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
}
@Override
@ -457,7 +465,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return;
}
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set);
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") || set && ess.getSettings().sleepIgnoresAfkPlayers());
if (set && !isAfk()) {
afkPosition = this.getLocation();
this.afkSince = System.currentTimeMillis();
@ -546,7 +554,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
public void updateActivity(final boolean broadcast) {
if (isAfk() && ess.getSettings().cancelAfkOnInteract()) {
if (isAfk()) {
setAfk(false);
if (broadcast && !isHidden()) {
setDisplayNick();
@ -559,6 +567,18 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
lastActivity = System.currentTimeMillis();
}
public void updateActivityOnMove(final boolean broadcast) {
if(ess.getSettings().cancelAfkOnMove()) {
updateActivity(broadcast);
}
}
public void updateActivityOnInteract(final boolean broadcast) {
if(ess.getSettings().cancelAfkOnInteract()) {
updateActivity(broadcast);
}
}
public void checkActivity() {
// Graceful time before the first afk check call.
if (System.currentTimeMillis() - lastActivity <= 10000) {
@ -716,7 +736,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
}
setHidden(true);
ess.getVanishedPlayers().add(getName());
ess.getVanishedPlayersNew().add(getName());
if (isAuthorized("essentials.vanish.effect")) {
this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false));
}
@ -725,7 +745,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
p.showPlayer(getBase());
}
setHidden(false);
ess.getVanishedPlayers().remove(getName());
ess.getVanishedPlayersNew().remove(getName());
if (isAuthorized("essentials.vanish.effect")) {
this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY);
}
@ -860,7 +880,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
* Returns the {@link ItemStack} in the main hand or off-hand. If the main hand is empty then the offhand item is returned - also nullable.
*/
public ItemStack getItemInHand() {
if (ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_9_R1)) {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_9_R01)) {
return getBase().getInventory().getItemInHand();
} else {
PlayerInventory inventory = getBase().getInventory();

View File

@ -7,6 +7,7 @@ import net.ess3.api.IEssentials;
import net.ess3.api.InvalidWorldException;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@ -101,7 +102,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
BigDecimal result = ess.getSettings().getStartingBalance();
BigDecimal maxMoney = ess.getSettings().getMaxMoney();
BigDecimal minMoney = ess.getSettings().getMinMoney();
// NPC banks are not actual player banks, as such they do not have player starting balance.
if (isNPC()) {
result = BigDecimal.ZERO;
@ -232,26 +233,35 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private List<Integer> unlimited;
private List<Material> unlimited;
private List<Integer> _getUnlimited() {
return config.getIntegerList("unlimited");
private List<Material> _getUnlimited() {
List<Material> retlist = new ArrayList<>();
List<String> configList = config.getStringList("unlimited");
for(String s : configList) {
Material mat = Material.matchMaterial(s);
if(mat != null) {
retlist.add(mat);
}
}
return retlist;
}
public List<Integer> getUnlimited() {
public List<Material> getUnlimited() {
return unlimited;
}
public boolean hasUnlimited(ItemStack stack) {
return unlimited.contains(stack.getTypeId());
return unlimited.contains(stack.getType());
}
public void setUnlimited(ItemStack stack, boolean state) {
if (unlimited.contains(stack.getTypeId())) {
unlimited.remove(Integer.valueOf(stack.getTypeId()));
if (unlimited.contains(stack.getType())) {
unlimited.remove(stack.getType());
}
if (state) {
unlimited.add(stack.getTypeId());
unlimited.add(stack.getType());
}
config.setProperty("unlimited", unlimited);
config.save();
@ -263,7 +273,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (config.isConfigurationSection("powertools")) {
return config.getConfigurationSection("powertools").getValues(false);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
public void clearAllPowertools() {
@ -274,19 +284,19 @@ public abstract class UserData extends PlayerExtension implements IConf {
@SuppressWarnings("unchecked")
public List<String> getPowertool(ItemStack stack) {
return (List<String>) powertools.get("" + stack.getTypeId());
return (List<String>) powertools.get(stack.getType().name().toLowerCase(Locale.ENGLISH));
}
@SuppressWarnings("unchecked")
public List<String> getPowertool(int id) {
return (List<String>) powertools.get("" + id);
public List<String> getPowertool(Material material) {
return (List<String>) powertools.get(material.name().toLowerCase(Locale.ENGLISH));
}
public void setPowertool(ItemStack stack, List<String> commandList) {
if (commandList == null || commandList.isEmpty()) {
powertools.remove("" + stack.getTypeId());
powertools.remove(stack.getType().name().toLowerCase(Locale.ENGLISH));
} else {
powertools.put("" + stack.getTypeId(), commandList);
powertools.put(stack.getType().name().toLowerCase(Locale.ENGLISH), commandList);
}
config.setProperty("powertools", powertools);
config.save();
@ -437,6 +447,22 @@ public abstract class UserData extends PlayerExtension implements IConf {
config.save();
}
private boolean autoTeleportEnabled;
private boolean _getAutoTeleportEnabled() {
return config.getBoolean("teleportauto", false);
}
public boolean isAutoTeleportEnabled() {
return autoTeleportEnabled;
}
public void setAutoTeleportEnabled(boolean set) {
autoTeleportEnabled = set;
config.setProperty("teleportauto", set);
config.save();
}
private List<String> ignoredPlayers;
public List<String> _getIgnoredPlayers() {
@ -468,10 +494,11 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
public void setIgnoredPlayer(IUser user, boolean set) {
final String entry = user.getName().toLowerCase(Locale.ENGLISH);
if (set) {
ignoredPlayers.add(user.getName().toLowerCase(Locale.ENGLISH));
if (!ignoredPlayers.contains(entry)) ignoredPlayers.add(entry);
} else {
ignoredPlayers.remove(user.getName().toLowerCase(Locale.ENGLISH));
ignoredPlayers.remove(entry);
}
setIgnoredPlayers(ignoredPlayers);
}
@ -831,7 +858,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (!config.isConfigurationSection("timestamps.command-cooldowns")) {
return null;
}
// See saveCommandCooldowns() for deserialization explanation
List<Map<?, ?>> section = config.getMapList("timestamps.command-cooldowns");
HashMap<Pattern, Long> result = new HashMap<>();
@ -870,19 +897,19 @@ public abstract class UserData extends PlayerExtension implements IConf {
saveCommandCooldowns();
}
}
public boolean clearCommandCooldown(Pattern pattern) {
if (this.commandCooldowns == null) {
return false; // false for no modification
}
if(this.commandCooldowns.remove(pattern) != null) {
saveCommandCooldowns();
return true;
}
return false;
}
private void saveCommandCooldowns() {
// Serialization explanation:
//
@ -923,14 +950,14 @@ public abstract class UserData extends PlayerExtension implements IConf {
save();
}
private boolean confirmPay = true; // players accept pay confirmation by default
private Boolean confirmPay;
public boolean _getConfirmPay() {
return config.getBoolean("confirm-pay", true);
private Boolean _getConfirmPay() {
return (Boolean) config.get("confirm-pay");
}
public boolean isPromptingPayConfirm() {
return confirmPay;
return confirmPay != null ? confirmPay : ess.getSettings().isConfirmCommandEnabledByDefault("pay");
}
public void setPromptingPayConfirm(boolean prompt) {
@ -939,14 +966,14 @@ public abstract class UserData extends PlayerExtension implements IConf {
save();
}
private boolean confirmClear = true; // players accept clear confirmation by default
private Boolean confirmClear;
public boolean _getConfirmClear() {
return config.getBoolean("confirm-clear", true);
private Boolean _getConfirmClear() {
return (Boolean) config.get("confirm-clear");
}
public boolean isPromptingClearConfirm() {
return confirmClear;
return confirmClear != null ? confirmClear : ess.getSettings().isConfirmCommandEnabledByDefault("clearinventory");
}
public void setPromptingClearConfirm(boolean prompt) {

View File

@ -6,13 +6,11 @@ import net.ess3.api.InvalidNameException;
import net.ess3.api.InvalidWorldException;
import org.bukkit.Location;
import org.bukkit.Server;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl;
@ -57,6 +55,11 @@ public class Warps implements IConf, net.ess3.api.IWarps {
@Override
public void setWarp(String name, Location loc) throws Exception {
setWarp(null, name, loc);
}
@Override
public void setWarp(IUser user, String name, Location loc) throws Exception {
String filename = StringUtil.sanitizeFileName(name);
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
@ -69,13 +72,28 @@ public class Warps implements IConf, net.ess3.api.IWarps {
}
conf.setProperty(null, loc);
conf.setProperty("name", name);
if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString());
try {
conf.saveWithError();
} catch (IOException ex) {
throw new IOException(tl("invalidWarpName"));
}
}
@Override
public UUID getLastOwner(String warp) throws WarpNotFoundException {
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp));
if (conf == null) {
throw new WarpNotFoundException();
}
UUID uuid = null;
try {
uuid = UUID.fromString(conf.getString("lastowner"));
}
catch (Exception ex) {}
return uuid;
}
@Override
public void removeWarp(String name) throws Exception {
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
@ -21,57 +22,62 @@ public class Worth implements IConf {
config.load();
}
public BigDecimal getPrice(ItemStack itemStack) {
String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
/**
* Get the value of an item stack from the config.
*
* @param ess The Essentials instance.
* @param itemStack The item stack to look up in the config.
* @return The price from the config.
*/
public BigDecimal getPrice(IEssentials ess, ItemStack itemStack) {
BigDecimal result;
//First check for matches with item name
String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
// Check for matches with data value from stack
// Note that we always default to BigDecimal.ONE.negate(), equivalent to -1
result = config.getBigDecimal("worth." + itemname + "." + itemStack.getDurability(), BigDecimal.ONE.negate());
// Check for matches with data value 0
if (result.signum() < 0) {
final ConfigurationSection itemNameMatch = config.getConfigurationSection("worth." + itemname);
if (itemNameMatch != null && itemNameMatch.getKeys(false).size() == 1) {
result = config.getBigDecimal("worth." + itemname + ".0", BigDecimal.ONE.negate());
}
}
// Check for matches with data value wildcard
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemname + ".*", BigDecimal.ONE.negate());
}
// Check for matches with item name alone
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemname, BigDecimal.ONE.negate());
}
//Now we should check for item ID
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + "." + itemStack.getDurability(), BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
final ConfigurationSection itemNumberMatch = config.getConfigurationSection("worth." + itemStack.getTypeId());
if (itemNumberMatch != null && itemNumberMatch.getKeys(false).size() == 1) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".0", BigDecimal.ONE.negate());
}
}
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".*", BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
result = config.getBigDecimal("worth." + itemStack.getTypeId(), BigDecimal.ONE.negate());
}
//This is to match the old worth syntax
if (result.signum() < 0) {
result = config.getBigDecimal("worth-" + itemStack.getTypeId(), BigDecimal.ONE.negate());
}
if (result.signum() < 0) {
return null;
}
return result;
}
/**
* Get the amount of items to be sold from a player's inventory.
*
* @param ess The Essentials instance.
* @param user The user attempting to sell the item.
* @param is A stack of the item to search the inventory for.
* @param args The amount to try to sell.
* @param isBulkSell Whether or not to try and bulk sell all items.
* @return The amount of items to sell from the player's inventory.
* @throws Exception Thrown if trying to sell air or an invalid amount.
*/
public int getAmount(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception {
if (is == null || is.getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
}
int id = is.getTypeId();
int amount = 0;
if (args.length > 1) {
@ -86,7 +92,7 @@ public class Worth implements IConf {
}
boolean stack = args.length > 1 && args[1].endsWith("s");
boolean requireStack = ess.getSettings().isTradeInStacks(id);
boolean requireStack = ess.getSettings().isTradeInStacks(is.getType());
if (requireStack && !stack) {
throw new Exception(tl("itemMustBeStacked"));
@ -123,14 +129,23 @@ public class Worth implements IConf {
return amount;
}
public void setPrice(ItemStack itemStack, double price) {
if (itemStack.getType().getData() == null) {
config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), price);
} else {
/**
* Set the price of an item and save it to the config.
*
* @param ess The Essentials instance.
* @param itemStack A stack of the item to save.
* @param price The new price of the item.
*/
public void setPrice(IEssentials ess, ItemStack itemStack, double price) {
String path = "worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
// Spigot 1.13+ throws an exception if a 1.13+ plugin even *attempts* to do set data.
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01) && itemStack.getType().getData() == null) {
// Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0.
config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "") + "." + itemStack.getDurability(), price);
path = path + "." + itemStack.getDurability();
}
config.removeProperty("worth-" + itemStack.getTypeId());
config.setProperty(path, price);
config.save();
}

View File

@ -8,6 +8,7 @@ import com.earth2me.essentials.utils.StringUtil;
import com.google.common.base.Charsets;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import org.bukkit.entity.Player;
import java.io.File;
import java.math.BigDecimal;
@ -18,7 +19,7 @@ import java.util.logging.Logger;
/**
* Instead of using this api directly, we recommend to use the register plugin: http://bit.ly/RegisterMethod
* You should use Vault instead of directly using this class.
*/
public class Economy {
public Economy() {
@ -64,7 +65,24 @@ public class Economy {
if (name == null) {
throw new RuntimeException("Economy username cannot be null");
}
return ess.getUser(name);
User user = ess.getUser(name);
if (user == null) {
/*
Attempt lookup using UUID - this prevents balance resets when accessing economy
via Vault during player join.
See: https://github.com/EssentialsX/Essentials/issues/2400
*/
Player player = ess.getServer().getPlayerExact(name);
if (player != null) {
user = ess.getUser(player.getUniqueId());
if (user != null) {
logger.info(String.format("[Economy] Found player %s by UUID %s but not by their actual name - they may have changed their username", name, player.getUniqueId().toString()));
}
}
}
return user;
}
/**
@ -78,7 +96,14 @@ public class Economy {
*/
@Deprecated
public static double getMoney(String name) throws UserDoesNotExistException {
return getMoneyExact(name).doubleValue();
BigDecimal exactAmount = getMoneyExact(name);
double amount = exactAmount.doubleValue();
if (new BigDecimal(amount).compareTo(exactAmount) > 0) {
// closest double is bigger than the exact amount
// -> get the previous double value to not return more money than the user has
amount = Math.nextAfter(amount, Double.NEGATIVE_INFINITY);
}
return amount;
}
public static BigDecimal getMoneyExact(String name) throws UserDoesNotExistException {
@ -178,7 +203,7 @@ public class Economy {
* Divides the balance of a user by a value
*
* @param name Name of the user
* @param value The balance is divided by this value
* @param amount The balance is divided by this value
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
@ -202,7 +227,7 @@ public class Economy {
* Multiplies the balance of a user by a value
*
* @param name Name of the user
* @param value The balance is multiplied by this value
* @param amount The balance is multiplied by this value
*
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance

View File

@ -1,24 +1,163 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
public interface IItemDb {
ItemStack get(final String name, final int quantity) throws Exception;
/**
* Create a stack from the given name with the given quantity.
*
* @param name Item name to look up in the database
* @param quantity Quantity of the item stack
* @return The requested item stack
* @throws Exception if the item stack cannot be created
*/
default ItemStack get(final String name, final int quantity) throws Exception {
final ItemStack stack = get(name.toLowerCase(Locale.ENGLISH));
stack.setAmount(quantity);
return stack;
}
/**
* Create a stack from the given name with the maximum stack size for that material.
*
* @param name Item name to look up in the database
* @return The requested item stack with the maximum stack size
* @throws Exception if the item stack cannot be created
*/
ItemStack get(final String name) throws Exception;
String names(ItemStack item);
/**
* Get a comma-separated string list of up to 15 aliases for the given stack.
*
* @param item Item stack whose names to find
* @return Comma-separated list of up to 15 item names
*/
default String names(ItemStack item) {
List<String> nameList = nameList(item);
if (nameList.size() > 15) {
nameList = nameList.subList(0, 14);
}
return StringUtil.joinList(", ", nameList);
};
/**
* Get a List of all aliases for the given item stack.
*
* @param item Item stack whose names to find
* @return List of all names
*/
List<String> nameList(ItemStack item);
/**
* Get the primary name for the given item stack.
*
* @param item Item stack whose name to find
* @return Primary name of the item
*/
String name(ItemStack item);
/**
* Get all stacks in a given User's inventory that matches the given arguments.
*
* @param user The user with the player inventory to search
* @param args Either an item name, or one of the following:
* hand (default), inventory/invent/all, blocks
* @return A List of all matching ItemStacks
* @throws Exception if the given args are invalid or no blocks are found
*/
List<ItemStack> getMatching(User user, String[] args) throws Exception;
/**
* Serialise an ItemStack into a format that can be decoded by
* {@link #get(String) get} and
* {@link com.earth2me.essentials.MetaItemStack#parseStringMeta(CommandSource, boolean, String[], int, IEssentials)} MetaItemStack#parseStringMeta}.
* Used to encode items for kits.
*
* @param is Stack to serialise
* @return Serialised stack
*/
String serialize(ItemStack is);
/**
* Return names recognised by the database, intended for tab-completion.
*
* @return Collection of all item names
*/
Collection<String> listNames();
/**
* Get the material matching the given legacy ID. Used for conversion from item IDs to
* modern names.
*
* @param id Legacy ID of material to find
* @return Updated material
*/
@Deprecated
default Material getFromLegacyId(int id) {
return getFromLegacy(id, (byte) 0);
}
/**
* Get the legacy ID for the given material.
*
* @param material Material to look up
* @return Legacy ID of given material
* @throws Exception if the ID cannot be looked up
* @deprecated Item IDs are no longer supported.
*/
@Deprecated
int getLegacyId(Material material) throws Exception;
/**
* Convert colon syntax (eg. "13", "1:5") legacy IDs to Material. Used for conversion from
* item IDs to modern names.
*
* @param item Legacy ID in colon syntax.
* @return
*/
default Material getFromLegacy(String item) {
final String[] split = item.split(":");
final int id = Integer.parseInt(split[0]);
byte damage = 0;
if (split.length > 1 && NumberUtil.isInt(split[1])) {
damage = Byte.parseByte(split[1]);
}
return getFromLegacy(id, damage);
}
/**
* Convert legacy ID and damage value to Material. Used for conversion from item IDs to
* modern names.
*
* @param id Legacy ID
* @param damage Damage value
* @return Material
*/
default Material getFromLegacy(final int id, final byte damage) {
return MaterialUtil.convertFromLegacy(id, damage);
}
/**
* Check whether the item database is loaded and ready for use.
*
* @return Whether items have finished loading
*/
boolean isReady();
}

View File

@ -1,11 +1,13 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.commands.WarpNotFoundException;
import org.bukkit.Location;
import java.io.File;
import java.util.Collection;
import java.util.UUID;
public interface IWarps extends IConf {
@ -54,6 +56,25 @@ public interface IWarps extends IConf {
*/
void setWarp(String name, Location loc) throws Exception;
/**
* Set a warp
*
* @param user - User of warp
* @param name - Name of warp
* @param loc - Location of warp
*
* @throws Exception
*/
void setWarp(IUser user, String name, Location loc) throws Exception;
/**
* Gets Lastowner UUID
*
* @param name - Name of warp
*
* @throws WarpNotFoundException
*/
UUID getLastOwner(String warp) throws WarpNotFoundException;
/**
* Check to see if the file is empty
*

View File

@ -79,6 +79,7 @@ public class Commandafk extends EssentialsCommand {
if (!msg.isEmpty()) {
ess.broadcastMessage(user, msg);
}
user.setDisplayNick(); // Set this again after toggling
}
@Override

View File

@ -17,9 +17,17 @@ public class Commandback extends EssentialsCommand {
if (user.getLastLocation() == null) {
throw new Exception(tl("noLocationFound"));
}
if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getLastLocation().getWorld().getName())) {
throw new Exception(tl("noPerm", "essentials.worlds." + user.getLastLocation().getWorld().getName()));
String lastWorldName = user.getLastLocation().getWorld().getName();
if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.worlds." + lastWorldName));
}
if (!user.isAuthorized("essentials.back.into." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.back.into." + lastWorldName));
}
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
user.getTeleport().back(charge);

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.BanList;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@ -14,7 +15,6 @@ import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
//TODO: Add kick to online players matching ip ban.
public class Commandbanip extends EssentialsCommand {
public Commandbanip() {
super("banip");
@ -51,9 +51,17 @@ public class Commandbanip extends EssentialsCommand {
banReason = tl("defaultBanReason");
}
String banDisplay = tl("banFormat", banReason, senderName);
ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName);
server.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderName, ipAddress, banReason));
for (Player player : ess.getServer().getOnlinePlayers()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
player.kickPlayer(banDisplay);
}
}
ess.broadcastMessage("essentials.banip.notify", tl("playerBanIpAddress", senderName, ipAddress, banReason));
}

View File

@ -27,6 +27,8 @@ public class Commandbigtree extends EssentialsCommand {
tree = TreeType.BIG_TREE;
} else if (args.length > 0 && args[0].equalsIgnoreCase("jungle")) {
tree = TreeType.JUNGLE;
} else if (args.length > 0 && args[0].equalsIgnoreCase("darkoak")) {
tree = TreeType.DARK_OAK;
} else {
throw new NotEnoughArgumentsException();
}
@ -44,7 +46,7 @@ public class Commandbigtree extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1) {
return Lists.newArrayList("redwood", "tree", "jungle");
return Lists.newArrayList("redwood", "tree", "jungle", "darkoak");
} else {
return Collections.emptyList();
}

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.Server;
@ -15,11 +16,13 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandbook extends EssentialsCommand {
private static final Material WRITABLE_BOOK = EnumUtil.getMaterial("WRITABLE_BOOK", "BOOK_AND_QUILL");
public Commandbook() {
super("book");
}
//TODO: Translate this
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack item = user.getItemInHand();
@ -45,7 +48,7 @@ public class Commandbook extends EssentialsCommand {
}
} else {
if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) {
ItemStack newItem = new ItemStack(Material.BOOK_AND_QUILL, item.getAmount());
ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount());
newItem.setItemMeta(bmeta);
InventoryWorkaround.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("editBookContents"));
@ -53,7 +56,7 @@ public class Commandbook extends EssentialsCommand {
throw new Exception(tl("denyBookEdit"));
}
}
} else if (item.getType() == Material.BOOK_AND_QUILL) {
} else if (item.getType() == WRITABLE_BOOK) {
BookMeta bmeta = (BookMeta) item.getItemMeta();
if (!user.isAuthorized("essentials.book.author")) {
bmeta.setAuthor(player);

View File

@ -27,7 +27,25 @@ public class Commandbroadcastworld extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
sendBroadcast(user.getWorld().getName(), user.getDisplayName(), getFinalArg(args, 0));
World world = user.getWorld();
String message = getFinalArg(args, 0);
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
World argWorld = ess.getWorld(args[0]);
if (argWorld != null) {
world = argWorld;
message = getFinalArg(args, 1);
}
}
if (world == null) {
world = user.getWorld();
message = getFinalArg(args, 0);
}
sendBroadcast(world.getName(), user.getDisplayName(), message);
}
@Override
@ -43,6 +61,9 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (world == null) {
throw new Exception(tl("invalidWorld"));
}
if (message.isEmpty()) {
throw new NotEnoughArgumentsException();
}
sendToWorld(world, tl("broadcast", FormatUtil.replaceFormat(message).replace("\\n", "\n"), name));
}
@ -63,7 +84,15 @@ public class Commandbroadcastworld extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
return Collections.emptyList(); // The argument is only for non-players
if (args.length == 1 && ess.getSettings().isAllowWorldInBroadcastworld()) {
List<String> worlds = Lists.newArrayList();
for (World world : server.getWorlds()) {
worlds.add(world.getName());
}
return worlds;
} else {
return Collections.emptyList();
}
}
@Override

View File

@ -8,15 +8,12 @@ import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.*;
public class Commandclearinventory extends EssentialsCommand {
@ -87,6 +84,7 @@ public class Commandclearinventory extends EssentialsCommand {
short data = -1;
int type = -1;
int amount = -1;
final Set<Material> mats = new HashSet<>();
if (args.length > (offset + 1) && NumberUtil.isInt(args[(offset + 1)])) {
amount = Integer.parseInt(args[(offset + 1)]);
@ -95,15 +93,15 @@ public class Commandclearinventory extends EssentialsCommand {
if (args[offset].equalsIgnoreCase("**")) {
type = -2;
} else if (!args[offset].equalsIgnoreCase("*")) {
final String[] split = args[offset].split(":");
final ItemStack item = ess.getItemDb().get(split[0]);
type = item.getTypeId();
final String[] split = args[offset].split(",");
if (split.length > 1 && NumberUtil.isInt(split[1])) {
data = Short.parseShort(split[1]);
} else {
data = item.getDurability();
for (String name : split) {
try {
mats.add(ess.getItemDb().get(name).getType());
} catch (Exception ignored) {}
}
type = 1;
}
}
@ -113,40 +111,37 @@ public class Commandclearinventory extends EssentialsCommand {
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
}
InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null);
} else if (type == -2) // type -2 represents double wildcard or all items and armor
{
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
}
InventoryWorkaround.clearInventoryNoArmor(player.getInventory());
InventoryWorkaround.setItemInOffHand(player, null);
player.getInventory().setArmorContents(null);
} else {
if (data == -1) // data -1 means that all subtypes will be cleared
{
ItemStack stack = new ItemStack(type);
if (showExtended) {
sender.sendMessage(tl("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
player.getInventory().clear(type, data);
} else if (amount == -1) // amount -1 means all items will be cleared
{
ItemStack stack = new ItemStack(type, BASE_AMOUNT, data);
ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
final int removedAmount = (BASE_AMOUNT - removedStack.getAmount());
if (removedAmount > 0 || showExtended) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
} else {
if (amount < 0) {
amount = 1;
}
ItemStack stack = new ItemStack(type, amount, data);
if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
for (Material mat : mats) {
if (amount == -1) // amount -1 means all items will be cleared
{
ItemStack stack = new ItemStack(mat, BASE_AMOUNT, data);
ItemStack removedStack = player.getInventory().removeItem(stack).get(0);
final int removedAmount = (BASE_AMOUNT - removedStack.getAmount());
if (removedAmount > 0 || showExtended) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
if (amount < 0) {
amount = 1;
}
ItemStack stack = new ItemStack(mat, amount);
if (player.getInventory().containsAtLeast(stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
} else {
if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
}
}
}
}

View File

@ -16,23 +16,23 @@ public class Commandcompass extends EssentialsCommand {
final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360;
String dir;
if (bearing < 23) {
dir = "N";
dir = tl("north");
} else if (bearing < 68) {
dir = "NE";
dir = tl("northEast");
} else if (bearing < 113) {
dir = "E";
dir = tl("east");
} else if (bearing < 158) {
dir = "SE";
dir = tl("southEast");
} else if (bearing < 203) {
dir = "S";
dir = tl("south");
} else if (bearing < 248) {
dir = "SW";
dir = tl("southWest");
} else if (bearing < 293) {
dir = "W";
dir = tl("west");
} else if (bearing < 338) {
dir = "NW";
dir = tl("northWest");
} else {
dir = "N";
dir = tl("north");
}
user.sendMessage(tl("compassBearing", dir, bearing));
}

View File

@ -2,9 +2,8 @@ package com.earth2me.essentials.commands;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;
import com.google.gson.JsonObject;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
@ -24,12 +23,10 @@ import org.yaml.snakeyaml.representer.Representer;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -37,8 +34,8 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandcreatekit extends EssentialsCommand {
private static final String PASTE_URL = "https://api.github.com/gists";
private static final String SHORTENER_URL = "https://git.io";
private static final String PASTE_URL = "https://hastebin.com/";
private static final String PASTE_UPLOAD_URL = PASTE_URL + "documents";
private static final Gson GSON = new Gson();
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
@ -72,7 +69,7 @@ public class Commandcreatekit extends EssentialsCommand {
}
// Some users might want to directly write to config knowing the consequences. *shrug*
if (!ess.getSettings().isPastebinCreateKit()) {
ess.getSettings().addKit(kitname, list, delay);
ess.getKits().addKit(kitname, list, delay);
user.sendMessage(tl("createdKit", kitname, list.size(), delay));
} else {
ConfigurationSection config = new MemoryConfiguration();
@ -83,34 +80,22 @@ public class Commandcreatekit extends EssentialsCommand {
String fileContents = "# Copy the kit code below into the kits section in your config.yml file\n";
fileContents += yaml.dump(config.getValues(false));
gist(user.getSource(), kitname, delay, fileContents);
uploadPaste(user.getSource(), kitname, delay, fileContents);
}
}
/**
* SEE https://developer.github.com/v3/gists/#create-a-gist
*/
private void gist(final CommandSource sender, final String kitName, final long delay, final String contents) {
private void uploadPaste(final CommandSource sender, final String kitName, final long delay, final String contents) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_URL).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "EssentialsX plugin");
try (OutputStream os = connection.getOutputStream()) {
StringWriter sw = new StringWriter();
new JsonWriter(sw).beginObject()
.name("description").value(sender.getSender().getName() + ": /createkit " + kitName)
.name("public").value(false)
.name("files")
.beginObject().name("kit.yml")
.beginObject().name("content").value(contents)
.endObject()
.endObject()
.endObject();
os.write(sw.toString().getBytes());
os.write(contents.getBytes(Charsets.UTF_8));
}
// Error
if (connection.getResponseCode() >= 400) {
@ -120,25 +105,10 @@ public class Commandcreatekit extends EssentialsCommand {
return;
}
// Read URl
Map<String, String> map = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8),
new TypeToken<Map<String, Object>>() {}.getType());
String pasteUrl = map.get("html_url");
// Read URL
JsonObject object = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), JsonObject.class);
String pasteUrl = PASTE_URL + object.get("key").getAsString();
connection.disconnect();
/* ================================
* >> Shorten URL to fit in chat
* ================================ */
{
connection = (HttpURLConnection) new URL(SHORTENER_URL).openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
pasteUrl = "url=" + pasteUrl;
try (OutputStream os = connection.getOutputStream()) {
os.write(pasteUrl.getBytes());
}
pasteUrl = connection.getHeaderField("Location");
}
String separator = tl("createKitSeparator");
String delayFormat = "0";

View File

@ -19,6 +19,10 @@ public class Commanddeljail extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
if (ess.getJails().getJail(args[0]) == null) {
throw new Exception(tl("jailNotExist"));
}
ess.getJails().removeJail(args[0]);
sender.sendMessage(tl("deleteJail", args[0]));
}

View File

@ -0,0 +1,20 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commanddisposal extends EssentialsCommand {
public Commanddisposal() {
super("disposal");
}
@Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
user.sendMessage(tl("openingDisposal"));
user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, "Disposal"));
}
}

View File

@ -71,7 +71,7 @@ public class Commandeco extends EssentialsLoopCommand {
private void take(BigDecimal amount, final User player, final CommandSource sender) throws ChargeException {
BigDecimal money = player.getMoney();
BigDecimal minBalance = ess.getSettings().getMinMoney();
if (money.subtract(amount).compareTo(minBalance) > 0) {
if (money.subtract(amount).compareTo(minBalance) >= 0) {
player.takeMoney(amount, sender);
} else if (sender == null) {
try {

View File

@ -46,7 +46,7 @@ public class Commandenchant extends EssentialsCommand {
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray())));
}
int level = -1;
int level = 1;
if (args.length > 1) {
try {
level = Integer.parseInt(args[1]);

View File

@ -4,10 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.EssentialsUpgrade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.UserMap;
import com.earth2me.essentials.metrics.Metrics;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.FloatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.*;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.bukkit.Material;
@ -15,19 +12,19 @@ import org.bukkit.Server;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import static com.earth2me.essentials.I18n.tl;
// This command has 4 undocumented behaviours #EasterEgg
public class Commandessentials extends EssentialsCommand {
private final Sound NOTE_HARP = EnumUtil.valueOf(Sound.class, "BLOCK_NOTE_HARP", "NOTE_PIANO");
public Commandessentials() {
super("essentials");
}
@ -35,6 +32,27 @@ public class Commandessentials extends EssentialsCommand {
private transient int taskid;
private final transient Map<Player, Block> noteBlocks = new HashMap<Player, Block>();
private final List<String> versionPlugins = Arrays.asList(
"Vault",
"LuckPerms",
"PermissionsEx",
"GroupManager"
);
private final List<String> officialPlugins = Arrays.asList(
"EssentialsAntiBuild",
"EssentialsChat",
"EssentialsGeoIP",
"EssentialsProtect",
"EssentialsSpawn",
"EssentialsXMPP"
);
private final List<String> warnPlugins = Arrays.asList(
"PermissionsEx",
"GroupManager"
);
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
@ -47,14 +65,14 @@ public class Commandessentials extends EssentialsCommand {
run_moo(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("reset")) {
run_reset(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("opt-out")) {
run_optout(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("cleanup")) {
run_cleanup(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("uuidconvert")) {
run_uuidconvert(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("uuidtest")) {
run_uuidtest(server, sender, commandLabel, args);
} else if (args[0].equalsIgnoreCase("version")) {
run_version(server, sender, commandLabel, args);
} else {
run_reload(server, sender, commandLabel, args);
}
@ -137,15 +155,9 @@ public class Commandessentials extends EssentialsCommand {
if (note == null || note.isEmpty()) {
return;
}
Sound noteHarp;
try {
noteHarp = Sound.valueOf("NOTE_PIANO"); // pre-1.9, referenced internally as note.harp
} catch (IllegalArgumentException e) {
noteHarp = Sound.valueOf("BLOCK_NOTE_HARP"); // 1.9
}
for (Player onlinePlayer : ess.getOnlinePlayers()) {
onlinePlayer.playSound(onlinePlayer.getLocation(), noteHarp, 1, noteMap.get(note));
onlinePlayer.playSound(onlinePlayer.getLocation(), NOTE_HARP, 1, noteMap.get(note));
}
}
}, 20, 2);
@ -165,12 +177,8 @@ public class Commandessentials extends EssentialsCommand {
private final String[] playerMoo = new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."};
private void run_moo(final Server server, final CommandSource sender, final String command, final String args[]) {
Sound moo;
try {
moo = Sound.valueOf("COW_IDLE"); // pre-1.9
} catch (IllegalArgumentException e) {
moo = Sound.valueOf("ENTITY_COW_MILK"); // 1.9
}
Sound moo = EnumUtil.valueOf(Sound.class, "COW_IDLE", "ENTITY_COW_MILK");
if (args.length == 2 && args[1].equals("moo")) {
for (String s : consoleMoo) {
logger.info(s);
@ -191,19 +199,6 @@ public class Commandessentials extends EssentialsCommand {
}
}
private void run_optout(final Server server, final CommandSource sender, final String command, final String args[]) {
final Metrics metrics = ess.getMetrics();
sender.sendMessage("Essentials collects simple metrics to highlight which features to concentrate work on in the future.");
if (metrics.isOptOut()) {
metrics.enable();
} else {
metrics.disable();
}
sender.sendMessage("Anonymous Metrics are now " + (metrics.isOptOut() ? "disabled" : "enabled") + " for EssentialsX until server restart.");
sender.sendMessage("To " + (metrics.isOptOut() ? "disable" : "enable") + " them for all plugins permanently, see the bStats config.");
}
private void run_cleanup(final Server server, final CommandSource sender, final String command, final String args[]) throws Exception {
if (args.length < 2 || !NumberUtil.isInt(args[1])) {
sender.sendMessage("This sub-command will delete users who havent logged in in the last <days> days.");
@ -307,6 +302,69 @@ public class Commandessentials extends EssentialsCommand {
sender.sendMessage("Offline Mode UUID: " + offlineuuid.toString());
}
private void run_version(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.version")) return;
boolean isMismatched = false;
boolean isVaultInstalled = false;
boolean isUnsupported = false;
final boolean isServerSupported = VersionUtil.isServerSupported();
final PluginManager pm = server.getPluginManager();
final String essVer = pm.getPlugin("Essentials").getDescription().getVersion();
sender.sendMessage(tl(isServerSupported ? "versionOutputFine" : "versionOutputWarn", "Server", server.getBukkitVersion() + " " + server.getVersion()));
sender.sendMessage(tl("versionOutputFine", "EssentialsX", essVer));
for (Plugin plugin : pm.getPlugins()) {
final PluginDescriptionFile desc = plugin.getDescription();
String name = desc.getName();
String version = desc.getVersion();
if (name.startsWith("Essentials") && !name.equalsIgnoreCase("Essentials")) {
if (officialPlugins.contains(name)) {
name = name.replace("Essentials", "EssentialsX");
if (!version.equalsIgnoreCase(essVer)) {
isMismatched = true;
sender.sendMessage(tl("versionOutputWarn", name, version));
} else {
sender.sendMessage(tl("versionOutputFine", name, version));
}
} else {
sender.sendMessage(tl("versionOutputUnsupported", name, version));
isUnsupported = true;
}
}
if (versionPlugins.contains(name)) {
if (warnPlugins.contains(name)) {
sender.sendMessage(tl("versionOutputUnsupported", name, version));
isUnsupported = true;
} else {
sender.sendMessage(tl("versionOutputFine", name, version));
}
}
if (name.equals("Vault")) isVaultInstalled = true;
}
if (isMismatched) {
sender.sendMessage(tl("versionMismatchAll"));
}
if (!isVaultInstalled) {
sender.sendMessage(tl("versionOutputVaultMissing"));
}
if (isUnsupported) {
sender.sendMessage(tl("versionOutputUnsupportedPlugins"));
}
if (!VersionUtil.isServerSupported()) {
sender.sendMessage(tl("serverUnsupported"));
}
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
@ -316,10 +374,10 @@ public class Commandessentials extends EssentialsCommand {
//options.add("nya");
//options.add("moo");
options.add("reset");
options.add("opt-out");
options.add("cleanup");
//options.add("uuidconvert");
//options.add("uuidtest");
options.add("version");
return options;
} else if (args[0].equalsIgnoreCase("debug")) {
// No args
@ -333,8 +391,6 @@ public class Commandessentials extends EssentialsCommand {
if (args.length == 2) {
return getPlayers(server, sender);
}
} else if (args[0].equalsIgnoreCase("opt-out")) {
// No args
} else if (args[0].equalsIgnoreCase("cleanup")) {
if (args.length == 2) {
return COMMON_DURATIONS;
@ -349,6 +405,8 @@ public class Commandessentials extends EssentialsCommand {
if (args.length == 2) {
return getPlayers(server, sender);
}
} else if (args[0].equalsIgnoreCase("version")) {
// No args
} else {
// No args
}

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.DyeColor;
@ -43,8 +44,8 @@ public class Commandfirework extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getBase().getItemInHand();
if (stack.getType() == Material.FIREWORK) {
final ItemStack stack = user.getItemInHand();
if (MaterialUtil.isFirework(stack.getType())) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("clear")) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();

View File

@ -31,9 +31,9 @@ public class Commandgive extends EssentialsCommand {
}
ItemStack stack = ess.getItemDb().get(args[1]);
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (sender.isPlayer() && (ess.getSettings().permissionBasedItemSpawn() ? (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-all") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + itemname) && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.exempt") && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getTypeId())))) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname));
}

View File

@ -30,7 +30,7 @@ public class Commandgod extends EssentialsToggleCommand {
}
final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(controller, user, enabled);
final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(user, controller, enabled);
ess.getServer().getPluginManager().callEvent(godEvent);
if (!godEvent.isCancelled()) {
user.setGodModeEnabled(enabled);

View File

@ -33,8 +33,8 @@ public class Commandhat extends EssentialsCommand {
user.sendMessage(tl("hatRemoved"));
}
} else {
if (user.getBase().getItemInHand().getType() != Material.AIR) {
final ItemStack hand = user.getBase().getItemInHand();
final ItemStack hand = user.getItemInHand();
if (hand != null && hand.getType() != Material.AIR) {
if (hand.getType().getMaxDurability() == 0) {
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();

View File

@ -25,12 +25,14 @@ public class Commanditem extends EssentialsCommand {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
ItemStack stack = ess.getItemDb().get(args[0]);
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (ess.getSettings().permissionBasedItemSpawn() ? (!user.isAuthorized("essentials.itemspawn.item-all") && !user.isAuthorized("essentials.itemspawn.item-" + itemname) && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId()))) {
if (!user.canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname));
}
try {
if (args.length > 1 && Integer.parseInt(args[1]) > 0) {
stack.setAmount(Integer.parseInt(args[1]));

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@ -21,9 +22,9 @@ public class Commanditemdb extends EssentialsCommand {
ItemStack itemStack = null;
boolean itemHeld = false;
if (args.length < 1) {
if (sender.isPlayer()) {
if (sender.isPlayer() && sender.getPlayer() != null) {
itemHeld = true;
itemStack = sender.getPlayer().getItemInHand();
itemStack = ess.getUser(sender.getPlayer()).getItemInHand();
}
if (itemStack == null) {
throw new NotEnoughArgumentsException();
@ -31,7 +32,19 @@ public class Commanditemdb extends EssentialsCommand {
} else {
itemStack = ess.getItemDb().get(args[0]);
}
sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemStack.getTypeId() + ":" + Integer.toString(itemStack.getDurability())));
String itemId = "none";
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
itemId = itemStack.getType().getId() + ":" + itemStack.getDurability();
}
sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemId));
// Don't send IDs twice
if (!tl("itemType").contains("{1}") && !itemId.equals("none")) {
sender.sendMessage(tl("itemId", itemId));
}
if (itemHeld && itemStack.getType() != Material.AIR) {
int maxuses = itemStack.getType().getMaxDurability();

View File

@ -4,6 +4,10 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Server;
import java.util.Collection;
import static com.earth2me.essentials.I18n.tl;
public class Commandjails extends EssentialsCommand {
public Commandjails() {
@ -12,6 +16,10 @@ public class Commandjails extends EssentialsCommand {
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
sender.sendMessage("§7" + StringUtil.joinList(" ", ess.getJails().getList()));
if (ess.getJails().getCount() < 1) {
sender.sendMessage(tl("noJailsDefined"));
} else {
sender.sendMessage(tl("jailList", StringUtil.joinList(" ", ess.getJails().getList())));
}
}
}

View File

@ -20,7 +20,9 @@ public class Commandkickall extends EssentialsCommand {
for (Player onlinePlayer : ess.getOnlinePlayers()) {
if (!sender.isPlayer() || !onlinePlayer.getName().equalsIgnoreCase(sender.getPlayer().getName())) {
onlinePlayer.kickPlayer(kickReason);
if (!ess.getUser(onlinePlayer).isAuthorized("essentials.kickall.exempt")) {
onlinePlayer.kickPlayer(kickReason);
}
}
}
sender.sendMessage(tl("kickedAll"));

View File

@ -23,7 +23,7 @@ public class Commandkit extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
final String kitList = Kit.listKits(ess, user);
final String kitList = ess.getKits().listKits(ess, user);
user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException();
} else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) {
@ -39,7 +39,7 @@ public class Commandkit extends EssentialsCommand {
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 2) {
final String kitList = Kit.listKits(ess, null);
final String kitList = ess.getKits().listKits(ess, null);
sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits"));
throw new NoChargeException();
} else {
@ -106,7 +106,7 @@ public class Commandkit extends EssentialsCommand {
if (args.length == 1) {
List<String> options = new ArrayList<>();
// TODO: Move all of this to its own method
for (String kitName : ess.getSettings().getKits().getKeys(false)) {
for (String kitName : ess.getKits().getKits().getKeys(false)) {
if (!user.isAuthorized("essentials.kits." + kitName)) { // Only check perm, not time or money
continue;
}
@ -123,7 +123,7 @@ public class Commandkit extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return new ArrayList<>(ess.getSettings().getKits().getKeys(false)); // TODO: Move this to its own method
return new ArrayList<>(ess.getKits().getKits().getKeys(false)); // TODO: Move this to its own method
} else if (args.length == 2) {
return getPlayers(server, sender);
} else {

View File

@ -56,8 +56,7 @@ public class Commandmail extends EssentialsCommand {
throw new Exception(tl("playerNeverOnServer", args[1]));
}
String mail = tl("mailFormat", user.getName(), StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2))));
mail = FormatUtil.formatMessage(user, "essentials.mail", mail);
String mail = tl("mailFormat", user.getName(), FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2)))));
if (mail.length() > 1000) {
throw new Exception(tl("mailTooLong"));
}
@ -82,7 +81,8 @@ public class Commandmail extends EssentialsCommand {
if (!user.isAuthorized("essentials.mail.sendall")) {
throw new Exception(tl("noPerm", "essentials.mail.sendall"));
}
ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(), FormatUtil.stripFormat(getFinalArg(args, 1)))));
ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(),
FormatUtil.formatMessage(user, "essentials.mail", StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 1)))))));
user.sendMessage(tl("mailSent"));
return;
}
@ -105,11 +105,11 @@ public class Commandmail extends EssentialsCommand {
if (u == null) {
throw new Exception(tl("playerNeverOnServer", args[1]));
}
u.addMail(tl("mailFormat", "Server", getFinalArg(args, 2)));
u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 2))));
sender.sendMessage(tl("mailSent"));
return;
} else if (args.length >= 2 && "sendall".equalsIgnoreCase(args[0])) {
ess.runTaskAsynchronously(new SendAll(tl("mailFormat", "Server", getFinalArg(args, 1))));
ess.runTaskAsynchronously(new SendAll(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 1)))));
sender.sendMessage(tl("mailSent"));
return;
} else if (args.length >= 2) {
@ -118,7 +118,7 @@ public class Commandmail extends EssentialsCommand {
if (u == null) {
throw new Exception(tl("playerNeverOnServer", args[0]));
}
u.addMail(tl("mailFormat", "Server", getFinalArg(args, 1)));
u.addMail(tl("mailFormat", "Server", FormatUtil.replaceFormat(getFinalArg(args, 1))));
sender.sendMessage(tl("mailSent"));
return;
}

View File

@ -16,15 +16,16 @@ public class Commandmore extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getBase().getItemInHand();
final ItemStack stack = user.getItemInHand();
if (stack == null) {
throw new Exception(tl("cantSpawnItem", "Air"));
}
if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks")) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) {
throw new Exception(tl("fullStack"));
}
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (ess.getSettings().permissionBasedItemSpawn() ? (!user.isAuthorized("essentials.itemspawn.item-all") && !user.isAuthorized("essentials.itemspawn.item-" + itemname) && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId()))) {
if (!user.canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname));
}
if (user.isAuthorized("essentials.oversizedstacks")) {

View File

@ -55,16 +55,16 @@ public class Commandnick extends EssentialsLoopCommand {
@Override
protected void updatePlayer(final Server server, final CommandSource sender, final User target, final String[] args) throws NotEnoughArgumentsException {
final String nick = args[0];
if (target.getName().equalsIgnoreCase(nick)) {
if ("off".equalsIgnoreCase(nick)) {
setNickname(server, sender, target, null);
target.sendMessage(tl("nickNoMore"));
} else if (target.getName().equalsIgnoreCase(nick)) {
String oldName = target.getDisplayName();
setNickname(server, sender, target, nick);
if (!target.getDisplayName().equalsIgnoreCase(oldName)) {
target.sendMessage(tl("nickNoMore"));
}
target.sendMessage(tl("nickSet", target.getDisplayName()));
} else if ("off".equalsIgnoreCase(nick)) {
setNickname(server, sender, target, null);
target.sendMessage(tl("nickNoMore"));
} else if (nickInUse(server, target, nick)) {
throw new NotEnoughArgumentsException(tl("nickInUse"));
} else {
@ -75,7 +75,7 @@ public class Commandnick extends EssentialsLoopCommand {
private String formatNickname(final User user, final String nick) throws Exception {
String newNick = user == null ? FormatUtil.replaceFormat(nick) : FormatUtil.formatString(user, "essentials.nick", nick);
if (!newNick.matches("^[a-zA-Z_0-9\u00a7]+$")) {
if (!newNick.matches("^[a-zA-Z_0-9\u00a7]+$") && user != null && !user.isAuthorized("essentials.nick.allowunsafe")) {
throw new Exception(tl("nickNamesAlpha"));
} else if (getNickLength(newNick) > ess.getSettings().getMaxNickLength()) {
throw new Exception(tl("nickTooLong"));

View File

@ -31,7 +31,7 @@ public class Commandrealname extends EssentialsCommand {
final String displayName = FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (displayName.contains(whois)) {
foundUser = true;
sender.sendMessage(u.getDisplayName() + " " + tl("is") + " " + u.getName());
sender.sendMessage(tl("realName", u.getDisplayName(), u.getName()));
}
}
if (!foundUser) {

View File

@ -2,7 +2,9 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.*;
@ -19,13 +21,20 @@ import net.ess3.nms.refl.ReflUtil;
public class Commandrecipe extends EssentialsCommand {
private static final Material FIREWORK_ROCKET = EnumUtil.getMaterial("FIREWORK_ROCKET", "FIREWORK");
private static final Material FIREWORK_STAR = EnumUtil.getMaterial("FIREWORK_STAR", "FIREWORK_CHARGE");
private static final Material GUNPOWDER = EnumUtil.getMaterial("GUNPOWDER", "SULPHUR");
public Commandrecipe() {
super("recipe");
}
private void disableCommandForVersion1_12() throws Exception {
if (ReflUtil.getNmsVersionObject().equals(ReflUtil.V1_12_R1)) {
throw new Exception("/recipe is temporarily disabled. Please use the recipe book in your inventory.");
VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion();
if (version.isHigherThanOrEqualTo(VersionUtil.v1_12_0_R01)
&& !ess.getSettings().isForceEnableRecipe()) {
throw new Exception("Please use the recipe book in your inventory.");
}
}
@ -64,11 +73,11 @@ public class Commandrecipe extends EssentialsCommand {
} else if (selectedRecipe instanceof ShapedRecipe) {
shapedRecipe(sender, (ShapedRecipe) selectedRecipe, sender.isPlayer());
} else if (selectedRecipe instanceof ShapelessRecipe) {
if (recipesOfType.size() == 1 && itemType.getType() == Material.FIREWORK) {
if (recipesOfType.size() == 1 && (itemType.getType() == FIREWORK_ROCKET)) {
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType);
shapelessRecipe.addIngredient(Material.SULPHUR);
shapelessRecipe.addIngredient(GUNPOWDER);
shapelessRecipe.addIngredient(Material.PAPER);
shapelessRecipe.addIngredient(Material.FIREWORK_CHARGE);
shapelessRecipe.addIngredient(FIREWORK_STAR);
shapelessRecipe(sender, shapelessRecipe, sender.isPlayer());
} else {
shapelessRecipe(sender, (ShapelessRecipe) selectedRecipe, sender.isPlayer());

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.StringUtil;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists;
import net.ess3.api.IUser;
import org.bukkit.Material;
@ -38,7 +39,7 @@ public class Commandrepair extends EssentialsCommand {
}
public void repairHand(User user) throws Exception {
final ItemStack item = user.getBase().getItemInHand();
final ItemStack item = user.getItemInHand();
if (item == null || item.getType().isBlock() || item.getDurability() == 0) {
throw new Exception(tl("repairInvalidType"));
}
@ -48,7 +49,7 @@ public class Commandrepair extends EssentialsCommand {
}
final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH);
final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess);
final Trade charge = getCharge(item.getType());
charge.isAffordableFor(user);
@ -76,7 +77,7 @@ public class Commandrepair extends EssentialsCommand {
}
private void repairItem(final ItemStack item) throws Exception {
final Material material = Material.getMaterial(item.getTypeId());
final Material material = item.getType();
if (material.isBlock() || material.getMaxDurability() < 1) {
throw new Exception(tl("repairInvalidType"));
}
@ -88,13 +89,15 @@ public class Commandrepair extends EssentialsCommand {
item.setDurability((short) 0);
}
private void repairItems(final ItemStack[] items, final IUser user, final List<String> repaired) {
private void repairItems(final ItemStack[] items, final IUser user, final List<String> repaired) throws Exception {
for (ItemStack item : items) {
if (item == null || item.getType().isBlock() || item.getDurability() == 0) {
continue;
}
final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH);
final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess);
final Trade charge = getCharge(item.getType());
try {
charge.isAffordableFor(user);
} catch (ChargeException ex) {
@ -119,6 +122,16 @@ public class Commandrepair extends EssentialsCommand {
}
}
private Trade getCharge(final Material material) {
final String itemName = material.toString().toLowerCase(Locale.ENGLISH);
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_13_0_R01)) {
final int itemId = material.getId();
return new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + itemId, new Trade("repair-item", ess), ess), ess);
} else {
return new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-item", ess), ess);
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
if (args.length == 1) {

View File

@ -28,16 +28,16 @@ public class Commandseen extends EssentialsCommand {
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
seen(server, sender, commandLabel, args, true, true, true);
seen(server, sender, commandLabel, args, true, true, true, true);
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
seen(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.extra"), user.isAuthorized("essentials.seen.ipsearch"));
seen(server, user.getSource(), commandLabel, args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.ip"), user.isAuthorized("essentials.seen.location"), user.isAuthorized("essentials.seen.ipsearch"));
}
protected void seen(final Server server, final CommandSource sender, final String commandLabel, final String[] args,
final boolean showBan, final boolean extra, final boolean ipLookup) throws Exception {
final boolean showBan, final boolean showIp, final boolean showLocation, final boolean ipLookup) throws Exception {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
@ -80,23 +80,23 @@ public class Commandseen extends EssentialsCommand {
if (user == null) {
throw new PlayerNotFoundException();
}
showSeenMessage(server, sender, user, showBan, extra);
showSeenMessage(server, sender, user, showBan, showIp, showLocation);
}
});
} else {
showSeenMessage(server, sender, player, showBan, extra);
showSeenMessage(server, sender, player, showBan, showIp, showLocation);
}
}
private void showSeenMessage(Server server, CommandSource sender, User player, boolean showBan, boolean extra) throws Exception {
private void showSeenMessage(Server server, CommandSource sender, User player, boolean showBan, boolean showIp, boolean showLocation) throws Exception {
if (player.getBase().isOnline() && canInteractWith(sender, player)) {
seenOnline(server, sender, player, showBan, extra);
seenOnline(server, sender, player, showBan, showIp, showLocation);
} else {
seenOffline(server, sender, player, showBan, extra);
seenOffline(server, sender, player, showBan, showIp, showLocation);
}
}
private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean extra) throws Exception {
private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean showIp, final boolean showLocation) throws Exception {
user.setDisplayNick();
sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin())));
@ -128,12 +128,12 @@ public class Commandseen extends EssentialsCommand {
if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) {
sender.sendMessage(tl("whoisGeoLocation", location));
}
if (extra) {
if (showIp) {
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
}
}
private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean extra) throws Exception {
private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean showIp, final boolean showLocation) throws Exception {
user.setDisplayNick();
if (user.getLastLogout() > 0) {
sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout())));
@ -177,10 +177,12 @@ public class Commandseen extends EssentialsCommand {
if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) {
sender.sendMessage(tl("whoisGeoLocation", location));
}
if (extra) {
if (showIp) {
if (!user.getLastLoginAddress().isEmpty()) {
sender.sendMessage(tl("whoisIPAddress", user.getLastLoginAddress()));
}
}
if (showLocation) {
final Location loc = user.getLogoutLocation();
if (loc != null) {
sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));

View File

@ -69,7 +69,7 @@ public class Commandsell extends EssentialsCommand {
private BigDecimal sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception {
int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell);
BigDecimal worth = ess.getWorth().getPrice(is);
BigDecimal worth = ess.getWorth().getPrice(ess, is);
if (worth == null) {
throw new Exception(tl("itemCannotBeSold"));

View File

@ -36,7 +36,7 @@ public class Commandsetwarp extends EssentialsCommand {
}
if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) {
warps.setWarp(args[0], loc);
warps.setWarp(user, args[0], loc);
} else {
throw new Exception(tl("warpOverwrite"));
}

View File

@ -31,7 +31,7 @@ public class Commandsetworth extends EssentialsCommand {
price = args[1];
}
ess.getWorth().setPrice(stack, FloatUtil.parseDouble(price));
ess.getWorth().setPrice(ess, stack, FloatUtil.parseDouble(price));
user.sendMessage(tl("worthSet"));
}
@ -42,7 +42,7 @@ public class Commandsetworth extends EssentialsCommand {
}
ItemStack stack = ess.getItemDb().get(args[0]);
ess.getWorth().setPrice(stack, FloatUtil.parseDouble(args[1]));
ess.getWorth().setPrice(ess, stack, FloatUtil.parseDouble(args[1]));
sender.sendMessage(tl("worthSet"));
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.Kit;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Settings;
import org.bukkit.Server;
import java.util.ArrayList;
@ -37,7 +36,7 @@ public class Commandshowkit extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
return new ArrayList<>(ess.getSettings().getKits().getKeys(false)); // TODO: Move this to its own method
return new ArrayList<>(ess.getKits().getKits().getKeys(false)); // TODO: Move this to its own method
} else {
return Collections.emptyList();
}

View File

@ -2,6 +2,8 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import com.google.common.collect.Lists;
import org.bukkit.Material;
import org.bukkit.Server;
@ -14,6 +16,9 @@ import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandskull extends EssentialsCommand {
private static final Material SKULL_ITEM = EnumUtil.getMaterial("PLAYER_HEAD", "SKULL_ITEM");
public Commandskull() {
super("skull");
}
@ -31,14 +36,14 @@ public class Commandskull extends EssentialsCommand {
owner = user.getName();
}
ItemStack itemSkull = user.getBase().getItemInHand();
ItemStack itemSkull = user.getItemInHand();
SkullMeta metaSkull = null;
boolean spawn = false;
if (itemSkull != null && itemSkull.getType() == Material.SKULL_ITEM && itemSkull.getDurability() == 3) {
if (itemSkull != null && MaterialUtil.isPlayerHead(itemSkull.getType(), itemSkull.getDurability())) {
metaSkull = (SkullMeta) itemSkull.getItemMeta();
} else if (user.isAuthorized("essentials.skull.spawn")) {
itemSkull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
itemSkull = new ItemStack(SKULL_ITEM, 1, (byte) 3);
metaSkull = (SkullMeta) itemSkull.getItemMeta();
spawn = true;
} else {

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.Mob;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
@ -28,7 +29,9 @@ public class Commandspawner extends EssentialsCommand {
}
final Location target = LocationUtil.getTarget(user.getBase());
if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) {
Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER");
if (target == null || target.getBlock().getType() != MOB_SPAWNER) {
throw new Exception(tl("mobSpawnTarget"));
}

View File

@ -1,7 +1,10 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Teleport;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.Collections;
import java.util.List;
@ -35,6 +38,15 @@ public class Commandtpa extends EssentialsCommand {
&& player.isTpRequestHere() == false) { // Make sure the last teleport request was actually tpa and not tpahere
throw new Exception(tl("requestSentAlready", player.getDisplayName()));
}
if (player.isAutoTeleportEnabled() && !player.isIgnoredPlayer(user)) {
final Trade charge = new Trade(this.getName(), ess);
Teleport teleport = user.getTeleport();
teleport.setTpType(Teleport.TeleportType.TPA);
teleport.teleport(player.getBase(), charge, PlayerTeleportEvent.TeleportCause.COMMAND);
player.sendMessage(tl("requestAcceptedAuto", user.getDisplayName()));
user.sendMessage(tl("requestAcceptedFromAuto", player.getDisplayName()));
return;
}
if (!player.isIgnoredPlayer(user)) {
player.requestTeleport(user, false);

View File

@ -0,0 +1,41 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandtpauto extends EssentialsToggleCommand {
public Commandtpauto() {
super("tpauto", "essentials.tpauto.others");
}
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
toggleOtherPlayers(server, sender, args);
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
handleToggleWithArgs(server, user, args);
}
@Override
void togglePlayer(CommandSource sender, User user, Boolean enabled) {
if (enabled == null) {
enabled = !user.isAutoTeleportEnabled();
}
user.setAutoTeleportEnabled(enabled);
user.sendMessage(enabled ? tl("autoTeleportEnabled") : tl("autoTeleportDisabled"));
if (enabled && !user.isTeleportEnabled()) {
user.sendMessage(tl("teleportationDisabledWarning"));
}
if (!sender.isPlayer() || !user.getBase().equals(sender.getPlayer())) {
sender.sendMessage(enabled ? tl("autoTeleportEnabledFor", user.getDisplayName()) : tl("autoTeleportDisabledFor", user.getDisplayName()));
}
}
}

View File

@ -32,6 +32,10 @@ public class Commandtree extends EssentialsCommand {
}
if (args[0].equalsIgnoreCase("jungle")) {
tree = TreeType.SMALL_JUNGLE;
} else if (args[0].equalsIgnoreCase("acacia")) {
tree = TreeType.ACACIA;
} else if (args[0].equalsIgnoreCase("birch")) {
tree = TreeType.BIRCH;
}
if (tree == null) {
throw new NotEnoughArgumentsException();

View File

@ -32,12 +32,12 @@ public class Commandunlimited extends EssentialsCommand {
final String list = getList(target);
user.sendMessage(list);
} else if (args[0].equalsIgnoreCase("clear")) {
final List<Integer> itemList = target.getUnlimited();
final List<Material> itemList = target.getUnlimited();
int index = 0;
while (itemList.size() > index) {
final Integer item = itemList.get(index);
if (toggleUnlimited(user, target, item.toString()) == false) {
final Material item = itemList.get(index);
if (!toggleUnlimited(user, target, item.toString())) {
index++;
}
}
@ -50,16 +50,16 @@ public class Commandunlimited extends EssentialsCommand {
final StringBuilder output = new StringBuilder();
output.append(tl("unlimitedItems")).append(" ");
boolean first = true;
final List<Integer> items = target.getUnlimited();
final List<Material> items = target.getUnlimited();
if (items.isEmpty()) {
output.append(tl("none"));
}
for (Integer integer : items) {
for (Material material : items) {
if (!first) {
output.append(", ");
}
first = false;
final String matname = Material.getMaterial(integer).toString().toLowerCase(Locale.ENGLISH).replace("_", "");
final String matname = material.toString().toLowerCase(Locale.ENGLISH).replace("_", "");
output.append(matname);
}
@ -71,7 +71,7 @@ public class Commandunlimited extends EssentialsCommand {
stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2));
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (ess.getSettings().permissionBasedItemSpawn() && (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-" + itemname) && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId()) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket")))) {
if (ess.getSettings().permissionBasedItemSpawn() && (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-" + itemname) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket")))) {
throw new Exception(tl("unlimitedItemPermission", itemname));
}

View File

@ -13,9 +13,9 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
@ -64,17 +64,8 @@ public class Commandwarp extends EssentialsCommand {
//TODO: Use one of the new text classes, like /help ?
private void warpList(final CommandSource sender, final String[] args, final IUser user) throws Exception {
final IWarps warps = ess.getWarps();
final List<String> warpNameList = new ArrayList<>(warps.getList());
final List<String> warpNameList = getAvailableWarpsFor(user);
if (user != null) {
final Iterator<String> iterator = warpNameList.iterator();
while (iterator.hasNext()) {
final String warpName = iterator.next();
if (ess.getSettings().getPerWarpPermission() && !user.isAuthorized("essentials.warps." + warpName)) {
iterator.remove();
}
}
}
if (warpNameList.isEmpty()) {
throw new Exception(tl("noWarpsDefined"));
}
@ -112,10 +103,20 @@ public class Commandwarp extends EssentialsCommand {
owner.getTeleport().warp(user, name, charge, TeleportCause.COMMAND);
}
private List<String> getAvailableWarpsFor(final IUser user) {
if (ess.getSettings().getPerWarpPermission() && user != null) {
return ess.getWarps().getList().stream()
.filter(warpName -> user.isAuthorized("essentials.warps." + warpName))
.collect(Collectors.toList());
}
return new ArrayList<>(ess.getWarps().getList());
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1 && user.isAuthorized("essentials.warp.list")) {
return new ArrayList<>(ess.getWarps().getList());
return getAvailableWarpsFor(user);
} else if (args.length == 2 && (user.isAuthorized("essentials.warp.otherplayers") || user.isAuthorized("essentials.warp.others"))) {
//TODO: Remove 'otherplayers' permission.
return getPlayers(server, user);

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server;
import org.bukkit.Statistic;
@ -16,6 +17,10 @@ import static com.earth2me.essentials.I18n.tl;
public class Commandwhois extends EssentialsCommand {
// For some reason, in 1.13 PLAY_ONE_MINUTE = ticks played = what used to be PLAY_ONE_TICK
// https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/commits/b848d8ce633871b52115247b089029749c02f579
private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK");
public Commandwhois() {
super("whois");
}
@ -36,12 +41,14 @@ public class Commandwhois extends EssentialsCommand {
sender.sendMessage(tl("whoisHunger", user.getBase().getFoodLevel(), user.getBase().getSaturation()));
sender.sendMessage(tl("whoisExp", SetExpFix.getTotalExperience(user.getBase()), user.getBase().getLevel()));
sender.sendMessage(tl("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ()));
long playtimeMs = System.currentTimeMillis() - (user.getBase().getStatistic(Statistic.PLAY_ONE_TICK) * 50);
long playtimeMs = System.currentTimeMillis() - (user.getBase().getStatistic(PLAY_ONE_TICK) * 50);
sender.sendMessage(tl("whoisPlaytime", DateUtil.formatDateDiff(playtimeMs)));
if (!ess.getSettings().isEcoDisabled()) {
sender.sendMessage(tl("whoisMoney", NumberUtil.displayCurrency(user.getMoney(), ess)));
}
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
if (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.whois.ip")) {
sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString()));
}
final String location = user.getGeoLocation();
if (location != null && (!sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) {
sender.sendMessage(tl("whoisGeoLocation", location));

View File

@ -84,7 +84,7 @@ public class Commandworth extends EssentialsCommand {
amount = ess.getWorth().getAmount(ess, user, is, args, true);
}
BigDecimal worth = ess.getWorth().getPrice(is);
BigDecimal worth = ess.getWorth().getPrice(ess, is);
if (worth == null) {
throw new Exception(tl("itemCannotBeSold"));

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.craftbukkit;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.*;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
@ -10,6 +11,8 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
import java.io.File;
@ -17,6 +20,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
public class FakeWorld implements World {
@ -38,16 +42,6 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getBlockTypeIdAt(int i, int i1, int i2) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getBlockTypeIdAt(Location lctn) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getHighestBlockYAt(int i, int i1) {
throw new UnsupportedOperationException("Not supported yet.");
@ -93,6 +87,11 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isChunkGenerated(int x, int z) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void loadChunk(int i, int i1) {
throw new UnsupportedOperationException("Not supported yet.");
@ -138,6 +137,21 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isChunkForceLoaded(int x, int z) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setChunkForceLoaded(int x, int z, boolean forced) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Chunk> getForceLoadedChunks() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Item dropItem(Location lctn, ItemStack is) {
throw new UnsupportedOperationException("Not supported yet.");
@ -164,7 +178,7 @@ public class FakeWorld implements World {
}
@Override
public boolean generateTree(Location lctn, TreeType tt, BlockChangeDelegate bcd) {
public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) {
throw new UnsupportedOperationException("Not supported yet.");
}
@ -203,6 +217,11 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean setSpawnLocation(Location location) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean setSpawnLocation(int i, int i1, int i2) {
throw new UnsupportedOperationException("Not supported yet.");
@ -348,6 +367,11 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public FallingBlock spawnFallingBlock(Location location, BlockData blockData) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1) {
throw new UnsupportedOperationException("Not supported yet.");
@ -583,11 +607,6 @@ public class FakeWorld implements World {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void playSound(Location arg0, Sound arg1, float arg2, float arg3) {
throw new UnsupportedOperationException("Not supported yet.");
@ -600,12 +619,12 @@ public class FakeWorld implements World {
@Override
public void playSound(Location location, Sound sound, SoundCategory soundCategory, float v, float v1) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void playSound(Location location, String s, SoundCategory soundCategory, float v, float v1) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
@ -650,66 +669,151 @@ public class FakeWorld implements World {
@Override
public void spawnParticle(Particle particle, Location location, int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void spawnParticle(Particle particle, double v, double v1, double v2, int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, Location location, int i, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6, T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3, T t, boolean b) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6, T t, boolean b) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Entity> getNearbyEntities(Location loc, double x, double y, double z) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public Collection<Entity> getNearbyEntities(Location location, double x, double y, double z, Predicate<Entity> filter) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Entity> getNearbyEntities(BoundingBox boundingBox) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Entity> getNearbyEntities(BoundingBox boundingBox, Predicate<Entity> filter) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate<Entity> filter) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate<Entity> filter) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate<Entity> filter) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> T getGameRuleDefault(GameRule<T> arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> T getGameRuleValue(GameRule<T> arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T> boolean setGameRule(GameRule<T> arg0, T arg1) {
throw new UnsupportedOperationException("Not supported yet.");
}
}

View File

@ -239,4 +239,17 @@ public final class InventoryWorkaround {
}
}
}
@SuppressWarnings("deprecation")
public static void setItemInOffHand(Player p, ItemStack item) {
// This assumes that all builds that support a main hand also support an off hand.
if (hasMainHandSupport == null || hasMainHandSupport) {
try {
p.getInventory().setItemInOffHand(item);
hasMainHandSupport = true;
} catch (Throwable e) {
hasMainHandSupport = false;
}
}
}
}

View File

@ -0,0 +1,234 @@
package com.earth2me.essentials.items;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.StringUtil;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.block.Banner;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb {
protected boolean ready = false;
@Override
public List<ItemStack> getMatching(User user, String[] args) throws Exception {
List<ItemStack> is = new ArrayList<>();
if (args.length < 1) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("hand")) {
is.add(user.getItemInHand().clone());
} else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else if (args[0].equalsIgnoreCase("blocks")) {
for (ItemStack stack : user.getBase().getInventory().getContents()) {
if (stack == null || stack.getType() == Material.AIR) {
continue;
}
is.add(stack.clone());
}
} else {
is.add(get(args[0]));
}
if (is.isEmpty() || is.get(0).getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
}
return is;
}
@Override
public String serialize(ItemStack is) {
String mat = name(is);
if (VersionUtil.getServerBukkitVersion().isLowerThanOrEqualTo(VersionUtil.v1_12_2_R01) && is.getData().getData() != 0) {
mat = mat + ":" + is.getData().getData();
}
int quantity = is.getAmount();
StringBuilder sb = new StringBuilder(); // Add space AFTER you add something. We can trim at end.
sb.append(mat).append(" ").append(quantity).append(" ");
// ItemMeta applies to anything.
if (is.hasItemMeta()) {
ItemMeta meta = is.getItemMeta();
if (meta.hasDisplayName()) {
sb.append("name:").append(meta.getDisplayName().replaceAll(" ", "_")).append(" ");
}
if (meta.hasLore()) {
sb.append("lore:");
boolean first = true;
for (String s : meta.getLore()) {
// Add | before the line if it's not the first one. Easy but weird way
// to do this since we need each line separated by |
if (!first) {
sb.append("|");
}
first = false;
sb.append(s.replaceAll(" ", "_"));
}
sb.append(" ");
}
if (meta.hasEnchants()) {
for (Enchantment e : meta.getEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(meta.getEnchantLevel(e)).append(" ");
}
}
Set<ItemFlag> flags = meta.getItemFlags();
if (flags != null && !flags.isEmpty()) {
sb.append("itemflags:");
boolean first = true;
for (ItemFlag flag : flags) {
if (!first) {
sb.append(",");
}
sb.append(flag.name());
first = false;
}
}
}
final Material material = is.getType();
switch (material) {
case WRITTEN_BOOK:
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Books in that order.
// Interesting as I didn't see a way to do pages or chapters.
BookMeta bookMeta = (BookMeta) is.getItemMeta();
if (bookMeta.hasTitle()) {
sb.append("title:").append(bookMeta.getTitle()).append(" ");
}
if (bookMeta.hasAuthor()) {
sb.append("author:").append(bookMeta.getAuthor()).append(" ");
}
// Only other thing it could have is lore but that's done up there ^^^
break;
case ENCHANTED_BOOK:
EnchantmentStorageMeta enchantmentStorageMeta = (EnchantmentStorageMeta) is.getItemMeta();
for (Enchantment e : enchantmentStorageMeta.getStoredEnchants().keySet()) {
sb.append(e.getName().toLowerCase()).append(":").append(enchantmentStorageMeta.getStoredEnchantLevel(e)).append(" ");
}
break;
}
if (MaterialUtil.isFirework(material)) {
// Everything from http://wiki.ess3.net/wiki/Item_Meta#Fireworks in that order.
FireworkMeta fireworkMeta = (FireworkMeta) is.getItemMeta();
if (fireworkMeta.hasEffects()) {
for (FireworkEffect effect : fireworkMeta.getEffects()) {
if (effect.getColors() != null && !effect.getColors().isEmpty()) {
sb.append("color:");
boolean first = true;
for (Color c : effect.getColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
sb.append("shape:").append(effect.getType().name()).append(" ");
if (effect.getFadeColors() != null && !effect.getFadeColors().isEmpty()) {
sb.append("fade:");
boolean first = true;
for (Color c : effect.getFadeColors()) {
if (!first) {
sb.append(","); // same thing as above.
}
sb.append(c.toString());
first = false;
}
sb.append(" ");
}
}
sb.append("power:").append(fireworkMeta.getPower()).append(" ");
}
} else if (MaterialUtil.isPotion(material)) {
Potion potion = Potion.fromItemStack(is);
for (PotionEffect e : potion.getEffects()) {
// long but needs to be effect:speed power:2 duration:120 in that order.
sb.append("splash:").append(potion.isSplash()).append(" ").append("effect:").append(e.getType().getName().toLowerCase()).append(" ").append("power:").append(e.getAmplifier()).append(" ").append("duration:").append(e.getDuration() / 20).append(" ");
}
} else if (MaterialUtil.isPlayerHead(material, is.getData().getData())) {
// item stack with meta
SkullMeta skullMeta = (SkullMeta) is.getItemMeta();
if (skullMeta != null && skullMeta.hasOwner()) {
sb.append("player:").append(skullMeta.getOwner()).append(" ");
}
} else if (MaterialUtil.isBanner(material)) {
if (material.toString().contains("SHIELD")) {
// Hacky fix for accessing Shield meta - https://github.com/drtshock/Essentials/pull/745#issuecomment-234843795
BlockStateMeta shieldMeta = (BlockStateMeta) is.getItemMeta();
Banner shieldBannerMeta = (Banner) shieldMeta.getBlockState();
DyeColor baseDyeColor = shieldBannerMeta.getBaseColor();
if (baseDyeColor != null) {
int basecolor = baseDyeColor.getColor().asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
}
for (org.bukkit.block.banner.Pattern p : shieldBannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
} else {
BannerMeta bannerMeta = (BannerMeta) is.getItemMeta();
if (bannerMeta != null) {
DyeColor baseDyeColor = bannerMeta.getBaseColor();
if (baseDyeColor == null) {
baseDyeColor = MaterialUtil.getColorOf(material);
}
if (baseDyeColor != null) {
int basecolor = baseDyeColor
.getColor()
.asRGB();
sb.append("basecolor:").append(basecolor).append(" ");
}
for (org.bukkit.block.banner.Pattern p : bannerMeta.getPatterns()) {
String type = p.getPattern().getIdentifier();
int color = p.getColor().getColor().asRGB();
sb.append(type).append(",").append(color).append(" ");
}
}
}
} else if (MaterialUtil.isLeatherArmor(material)) {
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) is.getItemMeta();
int rgb = leatherArmorMeta.getColor().asRGB();
sb.append("color:").append(rgb).append(" ");
}
return sb.toString().trim().replaceAll("§", "&");
}
@Override
public boolean isReady() {
return ready;
}
}

View File

@ -0,0 +1,278 @@
package com.earth2me.essentials.items;
import com.earth2me.essentials.ManagedFile;
import com.earth2me.essentials.utils.MaterialUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.ess3.api.IEssentials;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public class FlatItemDb extends AbstractItemDb {
protected static final Logger LOGGER = Logger.getLogger("Essentials");
private static Gson gson = new Gson();
private final transient IEssentials ess;
// Maps primary name to ItemData
private final transient Map<String, ItemData> items = new HashMap<>();
// Maps alias to primary name
private final transient Map<String, String> itemAliases = new HashMap<>();
// Every known alias
private final transient Set<String> allAliases = new HashSet<>();
private transient ManagedFile file = null;
public FlatItemDb(final IEssentials ess) {
this.ess = ess;
}
@Override
public void reloadConfig() {
if (file == null) {
file = new ManagedFile("items.json", ess);
}
this.rebuild();
LOGGER.info(String.format("Loaded %s items from items.json.", listNames().size()));
}
private void rebuild() {
this.reset();
String json = file.getLines().stream()
.filter(line -> !line.startsWith("#"))
.collect(Collectors.joining());
this.loadJSON(String.join("\n", json));
ready = true;
}
private void reset() {
ready = false;
items.clear();
itemAliases.clear();
allAliases.clear();
}
public void loadJSON(String source) {
JsonObject map = (new JsonParser()).parse(source).getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : map.entrySet()) {
String key = entry.getKey();
JsonElement element = entry.getValue();
boolean valid = false;
if (element.isJsonObject()) {
ItemData data = gson.fromJson(element, ItemData.class);
items.put(key, data);
valid = true;
} else {
try {
String target = element.getAsString();
itemAliases.put(key, target);
valid = true;
} catch (Exception ignored) {}
}
if (valid) {
allAliases.add(key);
} else {
LOGGER.warning(String.format("Failed to add item: \"%s\": %s", key, element.toString()));
}
}
}
@Override
public ItemStack get(String id) throws Exception {
id = id.toLowerCase();
final String[] split = id.split(":");
ItemData data = getByName(split[0]);
if (data == null) {
throw new Exception(tl("unknownItemName", id));
}
Material material = data.getMaterial();
if (!material.isItem()) throw new Exception(tl("unableToSpawnItem", id));
ItemStack stack = new ItemStack(material);
stack.setAmount(material.getMaxStackSize());
PotionData potionData = data.getPotionData();
ItemMeta meta = stack.getItemMeta();
if (potionData != null && meta instanceof PotionMeta) {
PotionMeta potionMeta = (PotionMeta) meta;
potionMeta.setBasePotionData(potionData);
}
// For some reason, Damageable doesn't extend ItemMeta but CB implements them in the same
// class. As to why, your guess is as good as mine.
if (split.length > 1 && meta instanceof Damageable) {
Damageable damageMeta = (Damageable) meta;
damageMeta.setDamage(Integer.parseInt(split[1]));
}
stack.setItemMeta(meta);
// The spawner provider will update the meta again, so we need to call it after
// setItemMeta to prevent a race condition
EntityType entity = data.getEntity();
if (entity != null && material.toString().contains("SPAWNER")) {
ess.getSpawnerProvider().setEntityType(stack, entity);
}
return stack;
}
private ItemData getByName(String name) {
name = name.toLowerCase();
if (items.containsKey(name)) {
return items.get(name);
} else if (itemAliases.containsKey(name)) {
return items.get(itemAliases.get(name));
}
return null;
}
@Override
public List<String> nameList(ItemStack item) {
List<String> names = new ArrayList<>();
String primaryName = name(item);
names.add(primaryName);
for (Map.Entry<String, String> entry : itemAliases.entrySet()) {
if (entry.getValue().equalsIgnoreCase(primaryName)) {
names.add(entry.getKey());
}
}
return names;
}
@Override
public String name(ItemStack item) {
ItemData data = lookup(item);
for (Map.Entry<String, ItemData> entry : items.entrySet()) {
if (entry.getValue().equals(data)) {
return entry.getKey();
}
}
return null;
}
@Override
@Deprecated
public int getLegacyId(Material material) throws Exception {
throw new UnsupportedOperationException("Legacy IDs aren't supported on this version.");
}
public ItemData lookup(ItemStack item) {
Material type = item.getType();
if (MaterialUtil.isPotion(type) && item.getItemMeta() instanceof PotionMeta) {
PotionData potion = ((PotionMeta) item.getItemMeta()).getBasePotionData();
return new ItemData(type, potion);
} else if (type.toString().contains("SPAWNER")) {
EntityType entity = ess.getSpawnerProvider().getEntityType(item);
return new ItemData(type, entity);
} else {
return new ItemData(type);
}
}
@Override
public Collection<String> listNames() {
return Collections.unmodifiableSet(allAliases);
}
public static class ItemData {
private final Material material;
private PotionData potionData = null;
private EntityType entity = null;
public ItemData(Material material) {
this.material = material;
}
public ItemData(Material material, PotionData potionData) {
this.material = material;
this.potionData = potionData;
}
public ItemData(Material material, EntityType entity) {
this.material = material;
this.entity = entity;
}
@Override
public int hashCode() {
return (31 * material.hashCode()) ^ potionData.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof ItemData)) {
return false;
}
ItemData that = (ItemData) o;
return this.material == that.getMaterial() && potionDataEquals(that) && entityEquals(that);
}
public Material getMaterial() {
return material;
}
public PotionData getPotionData() {
return this.potionData;
}
public EntityType getEntity() {
return this.entity;
}
private boolean potionDataEquals(ItemData o) {
if (this.potionData == null && o.getPotionData() == null) {
return true;
} else if (this.potionData != null && o.getPotionData() != null) {
return this.potionData.equals(o.getPotionData());
} else {
return false;
}
}
private boolean entityEquals(ItemData o) {
if (this.entity == null && o.getEntity() == null) { // neither have an entity
return true;
} else if (this.entity != null && o.getEntity() != null) { // both have an entity; check if it's the same one
return this.entity.equals(o.getEntity());
} else { // one has an entity but the other doesn't, so they can't be equal
return false;
}
}
}
}

View File

@ -0,0 +1,298 @@
package com.earth2me.essentials.items;
import com.earth2me.essentials.ManagedFile;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class LegacyItemDb extends AbstractItemDb {
protected static final Logger LOGGER = Logger.getLogger("Essentials");
private final transient IEssentials ess;
private final transient Map<String, Integer> items = new HashMap<>();
private final transient Map<ItemData, List<String>> names = new HashMap<>();
private final transient Map<ItemData, String> primaryName = new HashMap<>();
private final transient Map<Integer, ItemData> legacyIds = new HashMap<>();
private final transient Map<String, Short> durabilities = new HashMap<>();
private final transient Map<String, String> nbtData = new HashMap<>();
private final transient ManagedFile file;
private final transient Pattern splitPattern = Pattern.compile("((.*)[:+',;.](\\d+))");
private final transient Pattern csvSplitPattern = Pattern.compile("(\"([^\"]*)\"|[^,]*)(,|$)");
public LegacyItemDb(final IEssentials ess) {
this.ess = ess;
file = new ManagedFile("items.csv", ess);
}
@Override
public void reloadConfig() {
final List<String> lines = file.getLines();
if (lines.isEmpty()) {
return;
}
ready = false;
durabilities.clear();
items.clear();
names.clear();
primaryName.clear();
for (String line : lines) {
if (line.length() > 0 && line.charAt(0) == '#') {
continue;
}
String itemName = null;
int numeric = -1;
short data = 0;
String nbt = null;
int col = 0;
Matcher matcher = csvSplitPattern.matcher(line);
while (matcher.find()) {
String match = matcher.group(1);
if (StringUtils.stripToNull(match) == null) {
continue;
}
match = StringUtils.strip(match.trim(), "\"");
switch (col) {
case 0:
itemName = match.toLowerCase(Locale.ENGLISH);
break;
case 1:
numeric = Integer.parseInt(match);
break;
case 2:
data = Short.parseShort(match);
break;
case 3:
nbt = StringUtils.stripToNull(match);
break;
default:
continue;
}
col++;
}
// Invalid row
if (itemName == null || numeric < 0) {
continue;
}
durabilities.put(itemName, data);
items.put(itemName, numeric);
if (nbt != null) {
nbtData.put(itemName, nbt);
}
ItemData itemData = new ItemData(numeric, data);
if (names.containsKey(itemData)) {
List<String> nameList = names.get(itemData);
nameList.add(itemName);
} else {
List<String> nameList = new ArrayList<>();
nameList.add(itemName);
names.put(itemData, nameList);
primaryName.put(itemData, itemName);
}
legacyIds.put(numeric, itemData);
}
for (List<String> nameList : names.values()) {
Collections.sort(nameList, LengthCompare.INSTANCE);
}
LOGGER.info(String.format("Loaded %s items from items.csv.", listNames().size()));
ready = true;
}
@Override
public ItemStack get(final String id) throws Exception {
int itemid = 0;
String itemname;
short metaData = 0;
Matcher parts = splitPattern.matcher(id);
if (parts.matches()) {
itemname = parts.group(2);
metaData = Short.parseShort(parts.group(3));
} else {
itemname = id;
}
if (NumberUtil.isInt(itemname)) {
itemid = Integer.parseInt(itemname);
} else if (NumberUtil.isInt(id)) {
itemid = Integer.parseInt(id);
} else {
itemname = itemname.toLowerCase(Locale.ENGLISH);
}
if (itemid < 1) {
if (items.containsKey(itemname)) {
itemid = items.get(itemname);
if (durabilities.containsKey(itemname) && metaData == 0) {
metaData = durabilities.get(itemname);
}
}
}
if (itemid < 1) {
Material matFromName = EnumUtil.getMaterial(itemname.toUpperCase());
if (matFromName != null) {
itemid = matFromName.getId();
}
}
if (itemid < 1) {
throw new Exception(tl("unknownItemName", itemname));
}
ItemData data = legacyIds.get(itemid);
if (data == null) {
throw new Exception(tl("unknownItemId", itemid));
}
Material mat = getFromLegacy(itemid, (byte) metaData);
ItemStack retval = new ItemStack(mat);
if (nbtData.containsKey(itemname)) {
String nbt = nbtData.get(itemname);
if (nbt.startsWith("*")) {
nbt = nbtData.get(nbt.substring(1));
}
retval = ess.getServer().getUnsafe().modifyItemStack(retval, nbt);
}
Material MOB_SPAWNER = EnumUtil.getMaterial("SPAWNER", "MOB_SPAWNER");
if (mat == MOB_SPAWNER) {
if (metaData == 0) metaData = EntityType.PIG.getTypeId();
try {
retval = ess.getSpawnerProvider().setEntityType(retval, EntityType.fromId(metaData));
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from mob spawners.");
}
} else if (mat.name().contains("MONSTER_EGG")) {
EntityType type;
try {
type = EntityType.fromId(metaData);
} catch (IllegalArgumentException e) {
throw new Exception("Can't spawn entity ID " + metaData + " from spawn eggs.");
}
retval = ess.getSpawnEggProvider().createEggItem(type);
} else if (mat.name().endsWith("POTION")
&& ReflUtil.getNmsVersionObject().isLowerThan(ReflUtil.V1_11_R1)) { // Only apply this to pre-1.11 as items.csv might only work in 1.11
retval = ess.getPotionMetaProvider().createPotionItem(mat, metaData);
} else {
retval.setDurability(metaData);
}
retval.setAmount(mat.getMaxStackSize());
return retval;
}
@Override
public List<String> nameList(ItemStack item) {
ItemData itemData = new ItemData(item.getType().getId(), item.getDurability());
List<String> nameList = names.get(itemData);
if (nameList == null) {
itemData = new ItemData(item.getType().getId(), (short) 0);
nameList = names.get(itemData);
if (nameList == null) {
return null;
}
}
return Collections.unmodifiableList(nameList);
}
@Override
public String name(ItemStack item) {
ItemData itemData = new ItemData(item.getType().getId(), item.getDurability());
String name = primaryName.get(itemData);
if (name == null) {
itemData = new ItemData(item.getType().getId(), (short) 0);
name = primaryName.get(itemData);
if (name == null) {
return null;
}
}
return name;
}
@Override
public int getLegacyId(Material material) throws Exception {
for(Map.Entry<String, Integer> entry : items.entrySet()) {
if(material.name().toLowerCase(Locale.ENGLISH).equalsIgnoreCase(entry.getKey())) {
return entry.getValue();
}
}
throw new Exception("Itemid not found for material: " + material.name());
}
@Override
public Collection<String> listNames() {
return primaryName.values();
}
static class ItemData {
private int itemNo;
final private short itemData;
ItemData(final int itemNo, final short itemData) {
this.itemNo = itemNo;
this.itemData = itemData;
}
public int getItemNo() {
return itemNo;
}
public short getItemData() {
return itemData;
}
@Override
public int hashCode() {
return (31 * itemNo) ^ itemData;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof ItemData)) {
return false;
}
ItemData pairo = (ItemData) o;
return this.itemNo == pairo.getItemNo() && this.itemData == pairo.getItemData();
}
}
static class LengthCompare implements java.util.Comparator<String> {
private static final LengthCompare INSTANCE = new LengthCompare();
public LengthCompare() {
super();
}
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.messaging;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
@ -17,7 +16,7 @@ import java.lang.ref.WeakReference;
* <li>{@link IMessageRecipient#getReplyRecipient()}</li>
* <li>{@link IMessageRecipient#setReplyRecipient(IMessageRecipient)}</li>
* </ul>
*
*
* <b>The given {@code parent} must implement the following methods to prevent overflow:</b>
* <ul>
* <li>{@link IMessageRecipient#sendMessage(String)}</li>
@ -25,14 +24,14 @@ import java.lang.ref.WeakReference;
* <li>{@link IMessageRecipient#getDisplayName()}</li>
* <li>{@link IMessageRecipient#isReachable()}</li>
* </ul>
*
*
* The reply-recipient is wrapped in a {@link WeakReference}.
*/
public class SimpleMessageRecipient implements IMessageRecipient {
private final IEssentials ess;
private final IMessageRecipient parent;
private long lastMessageMs;
private WeakReference<IMessageRecipient> replyRecipient;
@ -42,7 +41,7 @@ public class SimpleMessageRecipient implements IMessageRecipient {
}
return recipient instanceof User ? (User) recipient : null;
}
public SimpleMessageRecipient(IEssentials ess, IMessageRecipient parent) {
this.ess = ess;
this.parent = parent;
@ -117,13 +116,12 @@ public class SimpleMessageRecipient implements IMessageRecipient {
if (!isReachable()) {
return MessageResponse.UNREACHABLE;
}
User user = getUser(this);
boolean afk = false;
if (user != null) {
if (user.isIgnoreMsg()
&& !(sender instanceof Console)) { // Console must never be ignored.
return MessageResponse.MESSAGES_IGNORED;
if (user.isIgnoreMsg() && sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { // Don't ignore console and senders with permission
return MessageResponse.MESSAGES_IGNORED;
}
afk = user.isAfk();
// Check whether this recipient ignores the sender, only if the sender is not the console.
@ -138,7 +136,7 @@ public class SimpleMessageRecipient implements IMessageRecipient {
// If this recipient doesn't have a reply recipient, initiate by setting the first
// message sender to this recipient's replyRecipient.
long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000;
if (getReplyRecipient() == null || !getReplyRecipient().isReachable()
if (getReplyRecipient() == null || !getReplyRecipient().isReachable()
|| System.currentTimeMillis() - this.lastMessageMs > timeout) {
setReplyRecipient(sender);
}

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ public class PermissionsHandler implements IPermissionsHandler {
private transient IPermissionsHandler handler = null;
private transient String defaultGroup = "default";
private final transient Essentials ess;
private transient boolean useSuperperms = false;
private transient boolean useSuperperms;
private Class<?> lastHandler = null;
@ -92,10 +92,7 @@ public class PermissionsHandler implements IPermissionsHandler {
public void checkPermissions() {
// load and assign a handler
List<Class<? extends SuperpermsHandler>> providerClazz = Arrays.asList(
BPermissions2Handler.class,
PermissionsExHandler.class,
PrivilegesHandler.class,
SimplyPermsHandler.class,
GenericVaultHandler.class,
SuperpermsHandler.class
);
@ -158,7 +155,4 @@ public class PermissionsHandler implements IPermissionsHandler {
}
}
private void checkPermLag(long start) {
checkPermLag(start, "not defined");
}
}

View File

@ -13,7 +13,7 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler {
protected static Permission perms = null;
protected static Chat chat = null;
public boolean setupProviders() {
private boolean setupProviders() {
try {
Class.forName("net.milkbowl.vault.permission.Permission");
Class.forName("net.milkbowl.vault.chat.Chat");
@ -65,7 +65,7 @@ public abstract class AbstractVaultHandler extends SuperpermsHandler {
}
}
protected boolean canLoad() {
boolean canLoad() {
if (Bukkit.getPluginManager().getPlugin("Vault") == null) return false;
try {
return setupProviders();

View File

@ -1,17 +0,0 @@
package com.earth2me.essentials.perm.impl;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class BPermissions2Handler extends AbstractVaultHandler {
@Override
public boolean canBuild(final Player base, final String group) {
return hasPermission(base, "bPermissions.build");
}
@Override
public boolean tryProvider() {
return super.canLoad() && Bukkit.getPluginManager().getPlugin("bPermissions") != null;
}
}

View File

@ -1,16 +0,0 @@
package com.earth2me.essentials.perm.impl;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class PrivilegesHandler extends AbstractVaultHandler {
@Override
public boolean canBuild(Player base, String group) {
return hasPermission(base, "privileges.build");
}
@Override
public boolean tryProvider() {
return super.canLoad() && Bukkit.getPluginManager().getPlugin("Privileges") != null;
}
}

View File

@ -1,16 +0,0 @@
package com.earth2me.essentials.perm.impl;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class SimplyPermsHandler extends AbstractVaultHandler {
@Override
public boolean canBuild(Player base, String group) {
return hasPermission(base, "permissions.allow.build");
}
@Override
public boolean tryProvider() {
return super.canLoad() && Bukkit.getPluginManager().getPlugin("SimplyPerms") != null;
}
}

View File

@ -5,10 +5,10 @@ import org.bukkit.plugin.Plugin;
/**
* Interface to be implemented by a payment method.
* Copyright (C) 2011
* AOL license <http://aol.nexua.org>
*
* @author Nijikokun <nijikokun@shortmail.com> (@nijikokun)
* @copyright Copyright (C) 2011
* @license AOL license <http://aol.nexua.org>
*/
public interface Method {
/**

View File

@ -22,7 +22,7 @@ import java.util.Set;
* preferred: "iConomy"
* </pre></blockquote>
*
* @author: Nijikokun <nijikokun@shortmail.com> (@nijikokun) @copyright: Copyright (C) 2011 @license: AOL license
* @author Nijikokun <nijikokun@shortmail.com> (@nijikokun) @copyright: Copyright (C) 2011 @license: AOL license
* <http://aol.nexua.org>
*/
public class Methods {
@ -30,9 +30,9 @@ public class Methods {
private static boolean self = false;
private static Method Method = null;
private static String preferred = "";
private static final Set<Method> Methods = new HashSet<Method>();
private static final Set<String> Dependencies = new HashSet<String>();
private static final Set<Method> Attachables = new HashSet<Method>();
private static final Set<Method> Methods = new HashSet<>();
private static final Set<String> Dependencies = new HashSet<>();
private static final Set<Method> Attachables = new HashSet<>();
static {
_init();
@ -42,11 +42,6 @@ public class Methods {
* Implement all methods along with their respective name & class.
*/
private static void _init() {
addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo6());
addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo5());
addMethod("BOSEconomy", new com.earth2me.essentials.register.payment.methods.BOSE7());
addMethod("Currency", new com.earth2me.essentials.register.payment.methods.MCUR());
Dependencies.add("MultiCurrency");
addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco());
}
@ -84,7 +79,7 @@ public class Methods {
*
* @return <code>Set<String></code> - Array of payment methods that are loaded.
*
* @see #setMethod(org.bukkit.plugin.Plugin)
* @see #setMethod(PluginManager)
*/
public static Set<String> getDependencies() {
return Dependencies;
@ -119,8 +114,8 @@ public class Methods {
*
* @return <code>boolean</code>
*
* @see #setMethod(org.bukkit.plugin.Plugin)
* @see #checkDisabled(org.bukkit.plugin.Plugin)
* @see #setMethod(PluginManager)
* @see #checkDisabled(Plugin)
*/
public static boolean hasMethod() {
return (Method != null);
@ -129,7 +124,7 @@ public class Methods {
/**
* Checks Plugin Class against a multitude of checks to verify it's usability as a payment method.
*
* @param <code>PluginManager</code> the plugin manager for the server
* @param manager the plugin manager for the server
*
* @return <code>boolean</code> True on success, False on failure.
*/
@ -145,7 +140,7 @@ public class Methods {
int count = 0;
boolean match = false;
Plugin plugin = null;
Plugin plugin;
for (String name : getDependencies()) {
if (hasMethod()) {

View File

@ -1,271 +0,0 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import cosine.boseconomy.BOSEconomy;
import org.bukkit.plugin.Plugin;
/**
* BOSEconomy 7 Implementation of Method
*
* @author Acrobot
* @author Nijikokun <nijikokun@shortmail.com> (@nijikokun) @copyright (c) 2011 @license AOL license
* <http://aol.nexua.org>
*/
public class BOSE7 implements Method {
private BOSEconomy BOSEconomy;
@Override
public BOSEconomy getPlugin() {
return this.BOSEconomy;
}
@Override
public String getName() {
return "BOSEconomy";
}
@Override
public String getLongName() {
return getName();
}
@Override
public String getVersion() {
return "0.7.0";
}
@Override
public int fractionalDigits() {
return this.BOSEconomy.getFractionalDigits();
}
@Override
public String format(double amount) {
String currency = this.BOSEconomy.getMoneyNamePlural();
if (amount == 1) {
currency = this.BOSEconomy.getMoneyName();
}
return amount + " " + currency;
}
@Override
public boolean hasBanks() {
return true;
}
@Override
public boolean hasBank(String bank) {
return this.BOSEconomy.bankExists(bank);
}
@Override
public boolean hasAccount(String name) {
return this.BOSEconomy.playerRegistered(name, false);
}
@Override
public boolean hasBankAccount(String bank, String name) {
return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name);
}
@Override
public boolean createAccount(String name) {
if (hasAccount(name)) {
return false;
}
this.BOSEconomy.registerPlayer(name);
return true;
}
@Override
public boolean createAccount(String name, Double balance) {
if (hasAccount(name)) {
return false;
}
this.BOSEconomy.registerPlayer(name);
this.BOSEconomy.setPlayerMoney(name, balance, false);
return true;
}
@Override
public MethodAccount getAccount(String name) {
if (!hasAccount(name)) {
return null;
}
return new BOSEAccount(name, this.BOSEconomy);
}
@Override
public MethodBankAccount getBankAccount(String bank, String name) {
if (!hasBankAccount(bank, name)) {
return null;
}
return new BOSEBankAccount(bank, BOSEconomy);
}
@Override
public boolean isCompatible(Plugin plugin) {
return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") && plugin instanceof BOSEconomy && !plugin.getDescription().getVersion().equals("0.6.2");
}
@Override
public void setPlugin(Plugin plugin) {
BOSEconomy = (BOSEconomy) plugin;
}
public class BOSEAccount implements MethodAccount {
private final String name;
private final BOSEconomy BOSEconomy;
public BOSEAccount(String name, BOSEconomy bOSEconomy) {
this.name = name;
this.BOSEconomy = bOSEconomy;
}
@Override
public double balance() {
return this.BOSEconomy.getPlayerMoneyDouble(this.name);
}
@Override
public boolean set(double amount) {
return this.BOSEconomy.setPlayerMoney(this.name, amount, false);
}
@Override
public boolean add(double amount) {
return this.BOSEconomy.addPlayerMoney(this.name, amount, false);
}
@Override
public boolean subtract(double amount) {
double balance = this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance - amount), false);
}
@Override
public boolean multiply(double amount) {
double balance = this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance * amount), false);
}
@Override
public boolean divide(double amount) {
double balance = this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance / amount), false);
}
@Override
public boolean hasEnough(double amount) {
return (this.balance() >= amount);
}
@Override
public boolean hasOver(double amount) {
return (this.balance() > amount);
}
@Override
public boolean hasUnder(double amount) {
return (this.balance() < amount);
}
@Override
public boolean isNegative() {
return (this.balance() < 0);
}
@Override
public boolean remove() {
return false;
}
}
public class BOSEBankAccount implements MethodBankAccount {
private final String bank;
private final BOSEconomy BOSEconomy;
public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) {
this.bank = bank;
this.BOSEconomy = bOSEconomy;
}
@Override
public String getBankName() {
return this.bank;
}
@Override
public int getBankId() {
return -1;
}
@Override
public double balance() {
return this.BOSEconomy.getBankMoneyDouble(bank);
}
@Override
public boolean set(double amount) {
return this.BOSEconomy.setBankMoney(bank, amount, true);
}
@Override
public boolean add(double amount) {
double balance = this.balance();
return this.BOSEconomy.setBankMoney(bank, (balance + amount), false);
}
@Override
public boolean subtract(double amount) {
double balance = this.balance();
return this.BOSEconomy.setBankMoney(bank, (balance - amount), false);
}
@Override
public boolean multiply(double amount) {
double balance = this.balance();
return this.BOSEconomy.setBankMoney(bank, (balance * amount), false);
}
@Override
public boolean divide(double amount) {
double balance = this.balance();
return this.BOSEconomy.setBankMoney(bank, (balance / amount), false);
}
@Override
public boolean hasEnough(double amount) {
return (this.balance() >= amount);
}
@Override
public boolean hasOver(double amount) {
return (this.balance() > amount);
}
@Override
public boolean hasUnder(double amount) {
return (this.balance() < amount);
}
@Override
public boolean isNegative() {
return (this.balance() < 0);
}
@Override
public boolean remove() {
return this.BOSEconomy.removeBank(bank);
}
}
}

View File

@ -1,163 +0,0 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import me.ashtheking.currency.Currency;
import me.ashtheking.currency.CurrencyList;
import org.bukkit.plugin.Plugin;
/**
* MultiCurrency Method implementation.
*
* @author Acrobot @copyright (c) 2011 @license AOL license <http://aol.nexua.org>
*/
public class MCUR implements Method {
private Currency currencyList;
@Override
public Object getPlugin() {
return this.currencyList;
}
@Override
public String getName() {
return "MultiCurrency";
}
@Override
public String getLongName() {
return getName();
}
@Override
public String getVersion() {
return "0.09";
}
@Override
public int fractionalDigits() {
return -1;
}
@Override
public String format(double amount) {
return amount + " Currency";
}
@Override
public boolean hasBanks() {
return false;
}
@Override
public boolean hasBank(String bank) {
return false;
}
@Override
public boolean hasAccount(String name) {
return true;
}
@Override
public boolean hasBankAccount(String bank, String name) {
return false;
}
@Override
public boolean createAccount(String name) {
CurrencyList.setValue((String) CurrencyList.maxCurrency(name)[0], name, 0);
return true;
}
@Override
public boolean createAccount(String name, Double balance) {
CurrencyList.setValue((String) CurrencyList.maxCurrency(name)[0], name, balance);
return true;
}
@Override
public MethodAccount getAccount(String name) {
return new MCurrencyAccount(name);
}
@Override
public MethodBankAccount getBankAccount(String bank, String name) {
return null;
}
@Override
public boolean isCompatible(Plugin plugin) {
return (plugin.getDescription().getName().equalsIgnoreCase("Currency") || plugin.getDescription().getName().equalsIgnoreCase("MultiCurrency")) && plugin instanceof Currency;
}
@Override
public void setPlugin(Plugin plugin) {
currencyList = (Currency) plugin;
}
public class MCurrencyAccount implements MethodAccount {
private final String name;
public MCurrencyAccount(String name) {
this.name = name;
}
@Override
public double balance() {
return CurrencyList.getValue((String) CurrencyList.maxCurrency(name)[0], name);
}
@Override
public boolean set(double amount) {
CurrencyList.setValue((String) CurrencyList.maxCurrency(name)[0], name, amount);
return true;
}
@Override
public boolean add(double amount) {
return CurrencyList.add(name, amount);
}
@Override
public boolean subtract(double amount) {
return CurrencyList.subtract(name, amount);
}
@Override
public boolean multiply(double amount) {
return CurrencyList.multiply(name, amount);
}
@Override
public boolean divide(double amount) {
return CurrencyList.divide(name, amount);
}
@Override
public boolean hasEnough(double amount) {
return CurrencyList.hasEnough(name, amount);
}
@Override
public boolean hasOver(double amount) {
return CurrencyList.hasOver(name, amount);
}
@Override
public boolean hasUnder(double amount) {
return CurrencyList.hasUnder(name, amount);
}
@Override
public boolean isNegative() {
return CurrencyList.isNegative(name);
}
@Override
public boolean remove() {
return CurrencyList.remove(name);
}
}
}

View File

@ -1,18 +1,17 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
public class VaultEco implements Method {
private Vault vault;
private Plugin vault;
private Economy economy;
@Override
public Vault getPlugin() {
public Plugin getPlugin() {
return this.vault;
}
@ -108,17 +107,15 @@ public class VaultEco implements Method {
public boolean isCompatible(Plugin plugin) {
try {
RegisteredServiceProvider<Economy> ecoPlugin = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
return plugin instanceof Vault && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy");
} catch (LinkageError e) {
return false;
} catch (Exception e) {
return plugin.getName().equals("Vault") && ecoPlugin != null && !ecoPlugin.getProvider().getName().equals("Essentials Economy");
} catch (LinkageError | Exception e) {
return false;
}
}
@Override
public void setPlugin(Plugin plugin) {
this.vault = (Vault) plugin;
this.vault = plugin;
RegisteredServiceProvider<Economy> economyProvider = this.vault.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
this.economy = economyProvider.getProvider();
@ -130,7 +127,7 @@ public class VaultEco implements Method {
private final String name;
private final Economy economy;
public VaultAccount(String name, Economy economy) {
VaultAccount(String name, Economy economy) {
this.name = name;
this.economy = economy;
}

View File

@ -1,312 +0,0 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import com.iConomy.iConomy;
import com.iConomy.system.Account;
import com.iConomy.system.BankAccount;
import com.iConomy.system.Holdings;
import com.iConomy.util.Constants;
import org.bukkit.plugin.Plugin;
/**
* iConomy 5 Implementation of Method
*
* @author Nijikokun <nijikokun@shortmail.com> (@nijikokun) @copyright (c) 2011 @license AOL license
* <http://aol.nexua.org>
*/
public class iCo5 implements Method {
private iConomy iConomy;
@Override
public iConomy getPlugin() {
return this.iConomy;
}
@Override
public String getName() {
return "iConomy";
}
@Override
public String getLongName() {
return getName();
}
@Override
public String getVersion() {
return "5";
}
@Override
public int fractionalDigits() {
return 2;
}
@Override
public String format(double amount) {
return com.iConomy.iConomy.format(amount);
}
@Override
public boolean hasBanks() {
return Constants.Banking;
}
@Override
public boolean hasBank(String bank) {
return (hasBanks()) && com.iConomy.iConomy.Banks.exists(bank);
}
@Override
public boolean hasAccount(String name) {
return com.iConomy.iConomy.hasAccount(name);
}
@Override
public boolean hasBankAccount(String bank, String name) {
return (hasBank(bank)) && com.iConomy.iConomy.getBank(bank).hasAccount(name);
}
@Override
public boolean createAccount(String name) {
if (hasAccount(name)) {
return false;
}
return com.iConomy.iConomy.Accounts.create(name);
}
@Override
public boolean createAccount(String name, Double balance) {
if (hasAccount(name)) {
return false;
}
if (!com.iConomy.iConomy.Accounts.create(name)) {
return false;
}
getAccount(name).set(balance);
return true;
}
@Override
public MethodAccount getAccount(String name) {
return new iCoAccount(com.iConomy.iConomy.getAccount(name));
}
@Override
public MethodBankAccount getBankAccount(String bank, String name) {
return new iCoBankAccount(com.iConomy.iConomy.getBank(bank).getAccount(name));
}
@Override
public boolean isCompatible(Plugin plugin) {
return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy;
}
@Override
public void setPlugin(Plugin plugin) {
iConomy = (iConomy) plugin;
}
public class iCoAccount implements MethodAccount {
private final Account account;
private final Holdings holdings;
public iCoAccount(Account account) {
this.account = account;
this.holdings = account.getHoldings();
}
public Account getiCoAccount() {
return account;
}
@Override
public double balance() {
return this.holdings.balance();
}
@Override
public boolean set(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.set(amount);
return true;
}
@Override
public boolean add(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.add(amount);
return true;
}
@Override
public boolean subtract(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.subtract(amount);
return true;
}
@Override
public boolean multiply(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.multiply(amount);
return true;
}
@Override
public boolean divide(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.divide(amount);
return true;
}
@Override
public boolean hasEnough(double amount) {
return this.holdings.hasEnough(amount);
}
@Override
public boolean hasOver(double amount) {
return this.holdings.hasOver(amount);
}
@Override
public boolean hasUnder(double amount) {
return this.holdings.hasUnder(amount);
}
@Override
public boolean isNegative() {
return this.holdings.isNegative();
}
@Override
public boolean remove() {
if (this.account == null) {
return false;
}
this.account.remove();
return true;
}
}
public class iCoBankAccount implements MethodBankAccount {
private final BankAccount account;
private final Holdings holdings;
public iCoBankAccount(BankAccount account) {
this.account = account;
this.holdings = account.getHoldings();
}
public BankAccount getiCoBankAccount() {
return account;
}
@Override
public String getBankName() {
return this.account.getBankName();
}
@Override
public int getBankId() {
return this.account.getBankId();
}
@Override
public double balance() {
return this.holdings.balance();
}
@Override
public boolean set(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.set(amount);
return true;
}
@Override
public boolean add(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.add(amount);
return true;
}
@Override
public boolean subtract(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.subtract(amount);
return true;
}
@Override
public boolean multiply(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.multiply(amount);
return true;
}
@Override
public boolean divide(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.divide(amount);
return true;
}
@Override
public boolean hasEnough(double amount) {
return this.holdings.hasEnough(amount);
}
@Override
public boolean hasOver(double amount) {
return this.holdings.hasOver(amount);
}
@Override
public boolean hasUnder(double amount) {
return this.holdings.hasUnder(amount);
}
@Override
public boolean isNegative() {
return this.holdings.isNegative();
}
@Override
public boolean remove() {
if (this.account == null) {
return false;
}
this.account.remove();
return true;
}
}
}

View File

@ -1,201 +0,0 @@
package com.earth2me.essentials.register.payment.methods;
import com.earth2me.essentials.register.payment.Method;
import com.iCo6.iConomy;
import com.iCo6.system.Account;
import com.iCo6.system.Accounts;
import com.iCo6.system.Holdings;
import org.bukkit.plugin.Plugin;
/**
* iConomy 6 Implementation of Method
*
* @author Nijikokun <nijikokun@shortmail.com> (@nijikokun) @copyright (c) 2011 @license AOL license
* <http://aol.nexua.org>
*/
public class iCo6 implements Method {
private iConomy iConomy;
@Override
public iConomy getPlugin() {
return this.iConomy;
}
@Override
public String getName() {
return "iConomy";
}
@Override
public String getLongName() {
return getName();
}
@Override
public String getVersion() {
return "6";
}
@Override
public int fractionalDigits() {
return 2;
}
@Override
public String format(double amount) {
return com.iCo6.iConomy.format(amount);
}
@Override
public boolean hasBanks() {
return false;
}
@Override
public boolean hasBank(String bank) {
return false;
}
@Override
public boolean hasAccount(String name) {
return (new Accounts()).exists(name);
}
@Override
public boolean hasBankAccount(String bank, String name) {
return false;
}
@Override
public boolean createAccount(String name) {
if (hasAccount(name)) {
return false;
}
return (new Accounts()).create(name);
}
@Override
public boolean createAccount(String name, Double balance) {
if (hasAccount(name)) {
return false;
}
return (new Accounts()).create(name, balance);
}
@Override
public MethodAccount getAccount(String name) {
return new iCoAccount((new Accounts()).get(name));
}
@Override
public MethodBankAccount getBankAccount(String bank, String name) {
return null;
}
@Override
public boolean isCompatible(Plugin plugin) {
return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals("com.iCo6.iConomy") && plugin instanceof iConomy;
}
@Override
public void setPlugin(Plugin plugin) {
iConomy = (iConomy) plugin;
}
public class iCoAccount implements MethodAccount {
private final Account account;
private final Holdings holdings;
public iCoAccount(Account account) {
this.account = account;
this.holdings = account.getHoldings();
}
public Account getiCoAccount() {
return account;
}
@Override
public double balance() {
return this.holdings.getBalance();
}
@Override
public boolean set(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.setBalance(amount);
return true;
}
@Override
public boolean add(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.add(amount);
return true;
}
@Override
public boolean subtract(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.subtract(amount);
return true;
}
@Override
public boolean multiply(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.multiply(amount);
return true;
}
@Override
public boolean divide(double amount) {
if (this.holdings == null) {
return false;
}
this.holdings.divide(amount);
return true;
}
@Override
public boolean hasEnough(double amount) {
return this.holdings.hasEnough(amount);
}
@Override
public boolean hasOver(double amount) {
return this.holdings.hasOver(amount);
}
@Override
public boolean hasUnder(double amount) {
return this.holdings.hasUnder(amount);
}
@Override
public boolean isNegative() {
return this.holdings.isNegative();
}
@Override
public boolean remove() {
if (this.account == null) {
return false;
}
this.account.remove();
return true;
}
}
}

View File

@ -2,15 +2,39 @@ package com.earth2me.essentials.settings;
import com.earth2me.essentials.storage.MapValueType;
import com.earth2me.essentials.storage.StorageObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.bukkit.Location;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Data @EqualsAndHashCode(callSuper = false) public class Jails implements StorageObject {
public class Jails implements StorageObject {
@MapValueType(Location.class)
private Map<String, Location> jails = new HashMap<String, Location>();
private Map<String, Location> jails = new HashMap<>();
public Map<String, Location> getJails() {
return jails;
}
public void setJails(Map<String, Location> jails) {
this.jails = jails;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Jails jails1 = (Jails) o;
return Objects.equals(jails, jails1.jails);
}
@Override
public int hashCode() {
return Objects.hash(jails);
}
}

Some files were not shown because too many files have changed in this diff Show More