Merge branch 'MV5' into world-revamp-continue

This commit is contained in:
Ben Woo 2023-09-03 15:52:56 +08:00
commit fa4391e543
No known key found for this signature in database
GPG Key ID: FB2A3645536E12C8
5 changed files with 12 additions and 898 deletions

View File

@ -1,142 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.api;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
/**
* A destination API for Multiverse
* Any plugin can add these to MV and when they are, any action that uses them (portals, MVTP, etc.) can use them!
*/
@Deprecated
public interface MVDestination {
/**
* Returns the identifier or prefix that is required for this destination.
* <p>
* Portals have a prefix of "p" for example and OpenWarp (third party plugin) uses "ow". This is derived from a
* hash and cannot have duplicate values. Read that as your plugin cannot use 'p' because it's already used.
* Please check the wiki when adding a custom destination!
*
* @return The identifier or prefix that is required for this destination.
*/
String getIdentifier();
/**
* Allows you to determine if a Destination is valid for the type it thinks it is.
* <p>
* An example of this would be the exact destination. A valid string would be: e:0,0,0 where an invalid one would
* be e:1:2:3. The first string would return true the second would return false. This is simply a convenience
* method
* and does not even NEED to be called, but it's highly recommended if you're teleporting, but it's mainly for
* Multiverse Internal use.
*
* @param plugin The plugin who the type belongs to.
* @param destination The destination string. ex: p:MyPortal:nw
*
* @return True if the destination is valid, false if not.
*/
boolean isThisType(JavaPlugin plugin, String destination);
/**
* Returns the location a specific entity will spawn at when being teleported to this Destination.
* <p>
* To just retrieve the location as it is stored you can just pass null, but be warned some destinations may return
* null back to you if you do this. It is always safer to pass an actual entity. This is used so things like
* minecarts can be teleported.
* <p>
* Do not forget to use {@link #getVelocity()} as destinations can use this too!
*
* @param entity The entity to be teleported.
*
* @return The location of the entity.
*/
Location getLocation(Entity entity);
/**
* Returns the velocity vector for this destination.
* <p>
* Plugins wishing to fully support MVDestinations MUST implement this.
*
* @return A vector representing the speed/direction the player should travel when arriving
*/
Vector getVelocity();
/**
* Sets the destination string.
* <p>
* This should be used when you want to tell this destination object about a change in where it should take people.
* The destination param should be match the result from {@link #getIdentifier()}. A valid example would be that if
* {@link #getIdentifier()} returned "ow" our destination string could be "ow:TownCenter" but could not be
* "p:HomePortal"
*
* @param plugin The plugin who the type belongs to.
* @param destination The destination string. ex: p:MyPortal:nw
*/
void setDestination(JavaPlugin plugin, String destination);
/**
* Returns true if the destination is valid and players will be taken to it.
* <p>
* Even if destinations are in the correct format (p:MyPortal) MyPortal may not exist, and therefore this would
* return false.
*
* @return True if the destination is valid; false if not.
*/
boolean isValid();
/**
* Gives you a general friendly description of the type of destination.
* <p>
* For example, the PlayerDestination sets this to "Player". You can use this to show where a player will be taken.
*
* @return A friendly string description of the type of destination.
*/
String getType();
/**
* Gives you a specific name of the destination.
* <p>
* For example, the PlayerDestination sets this to The Player's Name.
*
* @return A friendly string stating the name of the destination.
*/
String getName();
/**
* Returns a string that can easily be saved in the config that contains all the details needed to rebuild this
* destination.
* <p>
* ex: e:0,0,0:50:50
*
* @return The savable config string.
*/
String toString();
/**
* Returns the permissions string required to go here.
* <p>
* ex: multiverse.access.world
* <p>
* NOTE: This is NOT the permission to use the teleport command.
*
* @return the permissions string required to go here.
*/
String getRequiredPermission();
/**
* Should the Multiverse SafeTeleporter be used?
* <p>
* If not, MV will blindly take people to the location specified.
*
* @return True if the SafeTeleporter will be used, false if not.
*/
boolean useSafeTeleporter();
}

View File

@ -7,8 +7,8 @@
package com.onarandombox.MultiverseCore.event;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.api.SafeTTeleporter;
import com.onarandombox.MultiverseCore.destination.ParsedDestination;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -22,11 +22,11 @@ import org.bukkit.event.HandlerList;
public class MVTeleportEvent extends Event implements Cancellable {
private Player teleportee;
private CommandSender teleporter;
private MVDestination dest;
private ParsedDestination<?> dest;
private boolean useSafeTeleport;
private boolean isCancelled;
public MVTeleportEvent(MVDestination dest, Player teleportee, CommandSender teleporter, boolean safeTeleport) {
public MVTeleportEvent(ParsedDestination<?> dest, Player teleportee, CommandSender teleporter, boolean safeTeleport) {
this.teleportee = teleportee;
this.teleporter = teleporter;
this.dest = dest;
@ -83,7 +83,7 @@ public class MVTeleportEvent extends Event implements Cancellable {
*
* @return The destination the player will spawn at.
*/
public MVDestination getDestination() {
public ParsedDestination<?> getDestination() {
return this.dest;
}

View File

@ -21,9 +21,8 @@ import com.onarandombox.MultiverseCore.config.MVCoreConfig;
import com.onarandombox.MultiverseCore.economy.MVEconomist;
import com.onarandombox.MultiverseCore.event.MVRespawnEvent;
import com.onarandombox.MultiverseCore.inject.InjectableListener;
import com.onarandombox.MultiverseCore.permissions.CorePermissionsChecker;
import com.onarandombox.MultiverseCore.teleportation.TeleportQueue;
import com.onarandombox.MultiverseCore.utils.MVPermissions;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseCore.utils.result.ResultChain;
import com.onarandombox.MultiverseCore.world.entrycheck.EntryFeeResult;
import com.onarandombox.MultiverseCore.world.entrycheck.WorldEntryCheckerProvider;
@ -54,14 +53,13 @@ public class MVPlayerListener implements InjectableListener {
private final Plugin plugin;
private final MVCoreConfig config;
private final Provider<MVWorldManager> worldManagerProvider;
private final PermissionTools pt;
private final Provider<MVPermissions> mvPermsProvider;
private final SafeTTeleporter safeTTeleporter;
private final Server server;
private final TeleportQueue teleportQueue;
private final MVEconomist economist;
private final WorldEntryCheckerProvider worldEntryCheckerProvider;
private final Provider<MVCommandManager> commandManagerProvider;
private final CorePermissionsChecker permissionsChecker;
private final Map<String, String> playerWorld = new ConcurrentHashMap<String, String>();
@ -70,25 +68,24 @@ public class MVPlayerListener implements InjectableListener {
MultiverseCore plugin,
MVCoreConfig config,
Provider<MVWorldManager> worldManagerProvider,
PermissionTools permissionTools,
Provider<MVPermissions> mvPermsProvider,
SafeTTeleporter safeTTeleporter,
Server server,
TeleportQueue teleportQueue,
MVEconomist economist,
WorldEntryCheckerProvider worldEntryCheckerProvider,
Provider<MVCommandManager> commandManagerProvider) {
Provider<MVCommandManager> commandManagerProvider,
CorePermissionsChecker permissionsChecker
) {
this.plugin = plugin;
this.config = config;
this.worldManagerProvider = worldManagerProvider;
this.pt = permissionTools;
this.mvPermsProvider = mvPermsProvider;
this.safeTTeleporter = safeTTeleporter;
this.server = server;
this.teleportQueue = teleportQueue;
this.economist = economist;
this.worldEntryCheckerProvider = worldEntryCheckerProvider;
this.commandManagerProvider = commandManagerProvider;
this.permissionsChecker = permissionsChecker;
}
private MVWorldManager getWorldManager() {
@ -99,10 +96,6 @@ public class MVPlayerListener implements InjectableListener {
return commandManagerProvider.get();
}
private MVPermissions getMVPerms() {
return mvPermsProvider.get();
}
/**
* @return the playerWorld-map
*/
@ -173,7 +166,7 @@ public class MVPlayerListener implements InjectableListener {
} else {
Logging.finer("Player joined AGAIN!");
if (config.getEnforceAccess() // check this only if we're enforcing access!
&& !this.getMVPerms().hasPermission(p, "multiverse.access." + p.getWorld().getName(), false)) {
&& !permissionsChecker.hasWorldAccessPermission(p, getWorldManager().getFirstSpawnWorld())) {
p.sendMessage("[MV] - Sorry you can't be in this world anymore!");
this.sendPlayerToDefaultWorld(p);
}
@ -350,7 +343,7 @@ public class MVPlayerListener implements InjectableListener {
new Runnable() {
@Override
public void run() {
if (!MVPlayerListener.this.pt.playerCanIgnoreGameModeRestriction(world, player)) {
if (!permissionsChecker.hasGameModeBypassPermission(player, world)) {
// Check that the player is in the new world and they haven't been teleported elsewhere or the event cancelled.
if (player.getWorld() == world.getCBWorld()) {
Logging.fine("Handling gamemode for player: %s, Changing to %s", player.getName(), world.getGameMode().toString());

View File

@ -1,415 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.utils;
import java.util.List;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.MVDestination;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MVWorld;
import com.onarandombox.MultiverseCore.config.MVCoreConfig;
import jakarta.inject.Inject;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager;
import org.jvnet.hk2.annotations.Service;
/**
* Multiverse's permission checker
*/
@Service
public class MVPermissions {
private final PluginManager pluginManager;
private final MVCoreConfig config;
private final MVWorldManager worldMgr;
@Inject
public MVPermissions(
PluginManager pluginManager,
MVCoreConfig config,
MVWorldManager worldManager
) {
this.pluginManager = pluginManager;
this.config = config;
this.worldMgr = worldManager;
}
/**
* Check if a Player can ignore GameMode restrictions for world they travel to.
*
* @param p The {@link Player} to check.
* @param w The {@link MVWorld} the player wants to teleport to.
* @return True if they should bypass restrictions.
*/
public boolean canIgnoreGameModeRestriction(Player p, MVWorld w) {
return p.hasPermission("mv.bypass.gamemode." + w.getName());
}
/**
* Check if a Player can teleport to the Destination world from there current world.
*
* @param p The {@link Player} to check.
* @param w The {@link MVWorld} the player wants to teleport to.
* @return Whether the player can teleport to the given {@link MVWorld}.
*/
public boolean canTravelFromWorld(Player p, MVWorld w) {
List<String> blackList = w.getWorldBlacklist();
boolean returnValue = true;
for (String s : blackList) {
if (s.equalsIgnoreCase(p.getWorld().getName())) {
returnValue = false;
break;
}
}
return returnValue;
}
/**
* Checks if the specified {@link CommandSender} can travel to the specified {@link Location}.
* @param sender The {@link CommandSender}.
* @param location The {@link Location}.
* @return Whether the {@link CommandSender} can travel to the specified {@link Location}.
*/
public boolean canTravelFromLocation(CommandSender sender, Location location) {
// Now The Bed destination can return null now.
if (location == null) {
return false;
}
if (!(sender instanceof Player)) {
return true;
}
Player teleporter = (Player) sender;
if (!this.worldMgr.isMVWorld(location.getWorld().getName())) {
return false;
}
return canTravelFromWorld(teleporter, this.worldMgr.getMVWorld(location.getWorld().getName()));
}
/**
* Check if the Player has the permissions to enter this world.
*
* @param p The {@link Player} player that wants to enter
* @param w The {@link MVWorld} he wants to enter
* @return Whether he has the permission to enter the world
*/
public boolean canEnterWorld(Player p, MVWorld w) {
// If we're not enforcing access, anyone can enter.
if (!config.getEnforceAccess()) {
Logging.finest("EnforceAccess is OFF. Player was allowed in " + w.getAlias());
return true;
}
return this.hasPermission(p, "multiverse.access." + w.getName(), false);
}
private boolean canEnterLocation(Player p, Location l) {
if (l == null) {
return false;
}
String worldName = l.getWorld().getName();
if (!this.worldMgr.isMVWorld(worldName)) {
return false;
}
return this.hasPermission(p, "multiverse.access." + worldName, false);
}
/**
* Check to see if a sender can enter a destination.
* The reason this is not a player, is it can be used to simply check permissions
* The console should, for exmaple, always see all worlds
*
* @param sender The CommandSender to check.
* @param d The destination they are requesting.
* @return True if that sender can go to that destination
*/
public boolean canEnterDestination(CommandSender sender, MVDestination d) {
if (!(sender instanceof Player)) {
return true;
}
Player p = (Player) sender;
if (d == null || d.getLocation(p) == null) {
return false;
}
String worldName = d.getLocation(p).getWorld().getName();
if (!this.worldMgr.isMVWorld(worldName)) {
return false;
}
if (!canEnterLocation(p, d.getLocation(p))) {
return false;
}
return this.hasPermission(p, d.getRequiredPermission(), false);
}
/**
* Tells a {@link CommandSender} why another {@link CommandSender} can or can not access a certain {@link MVDestination}.
* @param asker The {@link CommandSender} that's asking.
* @param playerInQuestion The {@link CommandSender} whose permissions we want to know.
* @param d The {@link MVDestination}.
*/
public void tellMeWhyICantDoThis(CommandSender asker, CommandSender playerInQuestion, MVDestination d) {
boolean cango = true;
if (!(playerInQuestion instanceof Player)) {
asker.sendMessage(String.format("The console can do %severything%s.", ChatColor.RED, ChatColor.WHITE));
return;
}
Player p = (Player) playerInQuestion;
if (d == null) {
asker.sendMessage(String.format("The provided Destination is %sNULL%s, and therefore %sINVALID%s.",
ChatColor.RED, ChatColor.WHITE, ChatColor.RED, ChatColor.WHITE));
cango = false;
}
// We know it'll be a player here due to the first line of this method.
if (d.getLocation(p) == null) {
asker.sendMessage(String.format(
"The player will spawn at an %sindeterminate location%s. Talk to the MV Devs if you see this",
ChatColor.RED, ChatColor.WHITE));
cango = false;
}
String worldName = d.getLocation(p).getWorld().getName();
if (!this.worldMgr.isMVWorld(worldName)) {
asker.sendMessage(String.format("The destination resides in a world(%s%s%s) that is not managed by Multiverse.",
ChatColor.AQUA, worldName, ChatColor.WHITE));
asker.sendMessage(String.format("Type %s/mv import ?%s to see the import command's help page.",
ChatColor.DARK_AQUA, ChatColor.WHITE));
cango = false;
}
if (!this.hasPermission(p, "multiverse.access." + worldName, false)) {
asker.sendMessage(String.format("The player (%s%s%s) does not have the required world entry permission (%s%s%s) to go to the destination (%s%s%s).",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, "multiverse.access." + worldName, ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
cango = false;
}
if (!this.hasPermission(p, d.getRequiredPermission(), false)) {
asker.sendMessage(String.format("The player (%s%s%s) does not have the required entry permission (%s%s%s) to go to the destination (%s%s%s).",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, d.getRequiredPermission(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
cango = false;
}
if (cango) {
asker.sendMessage(String.format("The player (%s%s%s) CAN go to the destination (%s%s%s).",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
} else {
asker.sendMessage(String.format("The player (%s%s%s) cannot access the destination %s%s%s. Therefore they can't use mvtp at all for this.",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
return;
}
if (!this.hasPermission(p, "multiverse.teleport.self." + d.getIdentifier(), false)) {
asker.sendMessage(String.format("The player (%s%s%s) does not have the required teleport permission (%s%s%s) to use %s/mvtp %s%s.",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, "multiverse.teleport.self." + d.getIdentifier(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
} else {
asker.sendMessage(String.format("The player (%s%s%s) has the required teleport permission (%s%s%s) to use %s/mvtp %s%s.",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, "multiverse.teleport.self." + d.getIdentifier(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
}
if (!this.hasPermission(p, "multiverse.teleport.other." + d.getIdentifier(), false)) {
asker.sendMessage(String.format("The player (%s%s%s) does not have the required teleport permission (%s%s%s) to send others to %s%s%s via mvtp.",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, "multiverse.teleport.other." + d.getIdentifier(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
} else {
asker.sendMessage(String.format("The player (%s%s%s) has required teleport permission (%s%s%s) to send others to %s%s%s via mvtp.",
ChatColor.AQUA, p.getDisplayName(), ChatColor.WHITE,
ChatColor.GREEN, "multiverse.teleport.other." + d.getIdentifier(), ChatColor.WHITE,
ChatColor.DARK_AQUA, d.getName(), ChatColor.WHITE));
}
}
/**
* Check to see if a player has a permission.
*
* @param sender Who is requesting the permission.
* @param node The permission node in string format; multiverse.core.list.worlds for example.
* @param isOpRequired deprecated This is not used for anything anymore.
* @return True if they have that permission or any parent.
*/
public boolean hasPermission(CommandSender sender, String node, boolean isOpRequired) {
if (!(sender instanceof Player)) {
return true;
}
// NO one can access a null permission (mainly used for destinations):w
if (node == null) {
return false;
}
// Everyone can access an empty permission
// Currently used for the PlayerDestination
if (node.equals("")) {
return true;
}
return checkActualPermission(sender, node);
}
// TODO: Better player checks, most likely not needed, but safer.
private boolean checkActualPermission(CommandSender sender, String node) {
Player player = (Player) sender;
boolean hasPermission = sender.hasPermission(node);
if (!sender.isPermissionSet(node)) {
Logging.finer(String.format("The node [%s%s%s] was %sNOT%s set for [%s%s%s].",
ChatColor.RED, node, ChatColor.WHITE, ChatColor.RED, ChatColor.WHITE, ChatColor.AQUA,
player.getDisplayName(), ChatColor.WHITE));
}
if (hasPermission) {
Logging.finer("Checking to see if player [" + player.getName() + "] has permission [" + node + "]... YES");
} else {
Logging.finer("Checking to see if player [" + player.getName() + "] has permission [" + node + "]... NO");
}
return hasPermission;
}
/**
* Checks to see if the sender has any parent perms.
* Stops when it finds one or when there are no more parents.
* This method is recursive.
*
* @param sender Who is asking for the permission.
* @param node The permission node to check (possibly already a parent).
* @return True if they have any parent perm, false if none.
*/
// TODO: remove this...?
private boolean hasAnyParentPermission(CommandSender sender, String node) {
String parentPerm = this.pullOneLevelOff(node);
// Base case
if (parentPerm == null) {
return false;
}
// If they have a parent, they're good
if (this.checkActualPermission(sender, parentPerm + ".*")) {
return true;
}
return hasAnyParentPermission(sender, parentPerm);
}
/**
* Pulls one level off of a yaml style node.
* Given multiverse.core.list.worlds will return multiverse.core.list
*
* @param node The root node to check.
* @return The parent of the node
*/
private static String pullOneLevelOff(String node) {
if (node == null) {
return null;
}
int index = node.lastIndexOf(".");
if (index > 0) {
return node.substring(0, index);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean hasAnyPermission(CommandSender sender, List<String> nodes, boolean isOpRequired) {
for (String node : nodes) {
if (this.hasPermission(sender, node, isOpRequired)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean hasAllPermission(CommandSender sender, List<String> nodes, boolean isOpRequired) {
for (String node : nodes) {
if (!this.hasPermission(sender, node, isOpRequired)) {
return false;
}
}
return true;
}
/**
* Adds a permission.
* @param string The permission as {@link String}.
* @param defaultValue The default-value.
* @return The permission as {@link Permission}.
*/
public Permission addPermission(String string, PermissionDefault defaultValue) {
if (this.pluginManager.getPermission(string) == null) {
Permission permission = new Permission(string, defaultValue);
this.pluginManager.addPermission(permission);
this.addToParentPerms(string);
}
return this.pluginManager.getPermission(string);
}
private void addToParentPerms(String permString) {
String permStringChopped = permString.replace(".*", "");
String[] seperated = permStringChopped.split("\\.");
String parentPermString = getParentPerm(seperated);
if (parentPermString == null) {
addToRootPermission("*", permStringChopped);
addToRootPermission("*.*", permStringChopped);
return;
}
Permission parentPermission = this.pluginManager.getPermission(parentPermString);
// Creat parent and grandparents
if (parentPermission == null) {
parentPermission = new Permission(parentPermString);
this.pluginManager.addPermission(parentPermission);
this.addToParentPerms(parentPermString);
}
// Create actual perm.
Permission actualPermission = this.pluginManager.getPermission(permString);
// Extra check just to make sure the actual one is added
if (actualPermission == null) {
actualPermission = new Permission(permString);
this.pluginManager.addPermission(actualPermission);
}
if (!parentPermission.getChildren().containsKey(permString)) {
parentPermission.getChildren().put(actualPermission.getName(), true);
this.pluginManager.recalculatePermissionDefaults(parentPermission);
}
}
private void addToRootPermission(String rootPerm, String permStringChopped) {
Permission rootPermission = this.pluginManager.getPermission(rootPerm);
if (rootPermission == null) {
rootPermission = new Permission(rootPerm);
this.pluginManager.addPermission(rootPermission);
}
rootPermission.getChildren().put(permStringChopped + ".*", true);
this.pluginManager.recalculatePermissionDefaults(rootPermission);
}
/**
* If the given permission was 'multiverse.core.tp.self', this would return 'multiverse.core.tp.*'.
*/
private static String getParentPerm(String[] seperated) {
if (seperated.length == 1) {
return null;
}
String returnString = "";
for (int i = 0; i < seperated.length - 1; i++) {
returnString += seperated[i] + ".";
}
return returnString + "*";
}
}

View File

@ -1,322 +0,0 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.utils;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.MultiverseCore.api.MVWorld;
import com.onarandombox.MultiverseCore.config.MVCoreConfig;
import com.onarandombox.MultiverseCore.economy.MVEconomist;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.jvnet.hk2.annotations.Service;
/**
* Utility-class for permissions.
*/
@Service
public class PermissionTools {
private final MVCoreConfig config;
private final PluginManager pluginManager;
private final Provider<MVPermissions> mvPermsProvider;
private final MVEconomist economist;
@Inject
public PermissionTools(
MVCoreConfig config,
PluginManager pluginManager,
Provider<MVPermissions> mvPermsProvider,
MVEconomist economist)
{
this.config = config;
this.pluginManager = pluginManager;
this.mvPermsProvider = mvPermsProvider;
this.economist = economist;
}
private MVPermissions getMVPerms() {
return this.mvPermsProvider.get();
}
/**
* Adds a permission to the parent-permissions.
* @param permString The new permission as {@link String}.
*/
public void addToParentPerms(String permString) {
String permStringChopped = permString.replace(".*", "");
String[] seperated = permStringChopped.split("\\.");
String parentPermString = getParentPerm(seperated);
if (parentPermString == null) {
addToRootPermission("*", permStringChopped);
addToRootPermission("*.*", permStringChopped);
return;
}
Permission parentPermission = this.pluginManager.getPermission(parentPermString);
// Creat parent and grandparents
if (parentPermission == null) {
parentPermission = new Permission(parentPermString);
this.pluginManager.addPermission(parentPermission);
this.addToParentPerms(parentPermString);
}
// Create actual perm.
Permission actualPermission = this.pluginManager.getPermission(permString);
// Extra check just to make sure the actual one is added
if (actualPermission == null) {
actualPermission = new Permission(permString);
this.pluginManager.addPermission(actualPermission);
}
if (!parentPermission.getChildren().containsKey(permString)) {
parentPermission.getChildren().put(actualPermission.getName(), true);
this.pluginManager.recalculatePermissionDefaults(parentPermission);
}
}
private void addToRootPermission(String rootPerm, String permStringChopped) {
Permission rootPermission = this.pluginManager.getPermission(rootPerm);
if (rootPermission == null) {
rootPermission = new Permission(rootPerm);
this.pluginManager.addPermission(rootPermission);
}
rootPermission.getChildren().put(permStringChopped + ".*", true);
this.pluginManager.recalculatePermissionDefaults(rootPermission);
}
/**
* If the given permission was 'multiverse.core.tp.self', this would return 'multiverse.core.tp.*'.
*
* @param separatedPermissionString The array of a dot separated perm string.
* @return The dot separated parent permission string.
*/
private static String getParentPerm(String[] separatedPermissionString) {
if (separatedPermissionString.length == 1) {
return null;
}
String returnString = "";
for (int i = 0; i < separatedPermissionString.length - 1; i++) {
returnString += separatedPermissionString[i] + ".";
}
return returnString + "*";
}
/**
* Checks if the given {@link Player} has enough money to enter the specified {@link MVWorld}.
* @param fromWorld The {@link MVWorld} the player is coming from.
* @param toWorld The {@link MVWorld} the player is going to.
* @param teleporter The teleporter.
* @param teleportee The teleportee.
* @param pay If the player has to pay the money.
* @return True if the player can enter the world.
*/
public boolean playerHasMoneyToEnter(MVWorld fromWorld, MVWorld toWorld, CommandSender teleporter, Player teleportee, boolean pay) {
Player teleporterPlayer;
if (config.getTeleportIntercept()) {
if (teleporter instanceof ConsoleCommandSender) {
return true;
}
if (teleporter == null) {
teleporter = teleportee;
}
if (!(teleporter instanceof Player)) {
return false;
}
teleporterPlayer = (Player) teleporter;
} else {
if (teleporter instanceof Player) {
teleporterPlayer = (Player) teleporter;
} else {
teleporterPlayer = null;
}
// Old-style!
if (teleporterPlayer == null) {
return true;
}
}
// If the toWorld isn't controlled by MV,
// We don't care.
if (toWorld == null) {
return true;
}
// Only check payments if it's a different world:
if (!toWorld.equals(fromWorld)) {
final double price = toWorld.getPrice();
// Don't bother checking economy stuff if it doesn't even cost to enter.
if (price == 0D) {
return true;
}
// If the player does not have to pay, return now.
if (this.getMVPerms().hasPermission(teleporter, toWorld.getExemptPermission().getName(), true)) {
return true;
}
final Material currency = toWorld.getCurrency();
final String formattedAmount = economist.formatPrice(price, currency);
if (economist.isPlayerWealthyEnough(teleporterPlayer, price, currency)) {
if (pay) {
if (price < 0D) {
economist.deposit(teleporterPlayer, -price, currency);
} else {
economist.withdraw(teleporterPlayer, price, currency);
}
sendTeleportPaymentMessage(economist, teleporterPlayer, teleportee, toWorld.getColoredWorldString(), price, currency);
}
} else {
if (teleportee.equals(teleporter)) {
teleporterPlayer.sendMessage(economist.getNSFMessage(currency,
"You need " + formattedAmount + " to enter " + toWorld.getColoredWorldString()));
} else {
teleporterPlayer.sendMessage(economist.getNSFMessage(currency,
"You need " + formattedAmount + " to send " + teleportee.getName() + " to " + toWorld.getColoredWorldString()));
}
return false;
}
}
return true;
}
private void sendTeleportPaymentMessage (MVEconomist economist, Player teleporterPlayer, Player teleportee, String toWorld, double price, Material currency) {
price = Math.abs(price);
if (teleporterPlayer.equals(teleportee)) {
teleporterPlayer.sendMessage("You were " + (price > 0D ? "charged " : "given ") + economist.formatPrice(price, currency) + " for teleporting to " + toWorld);
} else {
teleporterPlayer.sendMessage("You were " + (price > 0D ? "charged " : "given ") + economist.formatPrice(price, currency) + " for teleporting " + teleportee.getName() + " to " + toWorld);
}
}
/**
* Checks to see if player can go to a world given their current status.
* <p>
* The return is a little backwards, and will return a value safe for event.setCancelled.
*
* @param fromWorld The MultiverseWorld they are in.
* @param toWorld The MultiverseWorld they want to go to.
* @param teleporter The CommandSender that wants to send someone somewhere. If null,
* will be given the same value as teleportee.
* @param teleportee The player going somewhere.
* @return True if they can't go to the world, False if they can.
*/
public boolean playerCanGoFromTo(MVWorld fromWorld, MVWorld toWorld, CommandSender teleporter, Player teleportee) {
Logging.finest("Checking '" + teleporter + "' can send '" + teleportee + "' somewhere");
Player teleporterPlayer;
if (config.getTeleportIntercept()) {
// The console can send anyone anywhere
if (teleporter instanceof ConsoleCommandSender) {
return true;
}
// Make sure we have a teleporter of some kind, even if it's inferred to be the teleportee
if (teleporter == null) {
teleporter = teleportee;
}
// Now make sure we can cast the teleporter to a player, 'cause I'm tired of console things now
if (!(teleporter instanceof Player)) {
return false;
}
teleporterPlayer = (Player) teleporter;
} else {
if (teleporter instanceof Player) {
teleporterPlayer = (Player) teleporter;
} else {
teleporterPlayer = null;
}
// Old-style!
if (teleporterPlayer == null) {
return true;
}
}
// Actual checks
if (toWorld != null) {
if (!this.getMVPerms().canEnterWorld(teleporterPlayer, toWorld)) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("You don't have access to go here...");
} else {
teleporter.sendMessage("You can't send " + teleportee.getName() + " here...");
}
return false;
}
} else {
// TODO: Determine if this value is false because a world didn't exist
// or if it was because a world wasn't imported.
return true;
}
if (fromWorld != null) {
if (fromWorld.getWorldBlacklist().contains(toWorld.getName())) {
if (teleportee.equals(teleporter)) {
teleporter.sendMessage("You don't have access to go to " + toWorld.getColoredWorldString() + " from " + fromWorld.getColoredWorldString());
} else {
teleporter.sendMessage("You don't have access to send " + teleportee.getName() + " from "
+ fromWorld.getColoredWorldString() + " to " + toWorld.getColoredWorldString());
}
return false;
}
}
return true;
}
/**
* Checks to see if a player can bypass the player limit.
*
* @param toWorld The world travelling to.
* @param teleporter The player that initiated the teleport.
* @param teleportee The player travelling.
* @return True if they can bypass the player limit.
*/
public boolean playerCanBypassPlayerLimit(MVWorld toWorld, CommandSender teleporter, Player teleportee) {
if (teleporter == null) {
teleporter = teleportee;
}
if (!(teleporter instanceof Player)) {
return true;
}
if (getMVPerms().hasPermission(teleportee, "mv.bypass.playerlimit." + toWorld.getName(), false)) {
return true;
} else {
teleporter.sendMessage("The world " + toWorld.getColoredWorldString() + " is full");
return false;
}
}
/**
* Checks to see if a player should bypass game mode restrictions.
*
* @param toWorld world travelling to.
* @param teleportee player travelling.
* @return True if they should bypass restrictions
*/
public boolean playerCanIgnoreGameModeRestriction(MVWorld toWorld, Player teleportee) {
if (toWorld != null) {
return this.getMVPerms().canIgnoreGameModeRestriction(teleportee, toWorld);
} else {
// TODO: Determine if this value is false because a world didn't exist
// or if it was because a world wasn't imported.
return true;
}
}
}