In progress: Using MassiveCraftCore and Allman indentation style and minor refactoring.

This commit is contained in:
Olof Larsson 2011-10-08 22:03:44 +02:00
parent 61998f459d
commit 0ce9cce9d3
75 changed files with 4605 additions and 2033 deletions

BIN
lib/PermissionsEx.jar Normal file

Binary file not shown.

Binary file not shown.

View File

@ -23,8 +23,9 @@ import com.massivecraft.factions.util.DiscUtil;
import com.massivecraft.factions.util.TextUtil;
public class Board {
private static transient File file = new File(Factions.instance.getDataFolder(), "board.json");
public class Board
{
private static transient File file = new File(P.p.getDataFolder(), "board.json");
private static transient HashMap<FLocation, Integer> flocationIds = new HashMap<FLocation, Integer>();
//----------------------------------------------//
@ -114,7 +115,7 @@ public class Board {
while (iter.hasNext()) {
Entry<FLocation, Integer> entry = iter.next();
if ( ! Faction.exists(entry.getValue())) {
Factions.log("Board cleaner removed "+entry.getValue()+" from "+entry.getKey());
P.log("Board cleaner removed "+entry.getValue()+" from "+entry.getKey());
iter.remove();
}
}
@ -282,10 +283,10 @@ public class Board {
//Factions.log("Saving board to disk");
try {
DiscUtil.write(file, Factions.instance.gson.toJson(dumpAsSaveFormat()));
DiscUtil.write(file, P.p.gson.toJson(dumpAsSaveFormat()));
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to save the board to disk.");
P.log("Failed to save the board to disk.");
return false;
}
@ -293,35 +294,35 @@ public class Board {
}
public static boolean load() {
Factions.log("Loading board from disk");
P.log("Loading board from disk");
if ( ! file.exists()) {
if ( ! loadOld())
Factions.log("No board to load from disk. Creating new file.");
P.log("No board to load from disk. Creating new file.");
save();
return true;
}
try {
Type type = new TypeToken<Map<String,Map<String,Integer>>>(){}.getType();
Map<String,Map<String,Integer>> worldCoordIds = Factions.instance.gson.fromJson(DiscUtil.read(file), type);
Map<String,Map<String,Integer>> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type);
loadFromSaveFormat(worldCoordIds);
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to load the board from disk.");
P.log("Failed to load the board from disk.");
return false;
}
return true;
}
private static boolean loadOld() {
File folderBoard = new File(Factions.instance.getDataFolder(), "board");
/*private static boolean loadOld() {
File folderBoard = new File(P.p.getDataFolder(), "board");
if ( ! folderBoard.isDirectory())
return false;
Factions.log("Board file doesn't exist, attempting to load old pre-1.1 data.");
P.log("Board file doesn't exist, attempting to load old pre-1.1 data.");
String ext = ".json";
@ -350,14 +351,14 @@ public class Board {
int factionId = coordDat.get(1).getAsInt();
flocationIds.put(new FLocation(name, coordX, coordZ), factionId);
}
Factions.log("loaded pre-1.1 board "+name);
P.log("loaded pre-1.1 board "+name);
} catch (Exception e) {
e.printStackTrace();
Factions.log(Level.WARNING, "failed to load board "+name);
P.log(Level.WARNING, "failed to load board "+name);
}
}
return true;
}
}*/
}

View File

@ -1,27 +1,28 @@
package com.massivecraft.factions;
import java.io.File;
import java.util.*;
import org.bukkit.*;
import org.bukkit.entity.CreatureType;
import com.massivecraft.factions.util.DiscUtil;
public class Conf {
public static final transient File file = new File(Factions.instance.getDataFolder(), "conf.json");
public class Conf
{
// track players with admin access who have enabled "admin bypass" mode, and should therefore be able to build anywhere
// not worth saving between server restarts, I think
public static transient Set<String> adminBypassPlayers = Collections.synchronizedSet(new HashSet<String>());
// Colors
public static ChatColor colorMember = ChatColor.GREEN;
public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE;
public static ChatColor colorNeutral = ChatColor.WHITE;
public static ChatColor colorEnemy = ChatColor.RED;
/*
public static ChatColor colorSystem = ChatColor.YELLOW;
public static ChatColor colorChrome = ChatColor.GOLD;
public static ChatColor colorCommand = ChatColor.AQUA;
public static ChatColor colorParameter = ChatColor.DARK_AQUA;
*/
// Power
public static double powerPlayerMax = 10.0;
public static double powerPlayerMin = -10.0;
@ -39,10 +40,10 @@ public class Conf {
public static int factionTagLengthMax = 10;
public static boolean factionTagForceUpperCase = false;
public static boolean newFactionsDefaultOpen = true;
public static boolean newFactionsDefaultOpen = false;
// what faction ID to start new players in when they first join the server; default is 0, "no faction"
public static int newPlayerStartingFactionID = 0;
public static String newPlayerStartingFactionID = "0";
public static boolean showMapFactionKey = true;
public static boolean showNeutralFactionsOnMap = true;
@ -183,7 +184,7 @@ public class Conf {
// Spout features
public static boolean spoutFactionTagsOverNames = true;
public static boolean spoutFactionTitlesOverNames = true;
public static boolean spoutFactionAdminCapes = true;
public static boolean spoutFactionAdminCapes = true; // TODO: What are these for?
public static boolean spoutFactionModeratorCapes = true;
public static int spoutTerritoryDisplayPosition = 3;
public static String capeAlly = "https://github.com/MassiveCraft/Factions/raw/master/capes/ally.png";
@ -236,7 +237,8 @@ public class Conf {
public static transient int mapWidth = 39;
public static transient char[] mapKeyChrs = "\\/#?$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz".toCharArray();
static {
static
{
territoryEnemyDenyCommands.add("home");
territoryEnemyDenyCommands.add("sethome");
territoryEnemyDenyCommands.add("spawn");
@ -281,45 +283,17 @@ public class Conf {
safeZoneNerfedCreatureTypes.add(CreatureType.ZOMBIE);
}
// track players with admin access who have enabled "admin bypass" mode, and should therefore be able to build anywhere
// not worth saving between server restarts, I think
public static transient Set<String> adminBypassPlayers = Collections.synchronizedSet(new HashSet<String>());
// -------------------------------------------- //
// Persistance
// -------------------------------------------- //
public static boolean save() {
//Factions.log("Saving config to disk.");
try {
DiscUtil.write(file, Factions.instance.gson.toJson(new Conf()));
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to save the config to disk.");
return false;
private static transient Conf i = new Conf();
public static void load()
{
P.p.persist.loadOrSaveDefault(i, Conf.class, "conf");
}
return true;
}
public static boolean load() {
Factions.log("Loading conf from disk");
if ( ! file.exists()) {
Factions.log("No conf to load from disk. Creating new file.");
save();
return true;
}
try {
Factions.instance.gson.fromJson(DiscUtil.read(file), Conf.class);
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to load the config from disk.");
return false;
}
return true;
public static void save()
{
P.p.persist.save(i);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,110 @@
package com.massivecraft.factions;
import java.io.File;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.zcore.persist.PlayerEntityCollection;
public class FPlayers extends PlayerEntityCollection<FPlayer>
{
public static FPlayers i = new FPlayers();
P p = P.p;
private FPlayers()
{
super
(
FPlayer.class,
new CopyOnWriteArrayList<FPlayer>(),
new ConcurrentSkipListMap<String, FPlayer>(String.CASE_INSENSITIVE_ORDER),
new File(P.p.getDataFolder(), "players.json"),
P.p.gson
);
this.setCreative(true);
}
@Override
public Type getMapType()
{
return new TypeToken<Map<String, FPlayer>>(){}.getType();
}
public void clean()
{
for (FPlayer fplayer : this.get())
{
if ( ! Factions.i.exists(fplayer.getFactionId()))
{
p.log("Reset faction data (invalid faction) for player "+fplayer.getName());
fplayer.resetFactionData();
}
}
}
public void autoLeaveOnInactivityRoutine()
{
if (Conf.autoLeaveAfterDaysOfInactivity <= 0.0)
{
return;
}
long now = System.currentTimeMillis();
double toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000;
for (FPlayer fplayer : FPlayers.i.get())
{
if (now - fplayer.getLastLoginTime() > toleranceMillis)
{
fplayer.leave(false);
fplayer.markForDeletion(true);
}
}
}
// TODO: Intressant.... denna skulle jag kanske behöva undersöka lite mer... lägga till i core?
// En form av match player name...
public FPlayer find(String playername)
{
for (FPlayer fplayer : this.get())
{
if (fplayer.getId().equalsIgnoreCase(playername) || fplayer.getId().startsWith(playername))
{
return fplayer;
}
}
return null;
}
/*public Set<VPlayer> findAllOnlineInfected()
{
Set<VPlayer> vplayers = new HashSet<VPlayer>();
for (VPlayer vplayer : this.getOnline())
{
if (vplayer.isInfected())
{
vplayers.add(vplayer);
}
}
return vplayers;
}
public Set<VPlayer> findAllOnlineVampires()
{
Set<VPlayer> vplayers = new HashSet<VPlayer>();
for (VPlayer vplayer : this.getOnline())
{
if (vplayer.isVampire())
{
vplayers.add(vplayer);
}
}
return vplayers;
}*/
}

View File

@ -15,38 +15,129 @@ import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.*;
import com.massivecraft.factions.zcore.persist.Entity;
public class Faction {
public class Faction extends Entity
{
// FIELD: relationWish
private Map<String, Relation> relationWish;
// -------------------------------------------- //
// Fields
// -------------------------------------------- //
private static transient Map<Integer, Faction> instances = new HashMap<Integer, Faction>();
private static transient File file = new File(Factions.instance.getDataFolder(), "factions.json");
private static transient int nextId;
private transient int id;
private Map<Integer, Relation> relationWish;
// FIELD: claimOwnership
private Map<FLocation, Set<String>> claimOwnership = new ConcurrentHashMap<FLocation, Set<String>>();
private Set<String> invites; // Where string is a lowercase player name
// FIELD: invites
// Where string is a lowercase player name
private Set<String> invites;
public void invite(FPlayer fplayer) { this.invites.add(fplayer.getName().toLowerCase()); }
public void deinvite(FPlayer fplayer) { this.invites.remove(fplayer.getName().toLowerCase()); }
public boolean isInvited(FPlayer fplayer) { return this.invites.contains(fplayer.getName().toLowerCase()); }
// FIELD: open
private boolean open;
public boolean getOpen() { return open; }
public void setOpen(boolean isOpen) { open = isOpen; }
// FIELD: peaceful
// "peaceful" status can only be set by server admins/moderators/ops, and prevents PvP and land capture to/from the faction
private boolean peaceful;
public boolean isPeaceful() { return this.peaceful; }
public void setPeaceful(boolean isPeaceful) { this.peaceful = isPeaceful; }
// FIELD: peacefulExplosionsEnabled
private boolean peacefulExplosionsEnabled;
public void setPeacefulExplosions(boolean disable) { peacefulExplosionsEnabled = disable; } //TODO: Convert to argswitch in command!!
public void setPeacefulExplosions() { setPeacefulExplosions(!peacefulExplosionsEnabled); }
// FIELD: permanent
// "permanent" status can only be set by server admins/moderators/ops, and allows the faction to remain even with 0 members
private boolean permanent;
public boolean isPermanent() { return permanent; }
public void setPermanent(boolean isPermanent) { permanent = isPermanent; }
// FIELD: tag
private String tag;
public String getTag() { return this.tag; }
public String getTag(String prefix) { return prefix+this.tag; }
public String getTag(Faction otherFaction)
{
if (otherFaction == null)
{
return getTag();
}
return this.getTag(otherFaction.getRelationColor(this).toString());
}
public String getTag(FPlayer otherFplayer) {
if (otherFplayer == null)
{
return getTag();
}
return this.getTag(otherFplayer.getRelationColor(this).toString());
}
public void setTag(String str)
{
if (Conf.factionTagForceUpperCase)
{
str = str.toUpperCase();
}
this.tag = str;
}
public String getComparisonTag() { return MiscUtil.getComparisonString(this.tag); }
// FIELD: description
private String description;
public String getDescription() { return this.description; }
public void setDescription(String value) { this.description = value; }
// FIELD: home
private Location home;
public void setHome(Location home) { this.home = home; }
public Location getHome() { confirmValidHome(); return home; }
public boolean hasHome() { return this.getHome() != null; }
public void confirmValidHome()
{
if (!Conf.homesMustBeInClaimedTerritory || this.home == null || Board.getFactionAt(new FLocation(this.home)) == this)
{
return;
}
sendMessage("Your faction home has been un-set since it is no longer in your territory.");
this.home = null;
}
// FIELD: lastPlayerLoggedOffTime
private transient long lastPlayerLoggedOffTime;
// FIELD: money
// Bank functions
private double money;
public double getMoney() { return this.money; }
public boolean addMoney(double amount)
{
if ( amount > 0.0 )
{
this.money += amount;
return true;
}
return false;
}
public boolean removeMoney( double amount )
{
if (amount <= 0.0 ) return false;
if (amount > this.money ) return false;
this.money -= amount;
return true;
}
// -------------------------------------------- //
// Construct
// -------------------------------------------- //
public Faction() {
this.relationWish = new HashMap<Integer, Relation>();
public Faction()
{
this.relationWish = new HashMap<String, Relation>();
this.invites = new HashSet<String>();
this.open = Conf.newFactionsDefaultOpen;
this.tag = "???";
@ -59,188 +150,97 @@ public class Faction {
}
// -------------------------------------------- //
// Getters And Setters
// Extra Getters And Setters
// -------------------------------------------- //
public int getId() {
return this.id;
}
public boolean noPvPInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); }
public boolean getOpen() {
return open;
}
public boolean noMonstersInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); }
public void setOpen(boolean isOpen) {
open = isOpen;
}
public String getTag() {
return this.getTag("");
}
public String getTag(String prefix) {
return prefix+this.tag;
}
public String getTag(Faction otherFaction) {
if (otherFaction == null)
return getTag();
else
return this.getTag(otherFaction.getRelationColor(this).toString());
}
public String getTag(FPlayer otherFplayer) {
if (otherFplayer == null)
return getTag();
else
return this.getTag(otherFplayer.getRelationColor(this).toString());
}
public void setTag(String str) {
if (Conf.factionTagForceUpperCase) {
str = str.toUpperCase();
}
this.tag = str;
}
public String getDescription() {
return this.description;
}
public void setDescription(String value) {
this.description = value;
}
public void setHome(Location home) {
this.home = home;
}
public Location getHome() {
confirmValidHome();
return home;
}
public boolean hasHome() {
confirmValidHome();
return this.home != null;
}
public void confirmValidHome() {
if (!Conf.homesMustBeInClaimedTerritory || this.home == null || Board.getFactionAt(new FLocation(this.home)) == this) {
return;
}
sendMessage("Your faction home has been un-set since it is no longer in your territory.");
this.home = null;
}
// "peaceful" status can only be set by server admins/moderators/ops, and prevents PvP and land capture to/from the faction
public boolean isPeaceful() {
return peaceful;
}
public void setPeaceful(boolean isPeaceful) {
peaceful = isPeaceful;
}
// "permanent" status can only be set by server admins/moderators/ops, and allows the faction to remain even with 0 members
public boolean isPermanent() {
return permanent;
}
public void setPermanent(boolean isPermanent) {
permanent = isPermanent;
}
public void setPeacefulExplosions(boolean disable) {
peacefulExplosionsEnabled = disable;
}
public void setPeacefulExplosions() {
setPeacefulExplosions(!peacefulExplosionsEnabled);
}
public boolean noPvPInTerritory() {
return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP);
}
public boolean noMonstersInTerritory() {
return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters);
}
public boolean noExplosionsInTerritory() {
return peaceful && !peacefulExplosionsEnabled;
}
public boolean noExplosionsInTerritory() { return peaceful && !peacefulExplosionsEnabled; }
// -------------------------------
// Understand the types
// -------------------------------
public boolean isNormal() {
return this.getId() > 0;
public boolean isNormal()
{
return ! (this.isNone() || this.isSafeZone() || this.isWarZone());
}
public boolean isNone() {
return this.getId() == 0;
public boolean isNone()
{
return this.getId().equals("0");
}
public boolean isSafeZone() {
return this.getId() == -1;
public boolean isSafeZone()
{
return this.getId().equals("-1");
}
public boolean isWarZone() {
return this.getId() == -2;
public boolean isWarZone()
{
return this.getId().equals("-2");
}
// -------------------------------
// Invites - uses lowercase name
// -------------------------------
public void invite(FPlayer fplayer) {
this.invites.add(fplayer.getName().toLowerCase());
}
public void deinvite(FPlayer fplayer) {
this.invites.remove(fplayer.getName().toLowerCase());
}
public boolean isInvited(FPlayer fplayer) {
return this.invites.contains(fplayer.getName().toLowerCase());
}
// -------------------------------
// Relation and relation colors TODO
// -------------------------------
public Relation getRelationWish(Faction otherFaction) {
if (this.relationWish.containsKey(otherFaction.getId())){
public Relation getRelationWish(Faction otherFaction)
{
if (this.relationWish.containsKey(otherFaction.getId()))
{
return this.relationWish.get(otherFaction.getId());
}
return Relation.NEUTRAL;
}
public void setRelationWish(Faction otherFaction, Relation relation) {
if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)){
public void setRelationWish(Faction otherFaction, Relation relation)
{
if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL))
{
this.relationWish.remove(otherFaction.getId());
} else {
}
else
{
this.relationWish.put(otherFaction.getId(), relation);
}
}
public Relation getRelation(Faction otherFaction) {
public Relation getRelation(Faction otherFaction)
{
return getRelation(otherFaction, false);
}
public Relation getRelation(Faction otherFaction, boolean ignorePeaceful) {
if (!otherFaction.isNormal() || !this.isNormal()) {
public Relation getRelation(Faction otherFaction, boolean ignorePeaceful)
{
if (!otherFaction.isNormal() || !this.isNormal())
{
return Relation.NEUTRAL;
}
if (otherFaction.equals(this)) {
if (otherFaction.equals(this))
{
return Relation.MEMBER;
}
if (!ignorePeaceful && (this.peaceful || otherFaction.isPeaceful())) {
if (!ignorePeaceful && (this.peaceful || otherFaction.isPeaceful()))
{
return Relation.NEUTRAL;
}
if(this.getRelationWish(otherFaction).value >= otherFaction.getRelationWish(this).value) {
if(this.getRelationWish(otherFaction).value >= otherFaction.getRelationWish(this).value)
{
return otherFaction.getRelationWish(this);
}
return this.getRelationWish(otherFaction);
}
public Relation getRelation(FPlayer fplayer) {
public Relation getRelation(FPlayer fplayer)
{
if (fplayer == null)
return Relation.NEUTRAL;
else
@ -250,7 +250,8 @@ public class Faction {
//----------------------------------------------//
// Power
//----------------------------------------------//
public double getPower() {
public double getPower()
{
double ret = 0;
for (FPlayer fplayer : this.getFPlayers()) {
ret += fplayer.getPower();
@ -296,13 +297,15 @@ public class Faction {
// Fplayers
// -------------------------------
public ArrayList<FPlayer> getFPlayers() {
public ArrayList<FPlayer> getFPlayers()
{
ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id < 0)
return ret;
if (id < 0) return ret;
for (FPlayer fplayer : FPlayer.getAll()) {
if (fplayer.getFaction() == this) {
for (FPlayer fplayer : FPlayers.i.get())
{
if (fplayer.getFaction() == this)
{
ret.add(fplayer);
}
}
@ -310,13 +313,15 @@ public class Faction {
return ret;
}
public ArrayList<FPlayer> getFPlayersWhereOnline(boolean online) {
public ArrayList<FPlayer> getFPlayersWhereOnline(boolean online)
{
ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id < 0)
return ret;
if (id < 0) return ret;
for (FPlayer fplayer : FPlayer.getAll()) {
if (fplayer.getFaction() == this && fplayer.isOnline() == online) {
for (FPlayer fplayer : FPlayers.i.get())
{
if (fplayer.getFaction() == this && fplayer.isOnline() == online)
{
ret.add(fplayer);
}
}
@ -324,12 +329,14 @@ public class Faction {
return ret;
}
public FPlayer getFPlayerAdmin() {
if (id <= 0)
return null;
public FPlayer getFPlayerAdmin()
{
if (id <= 0) return null;
for (FPlayer fplayer : FPlayer.getAll()) {
if (fplayer.getFaction() == this && fplayer.getRole() == Role.ADMIN) {
for (FPlayer fplayer : FPlayers.i.get())
{
if (fplayer.getFaction() == this && fplayer.getRole() == Role.ADMIN)
{
return fplayer;
}
}
@ -338,10 +345,9 @@ public class Faction {
public ArrayList<FPlayer> getFPlayersWhereRole(Role role) {
ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id <= 0)
return ret;
if (id <= 0) return ret;
for (FPlayer fplayer : FPlayer.getAll()) {
for (FPlayer fplayer : FPlayers.i.get()) {
if (fplayer.getFaction() == this && fplayer.getRole() == role) {
ret.add(fplayer);
}
@ -350,14 +356,16 @@ public class Faction {
return ret;
}
public ArrayList<Player> getOnlinePlayers() {
public ArrayList<Player> getOnlinePlayers()
{
ArrayList<Player> ret = new ArrayList<Player>();
if (id < 0)
return ret;
if (id < 0) return ret;
for (Player player: Factions.instance.getServer().getOnlinePlayers()) {
FPlayer fplayer = FPlayer.get(player);
if (fplayer.getFaction() == this) {
for (Player player: P.p.getServer().getOnlinePlayers())
{
FPlayer fplayer = FPlayers.i.get(player);
if (fplayer.getFaction() == this)
{
ret.add(player);
}
}
@ -366,85 +374,53 @@ public class Faction {
}
// slightly faster check than getOnlinePlayers() if you just want to see if there are any players online
public boolean hasPlayersOnline() {
public boolean hasPlayersOnline()
{
// only real factions can have players online, not safe zone / war zone
if (id < 0)
return false;
if (id < 0) return false;
for (Player player: Factions.instance.getServer().getOnlinePlayers()) {
FPlayer fplayer = FPlayer.get(player);
if (fplayer.getFaction() == this) {
for (Player player: P.p.getServer().getOnlinePlayers())
{
FPlayer fplayer = FPlayers.i.get(player);
if (fplayer.getFaction() == this)
{
return true;
}
}
// even if all players are technically logged off, maybe someone was on recently enough to not consider them officially offline yet
if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 &&
System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000)) {
if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000))
{
return true;
}
return false;
}
public void memberLoggedOff() {
if (this.isNormal()) {
public void memberLoggedOff()
{
if (this.isNormal())
{
lastPlayerLoggedOffTime = System.currentTimeMillis();
}
}
//----------------------------------------------//
// Faction tag
//----------------------------------------------//
public String getComparisonTag() {
return TextUtil.getComparisonString(this.tag);
}
public static ArrayList<String> validateTag(String str) {
ArrayList<String> errors = new ArrayList<String>();
if(TextUtil.getComparisonString(str).length() < Conf.factionTagLengthMin) {
errors.add(Conf.colorSystem+"The faction tag can't be shorter than "+Conf.factionTagLengthMin+ " chars.");
}
if(str.length() > Conf.factionTagLengthMax) {
errors.add(Conf.colorSystem+"The faction tag can't be longer than "+Conf.factionTagLengthMax+ " chars.");
}
for (char c : str.toCharArray()) {
if ( ! TextUtil.substanceChars.contains(String.valueOf(c))) {
errors.add(Conf.colorSystem+"Faction tag must be alphanumeric. \""+c+"\" is not allowed.");
}
}
return errors;
}
public static Faction findByTag(String str) {
String compStr = TextUtil.getComparisonString(str);
for (Faction faction : Faction.getAll()) {
if (faction.getComparisonTag().equals(compStr)) {
return faction;
}
}
return null;
}
public static boolean isTagTaken(String str) {
return Faction.findByTag(str) != null;
}
//----------------------------------------------//
// Messages
//----------------------------------------------//
public void sendMessage(String message) {
for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) {
public void sendMessage(String message)
{
for (FPlayer fplayer : this.getFPlayersWhereOnline(true))
{
fplayer.sendMessage(message);
}
}
public void sendMessage(List<String> messages) {
for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) {
public void sendMessage(List<String> messages)
{
for (FPlayer fplayer : this.getFPlayersWhereOnline(true))
{
fplayer.sendMessage(messages);
}
}
@ -453,11 +429,13 @@ public class Faction {
// Mudd TODO
//----------------------------------------------//
public ChatColor getRelationColor(Faction otherFaction) {
public ChatColor getRelationColor(Faction otherFaction)
{
return this.getRelation(otherFaction).getColor();
}
public ChatColor getRelationColor(FPlayer fplayer) {
public ChatColor getRelationColor(FPlayer fplayer)
{
return this.getRelation(fplayer).getColor();
}
@ -465,78 +443,96 @@ public class Faction {
// Ownership of specific claims
//----------------------------------------------//
public void clearAllClaimOwnership() {
public void clearAllClaimOwnership()
{
claimOwnership.clear();
}
public void clearClaimOwnership(FLocation loc) {
public void clearClaimOwnership(FLocation loc)
{
claimOwnership.remove(loc);
}
public void clearClaimOwnership(String playerName) {
if (playerName == null || playerName.isEmpty()) {
public void clearClaimOwnership(String playerName)
{
if (playerName == null || playerName.isEmpty())
{
return;
}
Set<String> ownerData;
String player = playerName.toLowerCase();
for (Entry<FLocation, Set<String>> entry : claimOwnership.entrySet()) {
for (Entry<FLocation, Set<String>> entry : claimOwnership.entrySet())
{
ownerData = entry.getValue();
if (ownerData == null) {
continue;
}
if (ownerData == null) continue;
Iterator<String> iter = ownerData.iterator();
while (iter.hasNext()) {
if (iter.next().equals(player)) {
while (iter.hasNext())
{
if (iter.next().equals(player))
{
iter.remove();
}
}
if (ownerData.isEmpty()) {
if (ownerData.isEmpty())
{
claimOwnership.remove(entry.getKey());
}
}
}
public int getCountOfClaimsWithOwners() {
public int getCountOfClaimsWithOwners()
{
return claimOwnership.isEmpty() ? 0 : claimOwnership.size();
}
public boolean doesLocationHaveOwnersSet(FLocation loc) {
if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) {
public boolean doesLocationHaveOwnersSet(FLocation loc)
{
if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc))
{
return false;
}
Set<String> ownerData = claimOwnership.get(loc);
return ownerData != null && !ownerData.isEmpty();
}
public boolean isPlayerInOwnerList(String playerName, FLocation loc) {
if (claimOwnership.isEmpty()) {
public boolean isPlayerInOwnerList(String playerName, FLocation loc)
{
if (claimOwnership.isEmpty())
{
return false;
}
Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) {
if (ownerData == null)
{
return false;
}
if (ownerData.contains(playerName.toLowerCase())) {
if (ownerData.contains(playerName.toLowerCase()))
{
return true;
}
return false;
}
public void setPlayerAsOwner(String playerName, FLocation loc) {
public void setPlayerAsOwner(String playerName, FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) {
if (ownerData == null)
{
ownerData = new HashSet<String>();
}
ownerData.add(playerName.toLowerCase());
claimOwnership.put(loc, ownerData);
}
public void removePlayerAsOwner(String playerName, FLocation loc) {
public void removePlayerAsOwner(String playerName, FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) {
return;
@ -545,13 +541,16 @@ public class Faction {
claimOwnership.put(loc, ownerData);
}
public Set<String> getOwnerList(FLocation loc) {
public Set<String> getOwnerList(FLocation loc)
{
return claimOwnership.get(loc);
}
public String getOwnerListString(FLocation loc) {
public String getOwnerListString(FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null || ownerData.isEmpty()) {
if (ownerData == null || ownerData.isEmpty())
{
return "";
}
@ -559,7 +558,8 @@ public class Faction {
Iterator<String> iter = ownerData.iterator();
while (iter.hasNext()) {
if (!ownerList.isEmpty()) {
if (!ownerList.isEmpty())
{
ownerList += ", ";
}
ownerList += iter.next();
@ -567,19 +567,23 @@ public class Faction {
return ownerList;
}
public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) {
public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc)
{
// different faction?
if (fplayer.getFactionId() != id) {
if (fplayer.getFactionId() != this.getId())
{
return false;
}
// sufficient role to bypass ownership?
if (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.ADMIN)) {
if (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.ADMIN))
{
return true;
}
// make sure claimOwnership is initialized
if (claimOwnership.isEmpty()) {
if (claimOwnership.isEmpty())
{
return true;
}
@ -587,82 +591,57 @@ public class Faction {
Set<String> ownerData = claimOwnership.get(loc);
// if no owner list, owner list is empty, or player is in owner list, they're allowed
if (ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getName().toLowerCase())) {
return true;
}
return false;
}
//----------------------------------------------//
// Bank functions
//----------------------------------------------//
public double getMoney() {
return this.money;
}
public boolean addMoney(double amount) {
if ( amount > 0.0 )
if (ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getName().toLowerCase()))
{
this.money += amount;
return true;
}
return false;
}
public boolean removeMoney( double amount ) {
if (amount <= 0.0 )
return false;
if (amount > this.money )
return false;
this.money -= amount;
return true;
}
//----------------------------------------------//
// Persistance and entity management
//----------------------------------------------//
public static boolean save() {
/*public static boolean save() {
//Factions.log("Saving factions to disk");
try {
DiscUtil.write(file, Factions.instance.gson.toJson(instances));
DiscUtil.write(file, P.p.gson.toJson(instances));
} catch (IOException e) {
e.printStackTrace();
Factions.log("Failed to save the factions to disk due to I/O exception.");
P.log("Failed to save the factions to disk due to I/O exception.");
return false;
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to save the factions to disk.");
P.log("Failed to save the factions to disk.");
return false;
}
return true;
}
public static boolean load() {
Factions.log("Loading factions from disk");
*/
/*public static boolean load() {
P.log("Loading factions from disk");
if ( ! file.exists()) {
if ( ! loadOld())
Factions.log("No factions to load from disk. Creating new file.");
P.log("No factions to load from disk. Creating new file.");
save();
}
try {
Type type = new TypeToken<Map<Integer, Faction>>(){}.getType();
Map<Integer, Faction> instancesFromFile = Factions.instance.gson.fromJson(DiscUtil.read(file), type);
Map<Integer, Faction> instancesFromFile = P.p.gson.fromJson(DiscUtil.read(file), type);
instances.clear();
instances.putAll(instancesFromFile);
} catch (Exception e) {
e.printStackTrace();
Factions.log("Failed to load the factions from disk.");
P.log("Failed to load the factions from disk.");
return false;
}
@ -696,28 +675,31 @@ public class Faction {
}
return true;
}*/
@Override
public void postDetach()
{
// Clean the board
Board.clean();
// Clean the fplayers
FPlayers.i.clean();
}
public static void fillIds() {
nextId = 1;
for(Entry<Integer, Faction> entry : instances.entrySet()) {
entry.getValue().id = entry.getKey();
if (nextId < entry.getKey()) {
nextId = entry.getKey();
}
}
nextId += 1; // make it the next id and not the current highest.
}
public static Faction get(Integer factionId) {
if ( ! instances.containsKey(factionId)) {
Factions.log(Level.WARNING, "Non existing factionId "+factionId+" requested! Issuing cleaning!");
/*public static Faction get(Integer factionId)
{
if ( ! instances.containsKey(factionId))
{
P.log(Level.WARNING, "Non existing factionId "+factionId+" requested! Issuing cleaning!");
Board.clean();
FPlayer.clean();
}
return instances.get(factionId);
}
}*/
/*
public static Faction getNone() {
return instances.get(0);
}
@ -728,23 +710,22 @@ public class Faction {
public static Faction getWarZone() {
return instances.get(-2);
}
}*/
/*
public static boolean exists(Integer factionId) {
return instances.containsKey(factionId);
}
public static Collection<Faction> getAll() {
return instances.values();
}
//TODO ta parametrar här. All info som behövs ska matas in här och sparar vi i denna method.
public static Faction create() {
public static Faction create()
{
Faction faction = new Faction();
faction.id = nextId;
nextId += 1;
instances.put(faction.id, faction);
Factions.log("created new faction "+faction.id);
P.log("created new faction "+faction.id);
//faction.save();
return faction;
}
@ -761,12 +742,12 @@ public class Faction {
}
private static boolean loadOld() {
File folderFaction = new File(Factions.instance.getDataFolder(), "faction");
File folderFaction = new File(P.p.getDataFolder(), "faction");
if ( ! folderFaction.isDirectory())
return false;
Factions.log("Factions file doesn't exist, attempting to load old pre-1.1 data.");
P.log("Factions file doesn't exist, attempting to load old pre-1.1 data.");
String ext = ".json";
@ -785,15 +766,15 @@ public class Faction {
int id = Integer.parseInt(name);
try {
Faction faction = Factions.instance.gson.fromJson(DiscUtil.read(jsonFile), Faction.class);
Faction faction = P.p.gson.fromJson(DiscUtil.read(jsonFile), Faction.class);
faction.id = id;
instances.put(faction.id, faction);
Factions.log("loaded pre-1.1 faction "+id);
P.log("loaded pre-1.1 faction "+id);
} catch (Exception e) {
e.printStackTrace();
Factions.log(Level.WARNING, "Failed to load faction "+id);
P.log(Level.WARNING, "Failed to load faction "+id);
}
}
return true;
}
}*/
}

View File

@ -1,538 +1,157 @@
package com.massivecraft.factions;
import java.io.File;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.ChatColor;
import com.massivecraft.factions.commands.*;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.integration.Worldguard;
import com.massivecraft.factions.listeners.FactionsBlockListener;
import com.massivecraft.factions.listeners.FactionsChatEarlyListener;
import com.massivecraft.factions.listeners.FactionsEntityListener;
import com.massivecraft.factions.listeners.FactionsPlayerListener;
import com.massivecraft.factions.struct.ChatMode;
import com.massivecraft.factions.util.JarLoader;
import com.massivecraft.factions.util.MapFLocToStringSetTypeAdapter;
import com.massivecraft.factions.util.MyLocationTypeAdapter;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import com.earth2me.essentials.chat.EssentialsChat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.integration.EssentialsFeatures;
import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.persist.EntityCollection;
/**
* The data is saved to disk every 30min and on plugin disable.
*/
public class Factions extends JavaPlugin {
// -------------------------------------------- //
// Fields
// -------------------------------------------- //
public static Factions instance;
private Integer saveTask = null;
public class Factions extends EntityCollection<Faction>
{
public static Factions i = new Factions();
public Gson gson;
P p = P.p;
private final FactionsPlayerListener playerListener = new FactionsPlayerListener();
private final FactionsChatEarlyListener chatEarlyListener = new FactionsChatEarlyListener();
private final FactionsEntityListener entityListener = new FactionsEntityListener();
private final FactionsBlockListener blockListener = new FactionsBlockListener();
public static PermissionHandler Permissions;
private static EssentialsChat essChat;
// Commands
public List<FBaseCommand> commands = new ArrayList<FBaseCommand>();
private String baseCommand;
public Factions() {
Factions.instance = this;
}
@Override
public void onEnable() {
log("=== ENABLE START ===");
long timeInitStart = System.currentTimeMillis();
// Load the gson library we require
File gsonfile = new File("./lib/gson.jar");
if ( ! JarLoader.load(gsonfile)) {
log(Level.SEVERE, "Disabling myself as "+gsonfile.getPath()+" is missing from the root Minecraft server folder.");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
Type mapFLocToStringSetType = new TypeToken<Map<FLocation, Set<String>>>(){}.getType();
gson = new GsonBuilder()
.setPrettyPrinting()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE)
.registerTypeAdapter(Location.class, new MyLocationTypeAdapter())
.registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter())
.create();
// Add the commands
commands.add(new FCommandHelp());
commands.add(new FCommandAdmin());
commands.add(new FCommandAutoClaim());
commands.add(new FCommandAutoSafeclaim());
commands.add(new FCommandAutoWarclaim());
commands.add(new FCommandBalance());
commands.add(new FCommandBypass());
commands.add(new FCommandChat());
commands.add(new FCommandClaim());
commands.add(new FCommandConfig());
commands.add(new FCommandCreate());
commands.add(new FCommandDeinvite());
commands.add(new FCommandDeposit());
commands.add(new FCommandDescription());
commands.add(new FCommandDisband());
commands.add(new FCommandHome());
commands.add(new FCommandInvite());
commands.add(new FCommandJoin());
commands.add(new FCommandKick());
commands.add(new FCommandLeave());
commands.add(new FCommandList());
commands.add(new FCommandLock());
commands.add(new FCommandMap());
commands.add(new FCommandMod());
commands.add(new FCommandNoBoom());
commands.add(new FCommandOpen());
commands.add(new FCommandOwner());
commands.add(new FCommandOwnerList());
commands.add(new FCommandPay());
commands.add(new FCommandPower());
commands.add(new FCommandPeaceful());
commands.add(new FCommandPermanent());
commands.add(new FCommandRelationAlly());
commands.add(new FCommandRelationEnemy());
commands.add(new FCommandRelationNeutral());
commands.add(new FCommandReload());
commands.add(new FCommandSafeclaim());
commands.add(new FCommandSafeunclaimall());
commands.add(new FCommandSaveAll());
commands.add(new FCommandSethome());
commands.add(new FCommandShow());
commands.add(new FCommandTag());
commands.add(new FCommandTitle());
commands.add(new FCommandUnclaim());
commands.add(new FCommandUnclaimall());
commands.add(new FCommandVersion());
commands.add(new FCommandWarclaim());
commands.add(new FCommandWarunclaimall());
commands.add(new FCommandWithdraw());
// Ensure base folder exists!
this.getDataFolder().mkdirs();
Conf.load();
FPlayer.load();
Faction.load();
Board.load();
setupPermissions();
integrateEssentialsChat();
setupSpout(this);
Econ.setup(this);
Econ.monitorPlugins();
if(Conf.worldGuardChecking) {
Worldguard.init(this);
}
// Register events
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Highest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, this.chatEarlyListener, Event.Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_RESPAWN, this.playerListener, Event.Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_KICK, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENDERMAN_PICKUP, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENDERMAN_PLACE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PAINTING_BREAK, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PAINTING_PLACE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_DAMAGE, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, this.blockListener, Event.Priority.Normal, this);
// Register recurring tasks
long saveTicks = 20 * 60 * 30; // Approximately every 30 min
if (saveTask == null)
saveTask = this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(), saveTicks, saveTicks);
log("=== ENABLE DONE (Took "+(System.currentTimeMillis()-timeInitStart)+"ms) ===");
private Factions()
{
super
(
Faction.class,
new CopyOnWriteArrayList<Faction>(),
new ConcurrentHashMap<String, Faction>(),
new File(P.p.getDataFolder(), "factions.json"),
P.p.gson
);
}
@Override
public void onDisable() {
if (saveTask != null) {
this.getServer().getScheduler().cancelTask(saveTask);
saveTask = null;
}
if (gson != null) {
saveAll();
}
unhookEssentialsChat();
}
// -------------------------------------------- //
// Integration with other plugins
// -------------------------------------------- //
private void setupPermissions() {
if (Permissions != null) {
return;
}
Plugin test = this.getServer().getPluginManager().getPlugin("Permissions");
if (test != null) {
Permissions = ((Permissions)test).getHandler();
Factions.log("Found and will use "+test.getDescription().getFullName()+" for permissions");
} else {
Factions.log("Permissions plugin not detected, defaulting to Bukkit superperms system");
}
}
private void setupSpout(Factions factions) {
Plugin test = factions.getServer().getPluginManager().getPlugin("Spout");
if (test != null && test.isEnabled()) {
SpoutFeatures.setAvailable(true, test.getDescription().getFullName());
}
}
private void integrateEssentialsChat() {
if (essChat != null) {
return;
}
Plugin test = this.getServer().getPluginManager().getPlugin("EssentialsChat");
if (test != null && test.isEnabled()) {
essChat = (EssentialsChat)test;
EssentialsFeatures.integrateChat(essChat);
}
}
private void unhookEssentialsChat() {
if (essChat != null) {
EssentialsFeatures.unhookChat();
}
}
// -------------------------------------------- //
// Functions for other plugins to hook into
// -------------------------------------------- //
// This value will be updated whenever new hooks are added
public int hookSupportVersion() {
return 3;
}
// If another plugin is handling insertion of chat tags, this should be used to notify Factions
public void handleFactionTagExternally(boolean notByFactions) {
Conf.chatTagHandledByAnotherPlugin = notByFactions;
}
// Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat
// enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand()
public boolean shouldLetFactionsHandleThisChat(PlayerChatEvent event) {
if (event == null)
return false;
return (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage()));
}
// Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels,
// local chat, or anything else which targets individual recipients, so Faction Chat can be done
public boolean isPlayerFactionChatting(Player player) {
if (player == null)
return false;
FPlayer me = FPlayer.get(player);
if (me == null)
return false;
return me.getChatMode().isAtLeast(ChatMode.ALLIANCE);
}
// Is this chat message actually a Factions command, and thus should be left alone by other plugins?
public boolean isFactionsCommand(String check) {
if (check == null || check.isEmpty())
return false;
return (Conf.allowNoSlashCommand && (check.startsWith(instance.getBaseCommand()+" ") || check.equals(instance.getBaseCommand())));
}
// Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat
public String getPlayerFactionTag(Player player) {
return getPlayerFactionTagRelation(player, null);
}
// Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag
public String getPlayerFactionTagRelation(Player speaker, Player listener) {
String tag = "~";
if (speaker == null)
return tag;
FPlayer me = FPlayer.get(speaker);
if (me == null)
return tag;
// if listener isn't set, or config option is disabled, give back uncolored tag
if (listener == null || !Conf.chatTagRelationColored) {
tag = me.getChatTag().trim();
} else {
FPlayer you = FPlayer.get(listener);
if (you == null)
tag = me.getChatTag().trim();
else // everything checks out, give the colored tag
tag = me.getChatTag(you).trim();
}
if (tag.isEmpty())
tag = "~";
return tag;
}
// Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat
public String getPlayerTitle(Player player) {
if (player == null)
return "";
FPlayer me = FPlayer.get(player);
if (me == null)
return "";
return me.getTitle().trim();
}
// Get a list of all faction tags (names)
public Set<String> getFactionTags() {
Set<String> tags = new HashSet<String>();
for (Faction faction : Faction.getAll()) {
tags.add(faction.getTag());
}
return tags;
}
// Get a list of all players in the specified faction
public Set<String> getPlayersInFaction(String factionTag) {
Set<String> players = new HashSet<String>();
Faction faction = Faction.findByTag(factionTag);
if (faction != null) {
for (FPlayer fplayer : faction.getFPlayers()) {
players.add(fplayer.getName());
}
}
return players;
}
// Get a list of all online players in the specified faction
public Set<String> getOnlinePlayersInFaction(String factionTag) {
Set<String> players = new HashSet<String>();
Faction faction = Faction.findByTag(factionTag);
if (faction != null) {
for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) {
players.add(fplayer.getName());
}
}
return players;
}
// check if player is allowed to build/destroy in a particular location
public boolean isPlayerAllowedToBuildHere(Player player, Location location) {
return FactionsBlockListener.playerCanBuildDestroyBlock(player, location, "", true);
}
// check if player is allowed to interact with the specified block (doors/chests/whatever)
public boolean isPlayerAllowedToInteractWith(Player player, Block block) {
return FactionsPlayerListener.canPlayerUseBlock(player, block, true);
}
// check if player is allowed to use a specified item (flint&steel, buckets, etc) in a particular location
public boolean isPlayerAllowedToUseThisHere(Player player, Location location, Material material) {
return FactionsPlayerListener.playerCanUseItemHere(player, location, material, true);
}
// -------------------------------------------- //
// Test rights
// -------------------------------------------- //
public static boolean hasPermParticipate(CommandSender sender) {
return hasPerm(sender, "factions.participate");
}
public static boolean hasPermCreate(CommandSender sender) {
return hasPerm(sender, "factions.create");
}
public static boolean hasPermManageSafeZone(CommandSender sender) {
return hasPerm(sender, "factions.manageSafeZone");
}
public static boolean hasPermManageWarZone(CommandSender sender) {
return hasPerm(sender, "factions.manageWarZone");
}
public static boolean hasPermAdminBypass(CommandSender sender) {
return hasPerm(sender, "factions.adminBypass");
}
public static boolean hasPermReload(CommandSender sender) {
return hasPerm(sender, "factions.reload");
}
public static boolean hasPermSaveAll(CommandSender sender) {
return hasPerm(sender, "factions.saveall");
}
public static boolean hasPermLock(CommandSender sender) {
return hasPerm(sender, "factions.lock");
}
public static boolean hasPermConfigure(CommandSender sender) {
return hasPerm(sender, "factions.config");
}
public static boolean hasPermDisband(CommandSender sender) {
return hasPerm(sender, "factions.disband");
}
public static boolean hasPermViewAnyPower(CommandSender sender) {
return hasPerm(sender, "factions.viewAnyPower");
}
public static boolean hasPermOwnershipBypass(CommandSender sender) {
return hasPerm(sender, "factions.ownershipBypass");
}
public static boolean hasPermSetPeaceful(CommandSender sender) {
return hasPerm(sender, "factions.setPeaceful");
}
public static boolean hasPermSetPermanent(CommandSender sender) {
return hasPerm(sender, "factions.setPermanent");
}
public static boolean hasPermPeacefulExplosionToggle(CommandSender sender) {
return hasPerm(sender, "factions.peacefulExplosionToggle");
}
public static boolean hasPermViewAnyFactionBalance(CommandSender sender) {
return hasPerm(sender, "factions.viewAnyFactionBalance");
}
public static boolean isCommandDisabled(CommandSender sender, String command) {
return (hasPerm(sender, "factions.commandDisable."+command) && !hasPerm(sender, "factions.commandDisable.none"));
}
private static boolean hasPerm(CommandSender sender, String permNode) {
if (Factions.Permissions == null || ! (sender instanceof Player)) {
return sender.isOp() || sender.hasPermission(permNode);
}
Player player = (Player)sender;
return Factions.Permissions.has(player, permNode);
}
// -------------------------------------------- //
// Commands
// -------------------------------------------- //
@SuppressWarnings("unchecked")
public String getBaseCommand() {
if (this.baseCommand != null) {
return this.baseCommand;
}
Map<String, Object> Commands = (Map<String, Object>)this.getDescription().getCommands();
this.baseCommand = Commands.keySet().iterator().next();
return this.baseCommand;
public Type getMapType()
{
return new TypeToken<Map<String, Faction>>(){}.getType();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
List<String> parameters = new ArrayList<String>(Arrays.asList(args));
this.handleCommand(sender, parameters);
public boolean loadFromDisc()
{
if ( ! super.loadFromDisc()) return false;
// Make sure the default neutral faction exists
if ( ! this.exists("0"))
{
Faction faction = this.create("0");
faction.setTag(ChatColor.DARK_GREEN+"Wilderness");
faction.setDescription("");
}
// Make sure the safe zone faction exists
if ( ! this.exists("-1"))
{
Faction faction = this.create("-1");
faction.setTag(ChatColor.GOLD+"Safe Zone");
faction.setDescription("Free from PVP and monsters");
}
// Make sure the war zone faction exists
if ( ! this.exists("-2"))
{
Faction faction = this.create("-2");
faction.setTag(ChatColor.DARK_RED+"War Zone");
faction.setDescription("Not the safest place to be");
}
return true;
}
public void handleCommand(CommandSender sender, List<String> parameters) {
if (parameters.size() == 0) {
this.commands.get(0).execute(sender, parameters);
return;
//----------------------------------------------//
// GET
//----------------------------------------------//
@Override
public Faction get(String id)
{
if ( ! this.exists(id))
{
p.log(Level.WARNING, "Non existing factionId "+id+" requested! Issuing cleaning!");
Board.clean();
FPlayers.i.clean();
}
String commandName = parameters.get(0).toLowerCase();
parameters.remove(0);
return super.get(id);
}
for (FBaseCommand fcommand : this.commands) {
if (fcommand.getAliases().contains(commandName)) {
fcommand.execute(sender, parameters);
return;
public Faction getNone()
{
return this.get("0");
}
public Faction getSafeZone()
{
return this.get("-1");
}
public Faction getWarZone()
{
return this.get("-2");
}
//----------------------------------------------//
// Faction tag
//----------------------------------------------//
public static ArrayList<String> validateTag(String str)
{
ArrayList<String> errors = new ArrayList<String>();
if(MiscUtil.getComparisonString(str).length() < Conf.factionTagLengthMin)
{
errors.add(P.p.txt.parse("<i>The faction tag can't be shorter than "+Conf.factionTagLengthMin+ " chars."));
}
if(str.length() > Conf.factionTagLengthMax)
{
errors.add(P.p.txt.parse("<i>The faction tag can't be longer than "+Conf.factionTagLengthMax+ " chars."));
}
for (char c : str.toCharArray())
{
if ( ! MiscUtil.substanceChars.contains(String.valueOf(c)))
{
errors.add(P.p.txt.parse("<i>Faction tag must be alphanumeric. \""+c+"\" is not allowed."));
}
}
sender.sendMessage(Conf.colorSystem+"Unknown faction command \""+commandName+"\". Try "+Conf.colorCommand+"/"+this.getBaseCommand()+" help");
return errors;
}
// -------------------------------------------- //
// Logging
// -------------------------------------------- //
public static void log(String msg) {
log(Level.INFO, msg);
public Faction findByTag(String str)
{
String compStr = MiscUtil.getComparisonString(str);
for (Faction faction : this.get())
{
if (faction.getComparisonTag().equals(compStr))
{
return faction;
}
}
return null;
}
public static void log(Level level, String msg) {
Logger.getLogger("Minecraft").log(level, "["+instance.getDescription().getFullName()+"] "+msg);
}
// -------------------------------------------- //
// Save all
// -------------------------------------------- //
public static void saveAll() {
FPlayer.save();
Faction.save();
Board.save();
Conf.save();
public boolean isTagTaken(String str)
{
return this.findByTag(str) != null;
}
}

View File

@ -0,0 +1,512 @@
package com.massivecraft.factions;
import java.io.File;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import com.massivecraft.factions.commands.*;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.integration.Worldguard;
import com.massivecraft.factions.listeners.FactionsBlockListener;
import com.massivecraft.factions.listeners.FactionsChatEarlyListener;
import com.massivecraft.factions.listeners.FactionsEntityListener;
import com.massivecraft.factions.listeners.FactionsPlayerListener;
import com.massivecraft.factions.struct.ChatMode;
import com.massivecraft.factions.util.MapFLocToStringSetTypeAdapter;
import com.massivecraft.factions.util.MyLocationTypeAdapter;
import com.massivecraft.factions.zcore.MPlugin;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import com.earth2me.essentials.chat.EssentialsChat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.integration.EssentialsFeatures;
/**
* The data is saved to disk every 30min and on plugin disable.
*/
public class P extends MPlugin
{
// Our single plugin instance
public static P p;
// Listeners
public final FactionsPlayerListener playerListener;
public final FactionsChatEarlyListener chatEarlyListener;
public final FactionsEntityListener entityListener;
public final FactionsBlockListener blockListener;
public P()
{
p = this;
this.playerListener = new FactionsPlayerListener(this);
this.chatEarlyListener = new FactionsChatEarlyListener(this);
this.entityListener = new FactionsEntityListener(this);
this.blockListener = new FactionsBlockListener(this);
}
public static PermissionHandler Permissions;
private static EssentialsChat essChat;
@Override
public void onEnable()
{
if ( ! preEnable()) return;
// Load Conf from disk
Conf.load();
FPlayers.i.loadFromDisc();
Factions.i.loadFromDisc();
Board.load();
//setupPermissions();
integrateEssentialsChat();
setupSpout(this);
Econ.setup(this);
Econ.monitorPlugins();
if(Conf.worldGuardChecking)
{
Worldguard.init(this);
}
Type mapFLocToStringSetType = new TypeToken<Map<FLocation, Set<String>>>(){}.getType();
// Add the commands
commands.add(new FCommandHelp());
commands.add(new FCommandAdmin());
commands.add(new FCommandAutoClaim());
commands.add(new FCommandAutoSafeclaim());
commands.add(new FCommandAutoWarclaim());
commands.add(new FCommandBalance());
commands.add(new FCommandBypass());
commands.add(new FCommandChat());
commands.add(new FCommandClaim());
commands.add(new FCommandConfig());
commands.add(new FCommandCreate());
commands.add(new FCommandDeinvite());
commands.add(new FCommandDeposit());
commands.add(new FCommandDescription());
commands.add(new FCommandDisband());
commands.add(new FCommandHome());
commands.add(new FCommandInvite());
commands.add(new FCommandJoin());
commands.add(new FCommandKick());
commands.add(new FCommandLeave());
commands.add(new FCommandList());
commands.add(new FCommandLock());
commands.add(new FCommandMap());
commands.add(new FCommandMod());
commands.add(new FCommandNoBoom());
commands.add(new FCommandOpen());
commands.add(new FCommandOwner());
commands.add(new FCommandOwnerList());
commands.add(new FCommandPay());
commands.add(new FCommandPower());
commands.add(new FCommandPeaceful());
commands.add(new FCommandPermanent());
commands.add(new FCommandRelationAlly());
commands.add(new FCommandRelationEnemy());
commands.add(new FCommandRelationNeutral());
commands.add(new FCommandReload());
commands.add(new FCommandSafeclaim());
commands.add(new FCommandSafeunclaimall());
commands.add(new FCommandSaveAll());
commands.add(new FCommandSethome());
commands.add(new FCommandShow());
commands.add(new FCommandTag());
commands.add(new FCommandTitle());
commands.add(new FCommandUnclaim());
commands.add(new FCommandUnclaimall());
commands.add(new FCommandVersion());
commands.add(new FCommandWarclaim());
commands.add(new FCommandWarunclaimall());
commands.add(new FCommandWithdraw());
// Register events
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Highest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, this.chatEarlyListener, Event.Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_RESPAWN, this.playerListener, Event.Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_KICK, this.playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENDERMAN_PICKUP, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENDERMAN_PLACE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PAINTING_BREAK, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PAINTING_PLACE, this.entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_DAMAGE, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, this.blockListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, this.blockListener, Event.Priority.Normal, this);
// Register recurring tasks
/*long saveTicks = 20 * 60 * 30; // Approximately every 30 min
if (saveTask == null)
saveTask = this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(), saveTicks, saveTicks);
*/
postEnable();
}
@Override
public GsonBuilder getGsonBuilder()
{
return new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE);
}
@Override
public void onDisable()
{
unhookEssentialsChat();
super.onDisable();
}
// -------------------------------------------- //
// Integration with other plugins
// -------------------------------------------- //
private void setupSpout(P factions)
{
Plugin test = factions.getServer().getPluginManager().getPlugin("Spout");
if (test != null && test.isEnabled())
{
SpoutFeatures.setAvailable(true, test.getDescription().getFullName());
}
}
private void integrateEssentialsChat()
{
if (essChat != null) return;
Plugin test = this.getServer().getPluginManager().getPlugin("EssentialsChat");
if (test != null && test.isEnabled())
{
essChat = (EssentialsChat)test;
EssentialsFeatures.integrateChat(essChat);
}
}
private void unhookEssentialsChat()
{
if (essChat != null) {
EssentialsFeatures.unhookChat();
}
}
// -------------------------------------------- //
// Functions for other plugins to hook into
// -------------------------------------------- //
// This value will be updated whenever new hooks are added
public int hookSupportVersion()
{
return 3;
}
// If another plugin is handling insertion of chat tags, this should be used to notify Factions
public void handleFactionTagExternally(boolean notByFactions)
{
Conf.chatTagHandledByAnotherPlugin = notByFactions;
}
// Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat
// enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand()
public boolean shouldLetFactionsHandleThisChat(PlayerChatEvent event)
{
if (event == null) return false;
return (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage()));
}
// Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels,
// local chat, or anything else which targets individual recipients, so Faction Chat can be done
public boolean isPlayerFactionChatting(Player player)
{
if (player == null) return false;
FPlayer me = FPlayers.i.get(player);
if (me == null)return false;
return me.getChatMode().isAtLeast(ChatMode.ALLIANCE);
}
// Is this chat message actually a Factions command, and thus should be left alone by other plugins?
public boolean isFactionsCommand(String check)
{
if (check == null || check.isEmpty()) return false;
return (Conf.allowNoSlashCommand && (check.startsWith(p.getBaseCommand()+" ") || check.equals(p.getBaseCommand())));
}
// Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat
public String getPlayerFactionTag(Player player)
{
return getPlayerFactionTagRelation(player, null);
}
// Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag
public String getPlayerFactionTagRelation(Player speaker, Player listener)
{
String tag = "~";
if (speaker == null)
return tag;
FPlayer me = FPlayers.i.get(speaker);
if (me == null)
return tag;
// if listener isn't set, or config option is disabled, give back uncolored tag
if (listener == null || !Conf.chatTagRelationColored) {
tag = me.getChatTag().trim();
} else {
FPlayer you = FPlayers.i.get(listener);
if (you == null)
tag = me.getChatTag().trim();
else // everything checks out, give the colored tag
tag = me.getChatTag(you).trim();
}
if (tag.isEmpty())
tag = "~";
return tag;
}
// Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat
public String getPlayerTitle(Player player)
{
if (player == null)
return "";
FPlayer me = FPlayers.i.get(player);
if (me == null)
return "";
return me.getTitle().trim();
}
// Get a list of all faction tags (names)
public Set<String> getFactionTags()
{
Set<String> tags = new HashSet<String>();
for (Faction faction : Factions.i.get())
{
tags.add(faction.getTag());
}
return tags;
}
// Get a list of all players in the specified faction
public Set<String> getPlayersInFaction(String factionTag)
{
Set<String> players = new HashSet<String>();
Faction faction = Factions.i.findByTag(factionTag);
if (faction != null)
{
for (FPlayer fplayer : faction.getFPlayers())
{
players.add(fplayer.getName());
}
}
return players;
}
// Get a list of all online players in the specified faction
public Set<String> getOnlinePlayersInFaction(String factionTag)
{
Set<String> players = new HashSet<String>();
Faction faction = Factions.i.findByTag(factionTag);
if (faction != null)
{
for (FPlayer fplayer : faction.getFPlayersWhereOnline(true))
{
players.add(fplayer.getName());
}
}
return players;
}
// check if player is allowed to build/destroy in a particular location
public boolean isPlayerAllowedToBuildHere(Player player, Location location)
{
return FactionsBlockListener.playerCanBuildDestroyBlock(player, location, "", true);
}
// check if player is allowed to interact with the specified block (doors/chests/whatever)
public boolean isPlayerAllowedToInteractWith(Player player, Block block)
{
return FactionsPlayerListener.canPlayerUseBlock(player, block, true);
}
// check if player is allowed to use a specified item (flint&steel, buckets, etc) in a particular location
public boolean isPlayerAllowedToUseThisHere(Player player, Location location, Material material)
{
return FactionsPlayerListener.playerCanUseItemHere(player, location, material, true);
}
// -------------------------------------------- //
// Test rights
// -------------------------------------------- //
public static boolean hasPermParticipate(CommandSender sender) {
return hasPerm(sender, "factions.participate");
}
public static boolean hasPermCreate(CommandSender sender) {
return hasPerm(sender, "factions.create");
}
public static boolean hasPermManageSafeZone(CommandSender sender) {
return hasPerm(sender, "factions.manageSafeZone");
}
public static boolean hasPermManageWarZone(CommandSender sender) {
return hasPerm(sender, "factions.manageWarZone");
}
public static boolean hasPermAdminBypass(CommandSender sender) {
return hasPerm(sender, "factions.adminBypass");
}
public static boolean hasPermReload(CommandSender sender) {
return hasPerm(sender, "factions.reload");
}
public static boolean hasPermSaveAll(CommandSender sender) {
return hasPerm(sender, "factions.saveall");
}
public static boolean hasPermLock(CommandSender sender) {
return hasPerm(sender, "factions.lock");
}
public static boolean hasPermConfigure(CommandSender sender) {
return hasPerm(sender, "factions.config");
}
public static boolean hasPermDisband(CommandSender sender) {
return hasPerm(sender, "factions.disband");
}
public static boolean hasPermViewAnyPower(CommandSender sender) {
return hasPerm(sender, "factions.viewAnyPower");
}
public static boolean hasPermOwnershipBypass(CommandSender sender) {
return hasPerm(sender, "factions.ownershipBypass");
}
public static boolean hasPermSetPeaceful(CommandSender sender) {
return hasPerm(sender, "factions.setPeaceful");
}
public static boolean hasPermSetPermanent(CommandSender sender) {
return hasPerm(sender, "factions.setPermanent");
}
public static boolean hasPermPeacefulExplosionToggle(CommandSender sender) {
return hasPerm(sender, "factions.peacefulExplosionToggle");
}
public static boolean hasPermViewAnyFactionBalance(CommandSender sender) {
return hasPerm(sender, "factions.viewAnyFactionBalance");
}
public static boolean isCommandDisabled(CommandSender sender, String command) {
return (hasPerm(sender, "factions.commandDisable."+command) && !hasPerm(sender, "factions.commandDisable.none"));
}
private static boolean hasPerm(CommandSender sender, String permNode) {
if (P.Permissions == null || ! (sender instanceof Player)) {
return sender.isOp() || sender.hasPermission(permNode);
}
Player player = (Player)sender;
return P.Permissions.has(player, permNode);
}
// -------------------------------------------- //
// Commands
// -------------------------------------------- //
/*
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
List<String> parameters = new ArrayList<String>(Arrays.asList(args));
this.handleCommand(sender, parameters);
return true;
}
public void handleCommand(CommandSender sender, List<String> parameters)
{
if (parameters.size() == 0)
{
this.commands.get(0).execute(sender, parameters);
return;
}
String commandName = parameters.get(0).toLowerCase();
parameters.remove(0);
for (FBaseCommand fcommand : this.commands)
{
if (fcommand.getAliases().contains(commandName))
{
fcommand.execute(sender, parameters);
return;
}
}
sender.sendMessage(Conf.colorSystem+"Unknown faction command \""+commandName+"\". Try "+Conf.colorCommand+"/"+this.getBaseCommand()+" help");
}
*/
// -------------------------------------------- //
// Save all
// -------------------------------------------- //
// TODO: Add a hook to this??
public static void saveAll()
{
// FPlayer.save();
// Faction.save();
Board.save();
Conf.save();
}
}

View File

@ -6,7 +6,7 @@ public class SaveTask implements Runnable {
@Override
public void run() {
Factions.saveAll();
P.saveAll();
}
}

View File

@ -12,7 +12,7 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.TextUtil;
@ -99,7 +99,7 @@ public class FBaseCommand {
// make sure player doesn't have their access to the command revoked
Iterator<String> iter = aliases.iterator();
while (iter.hasNext()) {
if (Factions.isCommandDisabled(sender, iter.next())) {
if (P.isCommandDisabled(sender, iter.next())) {
sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+".");
return false;
}
@ -114,7 +114,7 @@ public class FBaseCommand {
}
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermParticipate(sender);
return P.hasPermParticipate(sender);
}
// -------------------------------------------- //
@ -126,7 +126,7 @@ public class FBaseCommand {
ret += Conf.colorCommand;
ret += Factions.instance.getBaseCommand()+ " " +TextUtil.implode(this.getAliases(), ",")+" ";
ret += P.p.getBaseCommand()+ " " +TextUtil.implode(this.getAliases(), ",")+" ";
List<String> parts = new ArrayList<String>();

View File

@ -5,7 +5,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandAutoSafeclaim extends FBaseCommand {
@ -19,7 +19,7 @@ public class FCommandAutoSafeclaim extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageSafeZone(sender);
return P.hasPermManageSafeZone(sender);
}
@Override

View File

@ -5,7 +5,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandAutoWarclaim extends FBaseCommand {
@ -19,7 +19,7 @@ public class FCommandAutoWarclaim extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageWarZone(sender);
return P.hasPermManageWarZone(sender);
}
@Override

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandBalance extends FBaseCommand {
@ -30,7 +30,7 @@ public class FCommandBalance extends FBaseCommand {
Faction faction;
if (parameters.size() > 0) {
if (!Factions.hasPermViewAnyFactionBalance(sender)) {
if (!P.hasPermViewAnyFactionBalance(sender)) {
sendMessage("You do not have sufficient permissions to view the bank balance of other factions.");
return;
}

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandBypass extends FBaseCommand {
@ -16,7 +16,7 @@ public class FCommandBypass extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermAdminBypass(sender);
return P.hasPermAdminBypass(sender);
}
@Override
@ -24,11 +24,11 @@ public class FCommandBypass extends FBaseCommand {
if ( ! Conf.adminBypassPlayers.contains(player.getName())) {
Conf.adminBypassPlayers.add(player.getName());
me.sendMessage("You have enabled admin bypass mode. You will be able to build or destroy anywhere.");
Factions.log(player.getName() + " has ENABLED admin bypass mode.");
P.log(player.getName() + " has ENABLED admin bypass mode.");
} else {
Conf.adminBypassPlayers.remove(player.getName());
me.sendMessage("You have disabled admin bypass mode.");
Factions.log(player.getName() + " DISABLED admin bypass mode.");
P.log(player.getName() + " DISABLED admin bypass mode.");
}
}
}

View File

@ -12,7 +12,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.integration.SpoutFeatures;
public class FCommandConfig extends FBaseCommand {
@ -32,7 +32,7 @@ public class FCommandConfig extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermConfigure(sender);
return P.hasPermConfigure(sender);
}
@Override
@ -222,7 +222,7 @@ public class FCommandConfig extends FBaseCommand {
if (!success.isEmpty()) {
sendMessage(success);
if (sender instanceof Player) {
Factions.log(success + " Command was run by "+player.getName()+".");
P.log(success + " Command was run by "+player.getName()+".");
}
}
// save change to disk

View File

@ -7,7 +7,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Role;
@ -23,7 +23,7 @@ public class FCommandCreate extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermCreate(sender);
return P.hasPermCreate(sender);
}
@Override

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
@ -49,7 +49,7 @@ public class FCommandDeposit extends FBaseCommand {
faction.addMoney(amount);
sendMessage("You have deposited "+amountString+" into "+faction.getTag()+"'s bank.");
sendMessage(faction.getTag()+" now has "+Econ.moneyString(faction.getMoney()));
Factions.log(player.getName() + " deposited "+amountString+" into "+faction.getTag()+"'s bank.");
P.log(player.getName() + " deposited "+amountString+" into "+faction.getTag()+"'s bank.");
for (FPlayer fplayer : FPlayer.getAllOnline()) {
if (fplayer.getFaction() == faction) {

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.struct.Role;
@ -34,7 +34,7 @@ public class FCommandDisband extends FBaseCommand {
return;
}
if ( ! Factions.hasPermDisband(sender)) {
if ( ! P.hasPermDisband(sender)) {
if (me.getFaction() == faction) {
parameters.clear();
}
@ -54,7 +54,7 @@ public class FCommandDisband extends FBaseCommand {
faction = me.getFaction();
if (faction.isPermanent() && !Factions.hasPermDisband(sender)) {
if (faction.isPermanent() && !P.hasPermDisband(sender)) {
sendMessage("Your faction is designated as permanent, so you cannot disband it.");
return;
}
@ -75,7 +75,7 @@ public class FCommandDisband extends FBaseCommand {
if (amount > 0.0) {
String amountString = Econ.moneyString(amount);
sendMessage("You have been given the disbanded faction's bank, totaling "+amountString+".");
Factions.log(player.getName() + " has been given bank holdings of "+amountString+" from disbanding "+faction.getTag()+".");
P.log(player.getName() + " has been given bank holdings of "+amountString+" from disbanding "+faction.getTag()+".");
}
}

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandKick extends FBaseCommand {
@ -40,7 +40,7 @@ public class FCommandKick extends FBaseCommand {
Faction myFaction = me.getFaction();
// players with admin-level "disband" permission can bypass these requirements
if (!Factions.hasPermDisband(sender)) {
if (!P.hasPermDisband(sender)) {
if (yourFaction != myFaction) {
sendMessage(you.getNameAndRelevant(me)+Conf.colorSystem+" is not a member of "+myFaction.getTag(me));
return;

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandLock extends FBaseCommand {
@ -18,7 +18,7 @@ public class FCommandLock extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermLock(sender);
return P.hasPermLock(sender);
}
@Override

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Role;
public class FCommandNoBoom extends FBaseCommand {
@ -17,7 +17,7 @@ public class FCommandNoBoom extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermPeacefulExplosionToggle(sender);
return P.hasPermPeacefulExplosionToggle(sender);
}
@Override

View File

@ -4,7 +4,7 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Role;
@ -21,7 +21,7 @@ public class FCommandOwner extends FBaseCommand {
@Override
public void perform() {
boolean hasBypass = Factions.hasPermAdminBypass(player);
boolean hasBypass = P.hasPermAdminBypass(player);
if ( ! hasBypass && ! assertHasFaction()) {
return;

View File

@ -7,7 +7,7 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandOwnerList extends FBaseCommand {
@ -20,7 +20,7 @@ public class FCommandOwnerList extends FBaseCommand {
@Override
public void perform() {
boolean hasBypass = Factions.hasPermAdminBypass(player);
boolean hasBypass = P.hasPermAdminBypass(player);
if ( ! hasBypass && ! assertHasFaction()) {
return;

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Role;
@ -63,7 +63,7 @@ public class FCommandPay extends FBaseCommand {
them.addMoney(amount);
sendMessage("You have paid "+amountString+" from "+us.getTag()+"'s bank to "+them.getTag()+"'s bank.");
sendMessage(us.getTag()+" now has "+Econ.moneyString(us.getMoney()));
Factions.log(player.getName() + " paid "+amountString+" from "+us.getTag()+"'s bank to "+them.getTag()+"'s bank.");
P.log(player.getName() + " paid "+amountString+" from "+us.getTag()+"'s bank to "+them.getTag()+"'s bank.");
for (FPlayer fplayer : FPlayer.getAllOnline()) {
if (fplayer.getFaction() == us || fplayer.getFaction() == them) {

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.integration.SpoutFeatures;
@ -22,7 +22,7 @@ public class FCommandPeaceful extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermSetPeaceful(sender);
return P.hasPermSetPeaceful(sender);
}
@Override

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
@ -22,7 +22,7 @@ public class FCommandPermanent extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermSetPermanent(sender);
return P.hasPermSetPermanent(sender);
}
@Override

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
@ -30,7 +30,7 @@ public class FCommandPower extends FBaseCommand {
public void perform() {
FPlayer target;
if (parameters.size() > 0) {
if (!Factions.hasPermViewAnyPower(player)) {
if (!P.hasPermViewAnyPower(player)) {
me.sendMessage("You do not have the appropriate permission to view another player's power level.");
return;
}

View File

@ -6,7 +6,7 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandReload extends FBaseCommand {
@ -22,12 +22,12 @@ public class FCommandReload extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermReload(sender);
return P.hasPermReload(sender);
}
@Override
public void perform() {
Factions.log("=== RELOAD START ===");
P.log("=== RELOAD START ===");
long timeInitStart = System.currentTimeMillis();
String fileName = "s";
@ -35,33 +35,33 @@ public class FCommandReload extends FBaseCommand {
if (parameters.size() > 0) {
String file = parameters.get(0);
if (file.equalsIgnoreCase("conf") || file.equalsIgnoreCase("conf.json")) {
Factions.log("RELOADING CONF.JSON");
P.log("RELOADING CONF.JSON");
Conf.load();
fileName = " conf.json";
}
else if (file.equalsIgnoreCase("board") || file.equalsIgnoreCase("board.json")) {
Factions.log("RELOADING BOARD.JSON");
P.log("RELOADING BOARD.JSON");
Board.load();
fileName = " board.json";
}
else if (file.equalsIgnoreCase("factions") || file.equalsIgnoreCase("factions.json")) {
Factions.log("RELOADING FACTIONS.JSON");
P.log("RELOADING FACTIONS.JSON");
Faction.load();
fileName = " factions.json";
}
else if (file.equalsIgnoreCase("players") || file.equalsIgnoreCase("players.json")) {
Factions.log("RELOADING PLAYERS.JSON");
P.log("RELOADING PLAYERS.JSON");
FPlayer.load();
fileName = " players.json";
}
else {
Factions.log("RELOAD CANCELLED - SPECIFIED FILE INVALID");
P.log("RELOAD CANCELLED - SPECIFIED FILE INVALID");
sendMessage("Invalid file specified. Valid files: conf, board, factions, players.");
return;
}
}
else {
Factions.log("RELOADING ALL FILES");
P.log("RELOADING ALL FILES");
Conf.load();
FPlayer.load();
Faction.load();
@ -69,7 +69,7 @@ public class FCommandReload extends FBaseCommand {
}
long timeReload = (System.currentTimeMillis()-timeInitStart);
Factions.log("=== RELOAD DONE (Took "+timeReload+"ms) ===");
P.log("=== RELOAD DONE (Took "+timeReload+"ms) ===");
sendMessage("Factions file" + fileName + " reloaded from disk, took " + timeReload + "ms");
}

View File

@ -5,7 +5,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandSafeclaim extends FBaseCommand {
@ -20,7 +20,7 @@ public class FCommandSafeclaim extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageSafeZone(sender);
return P.hasPermManageSafeZone(sender);
}
@Override

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandSafeunclaimall extends FBaseCommand {
@ -17,7 +17,7 @@ public class FCommandSafeunclaimall extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageSafeZone(sender);
return P.hasPermManageSafeZone(sender);
}
@Override

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandSaveAll extends FBaseCommand {
@ -17,12 +17,12 @@ public class FCommandSaveAll extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermSaveAll(sender);
return P.hasPermSaveAll(sender);
}
@Override
public void perform() {
Factions.saveAll();
P.saveAll();
sendMessage("Factions saved to disk!");
}

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Role;
public class FCommandSethome extends FBaseCommand {
@ -38,7 +38,7 @@ public class FCommandSethome extends FBaseCommand {
Faction myFaction = me.getFaction();
if (parameters.size() > 0) {
if (!Factions.hasPermAdminBypass(player)) {
if (!P.hasPermAdminBypass(player)) {
me.sendMessage("You cannot set the home of another faction without adminBypass permission.");
return;
}
@ -51,7 +51,7 @@ public class FCommandSethome extends FBaseCommand {
}
}
if (Conf.homesMustBeInClaimedTerritory && !me.isInOwnTerritory() && !Factions.hasPermAdminBypass(player)) {
if (Conf.homesMustBeInClaimedTerritory && !me.isInOwnTerritory() && !P.hasPermAdminBypass(player)) {
me.sendMessage("Sorry, your faction home can only be set inside your own claimed territory.");
return;
}

View File

@ -5,7 +5,7 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Role;
public class FCommandUnclaim extends FBaseCommand {
@ -29,7 +29,7 @@ public class FCommandUnclaim extends FBaseCommand {
Faction otherFaction = Board.getFactionAt(flocation);
if (otherFaction.isSafeZone()) {
if (Factions.hasPermManageSafeZone(sender)) {
if (P.hasPermManageSafeZone(sender)) {
Board.removeAt(flocation);
sendMessage("Safe zone was unclaimed.");
} else {
@ -38,7 +38,7 @@ public class FCommandUnclaim extends FBaseCommand {
return;
}
else if (otherFaction.isWarZone()) {
if (Factions.hasPermManageWarZone(sender)) {
if (P.hasPermManageWarZone(sender)) {
Board.removeAt(flocation);
sendMessage("War zone was unclaimed.");
} else {

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandVersion extends FBaseCommand {
@ -22,7 +22,7 @@ public class FCommandVersion extends FBaseCommand {
@Override
public void perform() {
sendMessage("You are running "+Factions.instance.getDescription().getFullName());
sendMessage("You are running "+P.p.getDescription().getFullName());
}
}

View File

@ -5,7 +5,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandWarclaim extends FBaseCommand {
@ -20,7 +20,7 @@ public class FCommandWarclaim extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageWarZone(sender);
return P.hasPermManageWarZone(sender);
}
public void perform() {

View File

@ -4,7 +4,7 @@ import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class FCommandWarunclaimall extends FBaseCommand {
@ -17,7 +17,7 @@ public class FCommandWarunclaimall extends FBaseCommand {
@Override
public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageWarZone(sender);
return P.hasPermManageWarZone(sender);
}
@Override

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Role;
@ -55,7 +55,7 @@ public class FCommandWithdraw extends FBaseCommand {
Econ.addMoney(me.getName(), amount);
sendMessage("You have withdrawn "+amountString+" from "+faction.getTag()+"'s bank.");
sendMessage(faction.getTag()+" now has "+Econ.moneyString(faction.getMoney()));
Factions.log(player.getName() + " withdrew "+amountString+" from "+faction.getTag()+"'s bank.");
P.log(player.getName() + " withdrew "+amountString+" from "+faction.getTag()+"'s bank.");
for (FPlayer fplayer : FPlayer.getAllOnline()) {
if (fplayer.getFaction() == faction) {

View File

@ -4,7 +4,7 @@ import org.bukkit.ChatColor;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role;
@ -62,7 +62,7 @@ public class FRelationCommand extends FBaseCommand {
myFaction.sendMessage(Conf.colorSystem+"Your faction is now "+currentRelationColor+whishedRelation.toString()+Conf.colorSystem+" to "+currentRelationColor+otherFaction.getTag());
} else {
otherFaction.sendMessage(currentRelationColor+myFaction.getTag()+Conf.colorSystem+ " wishes to be your "+whishedRelation.getColor()+whishedRelation.toString());
otherFaction.sendMessage(Conf.colorSystem+"Type "+Conf.colorCommand+Factions.instance.getBaseCommand()+" "+whishedRelation+" "+myFaction.getTag()+Conf.colorSystem+" to accept.");
otherFaction.sendMessage(Conf.colorSystem+"Type "+Conf.colorCommand+P.p.getBaseCommand()+" "+whishedRelation+" "+myFaction.getTag()+Conf.colorSystem+" to accept.");
myFaction.sendMessage(currentRelationColor+otherFaction.getTag()+Conf.colorSystem+ " were informed that you wish to be "+whishedRelation.getColor()+whishedRelation);
}
if (!whishedRelation.isNeutral() && otherFaction.isPeaceful()) {

View File

@ -12,7 +12,7 @@ import com.nijikokun.register.payment.Method.MethodAccount;
import com.iConomy.*;
import com.iConomy.system.*;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class Econ {
@ -21,11 +21,11 @@ public class Econ {
private static boolean essEcoUse = false;
public static void monitorPlugins() {
Factions.instance.getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new FactionsServerListener(), Event.Priority.Monitor, Factions.instance);
Factions.instance.getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_DISABLE, new FactionsServerListener(), Event.Priority.Monitor, Factions.instance);
P.p.getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new FactionsServerListener(P.p), Event.Priority.Monitor, P.p);
P.p.getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_DISABLE, new FactionsServerListener(P.p), Event.Priority.Monitor, P.p);
}
public static void setup(Factions factions) {
public static void setup(P factions) {
if (enabled()) {
return;
}
@ -50,80 +50,96 @@ public class Econ {
}
}
public static void registerSet(boolean enable) {
public static void registerSet(boolean enable)
{
registerUse = enable;
if (enable) {
Factions.log("Register hook available, "+(Conf.econRegisterEnabled ? "and interface is enabled" : "but disabled (\"econRegisterEnabled\": false)")+".");
P.p.log("Register hook available, "+(Conf.econRegisterEnabled ? "and interface is enabled" : "but disabled (\"econRegisterEnabled\": false)")+".");
}
else {
Factions.log("Un-hooked from Register.");
P.p.log("Un-hooked from Register.");
}
FCommandHelp.updateHelp();
}
public static void iConomySet(boolean enable) {
public static void iConomySet(boolean enable)
{
iConomyUse = enable;
if (enable && !registerUse) {
Factions.log("iConomy hook available, "+(Conf.econIConomyEnabled ? "and interface is enabled" : "but disabled (\"econIConomyEnabled\": false)")+".");
P.p.log("iConomy hook available, "+(Conf.econIConomyEnabled ? "and interface is enabled" : "but disabled (\"econIConomyEnabled\": false)")+".");
}
else {
Factions.log("Un-hooked from iConomy.");
P.p.log("Un-hooked from iConomy.");
}
FCommandHelp.updateHelp();
}
public static void essentialsEcoSet(boolean enable) {
public static void essentialsEcoSet(boolean enable)
{
essEcoUse = enable;
if (enable && !registerUse) {
Factions.log("EssentialsEco hook available, "+(Conf.econEssentialsEcoEnabled ? "and interface is enabled" : "but disabled (\"econEssentialsEcoEnabled\": false)")+".");
if (enable && !registerUse)
{
P.p.log("EssentialsEco hook available, "+(Conf.econEssentialsEcoEnabled ? "and interface is enabled" : "but disabled (\"econEssentialsEcoEnabled\": false)")+".");
}
else {
Factions.log("Un-hooked from EssentialsEco.");
else
{
P.p.log("Un-hooked from EssentialsEco.");
}
FCommandHelp.updateHelp();
}
public static boolean registerHooked() {
public static boolean registerHooked()
{
return registerUse;
}
public static boolean iConomyHooked() {
public static boolean iConomyHooked()
{
return iConomyUse;
}
public static boolean essentialsEcoHooked() {
public static boolean essentialsEcoHooked()
{
return essEcoUse;
}
public static boolean registerAvailable() {
public static boolean registerAvailable()
{
return Conf.econRegisterEnabled && registerUse && Methods.hasMethod();
}
// If economy is enabled in conf.json, and we're successfully hooked into an economy plugin
public static boolean enabled() {
public static boolean enabled()
{
return (Conf.econRegisterEnabled && registerUse && Methods.hasMethod())
|| (Conf.econIConomyEnabled && iConomyUse)
|| (Conf.econEssentialsEcoEnabled && essEcoUse);
}
// mainly for internal use, for a little less code repetition
public static Holdings getIconomyHoldings(String playerName) {
if (!enabled()) {
public static Holdings getIconomyHoldings(String playerName)
{
if ( ! enabled())
{
return null;
}
Account account = iConomy.getAccount(playerName);
if (account == null) {
if (account == null)
{
return null;
}
Holdings holdings = account.getHoldings();
return holdings;
}
public static MethodAccount getRegisterAccount(String playerName) {
if (!enabled()) {
public static MethodAccount getRegisterAccount(String playerName)
{
if (!enabled())
{
return null;
}
if (!Methods.getMethod().hasAccount(playerName)) {
if (!Methods.getMethod().hasAccount(playerName))
{
return null;
}
@ -133,7 +149,8 @@ public class Econ {
// format money string based on server's set currency type, like "24 gold" or "$24.50"
public static String moneyString(double amount) {
public static String moneyString(double amount)
{
return registerAvailable() ? Methods.getMethod().format(amount)
: (iConomyUse ? iConomy.format(amount) : Economy.format(amount));
}
@ -141,102 +158,129 @@ public class Econ {
// whether a player can afford specified amount
public static boolean canAfford(String playerName, double amount) {
// if Economy support is not enabled, they can certainly afford to pay nothing
if (!enabled()) {
if (!enabled())
{
return true;
}
if (registerAvailable()) {
if (registerAvailable())
{
MethodAccount holdings = getRegisterAccount(playerName);
if (holdings == null) {
if (holdings == null)
{
return false;
}
return holdings.hasEnough(amount);
}
else if (iConomyUse) {
else if (iConomyUse)
{
Holdings holdings = getIconomyHoldings(playerName);
if (holdings == null) {
if (holdings == null)
{
return false;
}
return holdings.hasEnough(amount);
}
else {
try {
else
{
try
{
return Economy.hasEnough(playerName, amount);
}
catch (Exception ex) {
catch (Exception ex)
{
return false;
}
}
}
// deduct money from their account; returns true if successful
public static boolean deductMoney(String playerName, double amount) {
if (!enabled()) {
public static boolean deductMoney(String playerName, double amount)
{
if (!enabled())
{
return true;
}
if (registerAvailable()) {
if (registerAvailable())
{
MethodAccount holdings = getRegisterAccount(playerName);
if (holdings == null || !holdings.hasEnough(amount)) {
if (holdings == null || !holdings.hasEnough(amount))
{
return false;
}
return holdings.subtract(amount);
}
else if (iConomyUse) {
else if (iConomyUse)
{
Holdings holdings = getIconomyHoldings(playerName);
if (holdings == null || !holdings.hasEnough(amount)) {
if (holdings == null || !holdings.hasEnough(amount))
{
return false;
}
holdings.subtract(amount);
return true;
}
else {
try {
if (!Economy.hasEnough(playerName, amount)) {
else
{
try
{
if (!Economy.hasEnough(playerName, amount))
{
return false;
}
Economy.subtract(playerName, amount);
return true;
}
catch (Exception ex) {
catch (Exception ex)
{
return false;
}
}
}
// add money to their account; returns true if successful
public static boolean addMoney(String playerName, double amount) {
if (!enabled()) {
public static boolean addMoney(String playerName, double amount)
{
if (!enabled())
{
return true;
}
if (registerAvailable()) {
if (registerAvailable())
{
MethodAccount holdings = getRegisterAccount(playerName);
if (holdings == null) {
if (holdings == null)
{
return false;
}
return holdings.add(amount);
}
else if (iConomyUse) {
else if (iConomyUse)
{
Holdings holdings = getIconomyHoldings(playerName);
if (holdings == null) {
if (holdings == null)
{
return false;
}
holdings.add(amount);
return true;
}
else {
try {
else
{
try
{
Economy.add(playerName, amount);
return true;
}
catch (Exception ex) {
catch (Exception ex)
{
return false;
}
}
@ -244,8 +288,10 @@ public class Econ {
// calculate the cost for claiming land
public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) {
if (!enabled()) {
public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction)
{
if (!enabled())
{
return 0.0;
}
@ -256,12 +302,14 @@ public class Econ {
}
// calculate refund amount for unclaiming land
public static double calculateClaimRefund(int ownedLand) {
public static double calculateClaimRefund(int ownedLand)
{
return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier;
}
// calculate value of all owned land
public static double calculateTotalLandValue(int ownedLand) {
public static double calculateTotalLandValue(int ownedLand)
{
double amount = 0;
for (int x = 0; x < ownedLand; x++) {
amount += calculateClaimCost(x, false);
@ -270,7 +318,8 @@ public class Econ {
}
// calculate refund amount for all owned land
public static double calculateTotalLandRefund(int ownedLand) {
public static double calculateTotalLandRefund(int ownedLand)
{
return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier;
}
}

View File

@ -2,39 +2,45 @@ package com.massivecraft.factions.integration;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.plugin.Plugin;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.earth2me.essentials.chat.EssentialsChat;
import com.earth2me.essentials.chat.IEssentialsChatListener;
public class EssentialsFeatures {
public class EssentialsFeatures
{
private static EssentialsChat essChat;
public static void integrateChat(EssentialsChat instance) {
public static void integrateChat(EssentialsChat instance)
{
essChat = instance;
try {
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener() {
try
{
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener()
{
public boolean shouldHandleThisChat(PlayerChatEvent event)
{
return Factions.instance.shouldLetFactionsHandleThisChat(event);
return P.p.shouldLetFactionsHandleThisChat(event);
}
public String modifyMessage(PlayerChatEvent event, Player target, String message)
{
return message.replace("{FACTION}", Factions.instance.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("{FACTION_TITLE}", Factions.instance.getPlayerTitle(event.getPlayer()));
return message.replace("{FACTION}", P.p.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("{FACTION_TITLE}", P.p.getPlayerTitle(event.getPlayer()));
}
});
Factions.log("Found and will integrate chat with "+essChat.getDescription().getFullName());
P.p.log("Found and will integrate chat with "+essChat.getDescription().getFullName());
}
catch (NoSuchMethodError ex) {
catch (NoSuchMethodError ex)
{
essChat = null;
}
}
public static void unhookChat() {
if (essChat != null) {
public static void unhookChat()
{
if (essChat != null)
{
essChat.removeEssentialsChatListener("Factions");
}
}

View File

@ -4,8 +4,9 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@ -24,25 +25,30 @@ import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.gui.WidgetAnchor;
public class SpoutFeatures {
public class SpoutFeatures
{
private transient static AppearanceManager spoutApp;
private transient static boolean spoutMe = false;
private transient static Map<String, GenericLabel> territoryLabels = new HashMap<String, GenericLabel>();
// set integration availability
public static void setAvailable(boolean enable, String pluginName) {
public static void setAvailable(boolean enable, String pluginName)
{
spoutMe = enable;
if (spoutMe) {
if (spoutMe)
{
spoutApp = SpoutManager.getAppearanceManager();
Factions.log("Found and will use features of "+pluginName);
P.p.log("Found and will use features of "+pluginName);
}
else {
else
{
spoutApp = null;
}
}
// If any Spout feature is enabled in conf.json, and we're successfully hooked into it
public static boolean enabled() {
public static boolean enabled()
{
return spoutMe && (
Conf.spoutFactionTagsOverNames
|| Conf.spoutFactionTitlesOverNames
@ -54,24 +60,30 @@ public class SpoutFeatures {
// update displayed current territory for specified player; returns false if unsuccessful
public static boolean updateTerritoryDisplay(FPlayer player) {
if (!spoutMe || Conf.spoutTerritoryDisplayPosition == 0) {
public static boolean updateTerritoryDisplay(FPlayer player)
{
if (!spoutMe || Conf.spoutTerritoryDisplayPosition == 0)
{
return false;
}
SpoutPlayer sPlayer = SpoutManager.getPlayer(player.getPlayer());
if (!sPlayer.isSpoutCraftEnabled()) {
if (!sPlayer.isSpoutCraftEnabled())
{
return false;
}
GenericLabel label;
if (territoryLabels.containsKey(player.getName())) {
if (territoryLabels.containsKey(player.getName()))
{
label = territoryLabels.get(player.getName());
}
else {
else
{
label = new GenericLabel();
sPlayer.getMainScreen().attachWidget(Factions.instance, label);
switch (Conf.spoutTerritoryDisplayPosition) {
sPlayer.getMainScreen().attachWidget(P.p, label);
switch (Conf.spoutTerritoryDisplayPosition)
{
case 1: label.setAlign(WidgetAnchor.TOP_LEFT).setAnchor(WidgetAnchor.TOP_LEFT); break;
case 2: label.setAlign(WidgetAnchor.TOP_CENTER).setAnchor(WidgetAnchor.TOP_CENTER); break;
default: label.setAlign(WidgetAnchor.TOP_RIGHT).setAnchor(WidgetAnchor.TOP_RIGHT);
@ -81,7 +93,8 @@ public class SpoutFeatures {
Faction factionHere = Board.getFactionAt(new FLocation(player));
String msg = factionHere.getTag();
if (factionHere.getDescription().length() > 0) {
if (factionHere.getDescription().length() > 0)
{
msg += " - "+factionHere.getDescription();
}
label.setTextColor(getSpoutColor(player.getRelationColor(factionHere), 0));
@ -91,8 +104,10 @@ public class SpoutFeatures {
return true;
}
public static void playerDisconnect(FPlayer player) {
if (!enabled()) {
public static void playerDisconnect(FPlayer player)
{
if (!enabled())
{
return;
}
territoryLabels.remove(player.getName());
@ -100,33 +115,40 @@ public class SpoutFeatures {
// update all appearances between every player
public static void updateAppearances() {
if (!enabled()) {
public static void updateAppearances()
{
if (!enabled())
{
return;
}
Set<FPlayer> players = FPlayer.getAllOnline();
Set<FPlayer> players = FPlayers.i.getOnline();
Faction factionA;
for (FPlayer playerA : players) {
for (FPlayer playerA : players)
{
factionA = playerA.getFaction();
for (FPlayer playerB : players) {
for (FPlayer playerB : players)
{
updateSingle(playerB.getPlayer(), playerA.getPlayer(), factionA.getRelation(playerB), factionA, playerA.getTitle(), playerA.getRole());
}
}
}
// update all appearances related to a specific player
public static void updateAppearances(Player player) {
if (!enabled() || player == null) {
public static void updateAppearances(Player player)
{
if (!enabled() || player == null)
{
return;
}
Set<FPlayer> players = FPlayer.getAllOnline();
FPlayer playerA = FPlayer.get(player);
Set<FPlayer> players = FPlayers.i.getOnline();
FPlayer playerA = FPlayers.i.get(player);
Faction factionA = playerA.getFaction();
for (FPlayer playerB : players) {
for (FPlayer playerB : players)
{
Player player2 = playerB.getPlayer();
Relation rel = factionA.getRelation(playerB);
updateSingle(player2, player, rel, factionA, playerA.getTitle(), playerA.getRole());
@ -135,20 +157,25 @@ public class SpoutFeatures {
}
// update all appearances related to a single faction
public static void updateAppearances(Faction faction) {
if (!enabled() || faction == null) {
public static void updateAppearances(Faction faction)
{
if (!enabled() || faction == null)
{
return;
}
Set<FPlayer> players = FPlayer.getAllOnline();
Set<FPlayer> players = FPlayers.i.getOnline();
Faction factionA, factionB;
for (FPlayer playerA : players) {
for (FPlayer playerA : players)
{
factionA = playerA.getFaction();
for (FPlayer playerB : players) {
for (FPlayer playerB : players)
{
factionB = playerB.getFaction();
if (factionA != faction && factionB != faction) {
if (factionA != faction && factionB != faction)
{
continue;
}
updateSingle(playerB.getPlayer(), playerA.getPlayer(), factionA.getRelation(factionB), factionA, playerA.getTitle(), playerA.getRole());
@ -157,13 +184,17 @@ public class SpoutFeatures {
}
// update all appearances between two factions
public static void updateAppearances(Faction factionA, Faction factionB) {
if (!enabled() || factionA == null || factionB == null) {
public static void updateAppearances(Faction factionA, Faction factionB)
{
if (!enabled() || factionA == null || factionB == null)
{
return;
}
for (FPlayer playerA : factionA.getFPlayersWhereOnline(true)) {
for (FPlayer playerB : factionB.getFPlayersWhereOnline(true)) {
for (FPlayer playerA : factionA.getFPlayersWhereOnline(true))
{
for (FPlayer playerB : factionB.getFPlayersWhereOnline(true))
{
Player player1 = playerA.getPlayer();
Player player2 = playerB.getPlayer();
Relation rel = factionA.getRelation(factionB);
@ -175,71 +206,102 @@ public class SpoutFeatures {
// update a single appearance; internal use only by above public methods
private static void updateSingle(Player viewer, Player viewed, Relation relation, Faction viewedFaction, String viewedTitle, Role viewedRole) {
if (viewer == null || viewed == null) {
private static void updateSingle(Player viewer, Player viewed, Relation relation, Faction viewedFaction, String viewedTitle, Role viewedRole)
{
if (viewer == null || viewed == null)
{
return;
}
SpoutPlayer sPlayer = SpoutManager.getPlayer(viewer);
if (Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames) {
if (viewedFaction.isNormal()) {
if (Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames)
{
if (viewedFaction.isNormal())
{
String addTag = "";
if (Conf.spoutFactionTagsOverNames) {
if (Conf.spoutFactionTagsOverNames)
{
addTag += viewedFaction.getTag(relation.getColor().toString() + "[") + "]";
}
String rolePrefix = viewedRole.getPrefix();
if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty())) {
if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty()))
{
addTag += (addTag.isEmpty() ? "" : " ") + viewedRole.getPrefix() + viewedTitle;
}
spoutApp.setPlayerTitle(sPlayer, viewed, addTag + "\n" + viewed.getDisplayName());
}
else {
else
{
spoutApp.setPlayerTitle(sPlayer, viewed, viewed.getDisplayName());
}
}
if (
(Conf.spoutFactionAdminCapes && viewedRole.equals(Role.ADMIN))
|| (Conf.spoutFactionModeratorCapes && viewedRole.equals(Role.MODERATOR))
) {
if
(
(
Conf.spoutFactionAdminCapes
&&
viewedRole.equals(Role.ADMIN)
)
||
(
Conf.spoutFactionModeratorCapes
&&
viewedRole.equals(Role.MODERATOR)
)
)
{
String cape = "";
if (!viewedFaction.isNormal()) {
if (!viewedFaction.isNormal())
{
// yeah, no cape if no faction
}
else if (viewedFaction.isPeaceful()) {
else if (viewedFaction.isPeaceful())
{
cape = Conf.capePeaceful;
}
else if (relation.isNeutral()) {
else if (relation.isNeutral())
{
cape = Conf.capeNeutral;
}
else if (relation.isMember()) {
else if (relation.isMember())
{
cape = Conf.capeMember;
}
else if (relation.isEnemy()) {
else if (relation.isEnemy())
{
cape = Conf.capeEnemy;
}
else if (relation.isAlly()) {
else if (relation.isAlly())
{
cape = Conf.capeAlly;
}
if (cape.isEmpty()) {
if (cape.isEmpty())
{
spoutApp.resetPlayerCloak(sPlayer, viewed);
} else {
}
else
{
spoutApp.setPlayerCloak(sPlayer, viewed, cape);
}
}
else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes) {
else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes)
{
spoutApp.resetPlayerCloak(sPlayer, viewed);
}
}
// method to convert a Bukkit ChatColor to a Spout Color
private static Color getSpoutColor(ChatColor inColor, int alpha) {
if (inColor == null) {
private static Color getSpoutColor(ChatColor inColor, int alpha)
{
if (inColor == null)
{
return new Color(191, 191, 191, alpha);
}
switch (inColor.getCode()) {
switch (inColor.getCode())
{
case 0x1: return new Color(0, 0, 191, alpha);
case 0x2: return new Color(0, 191, 0, alpha);
case 0x3: return new Color(0, 191, 191, alpha);

View File

@ -1,6 +1,6 @@
package com.massivecraft.factions.integration;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -28,24 +28,30 @@ import org.bukkit.entity.Player;
* Author: Spathizilla
*/
public class Worldguard {
public class Worldguard
{
private static WorldGuardPlugin wg;
private static boolean enabled = false;
public static void init(Plugin plugin) {
public static void init(Plugin plugin)
{
Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) {
if (wgplug == null || !(wgplug instanceof WorldGuardPlugin))
{
enabled = false;
wg = null;
Factions.log("Could not hook to WorldGuard. WorldGuard checks are disabled.");
} else {
P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled.");
}
else
{
wg = (WorldGuardPlugin) wgplug;
enabled = true;
Factions.log("Successfully hooked to WorldGuard.");
P.p.log("Successfully hooked to WorldGuard.");
}
}
public static boolean isEnabled() {
public static boolean isEnabled()
{
return enabled;
}
@ -53,8 +59,10 @@ public class Worldguard {
// Returns:
// True: PVP is allowed
// False: PVP is disallowed
public static boolean isPVP(Player player) {
if(!enabled) {
public static boolean isPVP(Player player)
{
if( ! enabled)
{
// No WG hooks so we'll always bypass this check.
return true;
}
@ -72,8 +80,10 @@ public class Worldguard {
// Returns:
// True: Regions found within chunk
// False: No regions found within chunk
public static boolean checkForRegionsInChunk(Location loc) {
if(!enabled) {
public static boolean checkForRegionsInChunk(Location loc)
{
if( ! enabled)
{
// No WG hooks so we'll always bypass this check.
return false;
}
@ -97,14 +107,20 @@ public class Worldguard {
List<ProtectedRegion> overlaps;
boolean foundregions = false;
try {
try
{
overlaps = region.getIntersectingRegions(allregionslist);
if(overlaps == null || overlaps.isEmpty()) {
if(overlaps == null || overlaps.isEmpty())
{
foundregions = false;
} else {
}
else
{
foundregions = true;
}
} catch (UnsupportedIntersectionException e) {
}
catch (UnsupportedIntersectionException e)
{
e.printStackTrace();
}

View File

@ -15,58 +15,65 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Relation;
public class FactionsBlockListener extends BlockListener {
public class FactionsBlockListener extends BlockListener
{
public P p;
public FactionsBlockListener(P p)
{
this.p = p;
}
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
if (!event.canBuild()) {
return;
}
public void onBlockPlace(BlockPlaceEvent event)
{
if (event.isCancelled()) return;
if ( ! event.canBuild()) return;
// special case for flint&steel, which should only be prevented by DenyUsage list
if (event.getBlockPlaced().getType() == Material.FIRE) {
if (event.getBlockPlaced().getType() == Material.FIRE)
{
return;
}
if ( ! this.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) {
if ( ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false))
{
event.setCancelled(true);
}
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
public void onBlockBreak(BlockBreakEvent event)
{
if (event.isCancelled()) return;
if ( ! this.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) {
if ( ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false))
{
event.setCancelled(true);
}
}
@Override
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
public void onBlockDamage(BlockDamageEvent event)
{
if (event.isCancelled()) return;
if (event.getInstaBreak() && ! this.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) {
if (event.getInstaBreak() && ! playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false))
{
event.setCancelled(true);
}
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (event.isCancelled() || !Conf.pistonProtectionThroughDenyBuild) {
return;
}
public void onBlockPistonExtend(BlockPistonExtendEvent event)
{
if (event.isCancelled()) return;
if ( ! Conf.pistonProtectionThroughDenyBuild) return;
Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock()));
@ -74,7 +81,8 @@ public class FactionsBlockListener extends BlockListener {
Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1);
// if potentially pushing into air in another territory, we need to check it out
if (targetBlock.isEmpty() && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) {
if (targetBlock.isEmpty() && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation()))
{
event.setCancelled(true);
return;
}
@ -87,49 +95,61 @@ public class FactionsBlockListener extends BlockListener {
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
public void onBlockPistonRetract(BlockPistonRetractEvent event)
{
// if not a sticky piston, retraction should be fine
if (event.isCancelled() || !event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) {
if (event.isCancelled() || !event.isSticky() || !Conf.pistonProtectionThroughDenyBuild)
{
return;
}
Location targetLoc = event.getRetractLocation();
// if potentially retracted block is just air, no worries
if (targetLoc.getBlock().isEmpty()) {
if (targetLoc.getBlock().isEmpty())
{
return;
}
Faction pistonFaction = Board.getFactionAt(new FLocation(event.getBlock()));
if (!canPistonMoveBlock(pistonFaction, targetLoc)) {
if (!canPistonMoveBlock(pistonFaction, targetLoc))
{
event.setCancelled(true);
return;
}
}
private boolean canPistonMoveBlock(Faction pistonFaction, Location target) {
private boolean canPistonMoveBlock(Faction pistonFaction, Location target)
{
Faction otherFaction = Board.getFactionAt(new FLocation(target));
if (pistonFaction == otherFaction) {
if (pistonFaction == otherFaction)
{
return true;
}
if (otherFaction.isNone()) {
if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName())) {
if (otherFaction.isNone())
{
if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()))
{
return true;
}
return false;
}
else if (otherFaction.isSafeZone()) {
if (!Conf.safeZoneDenyBuild) {
else if (otherFaction.isSafeZone())
{
if ( ! Conf.safeZoneDenyBuild)
{
return true;
}
return false;
}
else if (otherFaction.isWarZone()) {
if (!Conf.warZoneDenyBuild) {
else if (otherFaction.isWarZone())
{
if ( ! Conf.warZoneDenyBuild)
{
return true;
}
return false;
@ -138,37 +158,47 @@ public class FactionsBlockListener extends BlockListener {
Relation rel = pistonFaction.getRelation(otherFaction);
boolean online = otherFaction.hasPlayersOnline();
if (
if
(
(online && (rel.isEnemy() ? Conf.territoryEnemyDenyBuild : (rel.isAlly() ? Conf.territoryAllyDenyBuild : Conf.territoryDenyBuild)))
|| (!online && (rel.isEnemy() ? Conf.territoryEnemyDenyBuildWhenOffline : (rel.isAlly() ? Conf.territoryAllyDenyBuildWhenOffline : Conf.territoryDenyBuildWhenOffline)))
) {
||
(!online && (rel.isEnemy() ? Conf.territoryEnemyDenyBuildWhenOffline : (rel.isAlly() ? Conf.territoryAllyDenyBuildWhenOffline : Conf.territoryDenyBuildWhenOffline)))
)
{
return false;
}
return true;
}
public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) {
public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck)
{
if (Conf.adminBypassPlayers.contains(player.getName())) {
if (Conf.adminBypassPlayers.contains(player.getName()))
{
return true;
}
FLocation loc = new FLocation(location);
Faction otherFaction = Board.getFactionAt(loc);
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
if (otherFaction.isNone()) {
if (!Conf.wildernessDenyBuild || Factions.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) {
if (otherFaction.isNone())
{
if (!Conf.wildernessDenyBuild || P.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName()))
{
return true; // This is not faction territory. Use whatever you like here.
}
if (!justCheck) {
if (!justCheck)
{
me.sendMessage("You can't "+action+" in the wilderness.");
}
return false;
}
else if (otherFaction.isSafeZone()) {
if (!Conf.safeZoneDenyBuild || Factions.hasPermManageSafeZone(player)) {
else if (otherFaction.isSafeZone())
{
if (!Conf.safeZoneDenyBuild || P.hasPermManageSafeZone(player))
{
return true;
}
if (!justCheck) {
@ -176,11 +206,14 @@ public class FactionsBlockListener extends BlockListener {
}
return false;
}
else if (otherFaction.isWarZone()) {
if (!Conf.warZoneDenyBuild || Factions.hasPermManageWarZone(player)) {
else if (otherFaction.isWarZone())
{
if (!Conf.warZoneDenyBuild || P.hasPermManageWarZone(player))
{
return true;
}
if (!justCheck) {
if (!justCheck)
{
me.sendMessage("You can't "+action+" in a war zone.");
}
return false;
@ -191,38 +224,49 @@ public class FactionsBlockListener extends BlockListener {
boolean ownershipFail = Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc);
// Cancel and/or cause pain (depending on configuration) if we are not in our own territory
if (!rel.isMember()) {
if (!rel.isMember())
{
boolean online = otherFaction.hasPlayersOnline();
boolean pain = (!justCheck) && rel.confPainBuild(online);
boolean deny = rel.confDenyBuild(online);
//hurt the player for building/destroying?
if (pain) {
if (pain)
{
player.damage(Conf.actionDeniedPainAmount);
if (!deny) {
if (!deny)
{
me.sendMessage("You are hurt for "+action+" in the territory of "+otherFaction.getTag(myFaction));
if (!Conf.ownedAreaDenyBuild) {
if (!Conf.ownedAreaDenyBuild)
{
return true;
}
}
}
if (deny) {
if (!justCheck) {
if (deny)
{
if (!justCheck)
{
me.sendMessage("You can't "+action+" in the territory of "+otherFaction.getTag(myFaction));
}
return false;
}
}
// Also cancel and/or cause pain if player doesn't have ownership rights for this claim
else if (rel.isMember() && ownershipFail && !Factions.hasPermOwnershipBypass(player)) {
if (Conf.ownedAreaPainBuild && !justCheck){
else if (rel.isMember() && ownershipFail && !P.hasPermOwnershipBypass(player))
{
if (Conf.ownedAreaPainBuild && !justCheck)
{
player.damage(Conf.actionDeniedPainAmount);
if (!Conf.ownedAreaDenyBuild) {
if (!Conf.ownedAreaDenyBuild)
{
me.sendMessage("You are hurt for "+action+" in this territory, it is owned by: "+myFaction.getOwnerListString(loc));
}
}
if (Conf.ownedAreaDenyBuild){
if (!justCheck) {
if (Conf.ownedAreaDenyBuild)
{
if (!justCheck)
{
me.sendMessage("You can't "+action+" in this territory, it is owned by: "+myFaction.getOwnerListString(loc));
}
return false;

View File

@ -1,62 +1,70 @@
package com.massivecraft.factions.listeners;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.ChatMode;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.util.TextUtil;
// this is an addtional PlayerListener for handling slashless command usage and faction chat, to be set at low priority so Factions gets to them first
public class FactionsChatEarlyListener extends PlayerListener{
public class FactionsChatEarlyListener extends PlayerListener
{
public P p;
public FactionsChatEarlyListener(P p)
{
this.p = p;
}
@Override
public void onPlayerChat(PlayerChatEvent event) {
public void onPlayerChat(PlayerChatEvent event)
{
// Is it a slashless Factions command?
if ((event.getMessage().startsWith(Factions.instance.getBaseCommand()+" ") || event.getMessage().equals(Factions.instance.getBaseCommand())) && Conf.allowNoSlashCommand) {
/*if ((event.getMessage().startsWith(P.p.getBaseCommand()+" ") || event.getMessage().equals(P.p.getBaseCommand())) && Conf.allowNoSlashCommand) {
String msg = event.getMessage().trim();
// make sure command isn't denied due to being in enemy/neutral territory
if (!FactionsPlayerListener.preventCommand("/" + msg.toLowerCase(), event.getPlayer())) {
List<String> parameters = TextUtil.split(msg);
parameters.remove(0);
CommandSender sender = event.getPlayer();
Factions.instance.handleCommand(sender, parameters);
P.p.handleCommand(sender, parameters);
}
event.setCancelled(true);
return;
}
}*/
if (event.isCancelled()) {
return;
}
if (event.isCancelled()) return;
Player talkingPlayer = event.getPlayer();
String msg = event.getMessage();
// ... it was not a command. This means that it is a chat message!
FPlayer me = FPlayer.get(talkingPlayer);
FPlayer me = FPlayers.i.get(talkingPlayer);
// Is it a faction chat message?
if (me.getChatMode() == ChatMode.FACTION) {
if (me.getChatMode() == ChatMode.FACTION)
{
String message = String.format(Conf.factionChatFormat, me.getNameAndRelevant(me), msg);
me.getFaction().sendMessage(message);
Logger.getLogger("Minecraft").info(ChatColor.stripColor("FactionChat "+me.getFaction().getTag()+": "+message));
P.p.log(Level.INFO, ChatColor.stripColor("FactionChat "+me.getFaction().getTag()+": "+message));
event.setCancelled(true);
return;
} else if (me.getChatMode() == ChatMode.ALLIANCE ) {
}
else if (me.getChatMode() == ChatMode.ALLIANCE )
{
Faction myFaction = me.getFaction();
String factionAndName = ChatColor.stripColor(me.getNameAndTag());
@ -64,13 +72,17 @@ public class FactionsChatEarlyListener extends PlayerListener{
//Send message to our own faction
myFaction.sendMessage(message);
for (FPlayer fplayer : FPlayer.getAllOnline()) {
if(myFaction.getRelation(fplayer) == Relation.ALLY) {
for (FPlayer fplayer : FPlayers.i.getOnline())
{
if(myFaction.getRelation(fplayer) == Relation.ALLY)
{
//Send to all our allies
fplayer.sendMessage(message);
}
}
Logger.getLogger("Minecraft").info(ChatColor.stripColor("AllianceChat "+me.getFaction().getTag()+": "+message));
P.p.log(Level.INFO, ChatColor.stripColor("AllianceChat "+me.getFaction().getTag()+": "+message));
event.setCancelled(true);
return;
}

View File

@ -26,39 +26,58 @@ import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.util.EntityUtil;
import com.massivecraft.factions.util.MiscUtil;
public class FactionsEntityListener extends EntityListener {
public class FactionsEntityListener extends EntityListener
{
public P p;
public FactionsEntityListener(P p)
{
this.p = p;
}
@Override
public void onEntityDeath(EntityDeathEvent event) {
public void onEntityDeath(EntityDeathEvent event)
{
Entity entity = event.getEntity();
if ( ! (entity instanceof Player)) {
if ( ! (entity instanceof Player))
{
return;
}
Player player = (Player) entity;
FPlayer fplayer = FPlayer.get(player);
FPlayer fplayer = FPlayers.i.get(player);
Faction faction = Board.getFactionAt(new FLocation(player.getLocation()));
if (faction.isWarZone()) { // war zones always override worldsNoPowerLoss either way, thus this layout
if (! Conf.warZonePowerLoss) {
if (faction.isWarZone())
{
// war zones always override worldsNoPowerLoss either way, thus this layout
if (! Conf.warZonePowerLoss)
{
fplayer.sendMessage("You didn't lose any power since you were in a war zone.");
return;
}
if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) {
if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName()))
{
fplayer.sendMessage("The world you are in has power loss normally disabled, but you still lost power since you were in a war zone.");
}
} else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) {
}
else if (faction.isNone() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName()))
{
fplayer.sendMessage("You didn't lose any power since you were in the wilderness.");
return;
} else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) {
}
else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName()))
{
fplayer.sendMessage("You didn't lose any power due to the world you died in.");
return;
} else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) {
}
else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful())
{
fplayer.sendMessage("You didn't lose any power since you are in a peaceful faction.");
return;
}
@ -92,105 +111,161 @@ public class FactionsEntityListener extends EntityListener {
@Override
public void onEntityExplode(EntityExplodeEvent event)
{
if ( event.isCancelled()) {
return;
}
if ( event.isCancelled()) return;
Location loc = event.getLocation();
Faction faction = Board.getFactionAt(new FLocation(loc));
boolean online = faction.hasPlayersOnline();
if (faction.noExplosionsInTerritory()) {
if (faction.noExplosionsInTerritory())
{
// faction is peaceful and has explosions set to disabled
event.setCancelled(true);
}
else if (event.getEntity() instanceof Creeper && (
(faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) ||
(faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) ||
(faction.isWarZone() && Conf.warZoneBlockCreepers) ||
else if
(
event.getEntity() instanceof Creeper
&&
(
(faction.isNone() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()))
||
(faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline))
||
(faction.isWarZone() && Conf.warZoneBlockCreepers)
||
faction.isSafeZone()
)) {
)
)
{
// creeper which needs prevention
event.setCancelled(true);
} else if (event.getEntity() instanceof Fireball && (
(faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) ||
(faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) ||
(faction.isWarZone() && Conf.warZoneBlockFireballs) ||
}
else if
(
event.getEntity() instanceof Fireball
&&
(
(faction.isNone() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()))
||
(faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline))
||
(faction.isWarZone() && Conf.warZoneBlockFireballs)
||
faction.isSafeZone()
)) {
)
)
{
// ghast fireball which needs prevention
event.setCancelled(true);
} else if (
(faction.isNone() && Conf.wildernessBlockTNT && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) ||
(faction.isNormal() && (online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline)) ||
(faction.isWarZone() && Conf.warZoneBlockTNT) ||
(faction.isSafeZone() && Conf.safeZoneBlockTNT)
) {
}
else if
(
(
faction.isNone()
&&
Conf.wildernessBlockTNT
&&
! Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())
)
||
(
faction.isNormal()
&&
(
online ? Conf.territoryBlockTNT : Conf.territoryBlockTNTWhenOffline
)
)
||
(
faction.isWarZone()
&&
Conf.warZoneBlockTNT
)
||
(
faction.isSafeZone()
&&
Conf.safeZoneBlockTNT
)
)
{
// we'll assume it's TNT, which needs prevention
event.setCancelled(true);
}
}
public boolean isPlayerInSafeZone(Entity damagee) {
if ( ! (damagee instanceof Player)) {
public boolean isPlayerInSafeZone(Entity damagee)
{
if ( ! (damagee instanceof Player))
{
return false;
}
if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone()) {
if (Board.getFactionAt(new FLocation(damagee.getLocation())).isSafeZone())
{
return true;
}
return false;
}
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) {
public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub)
{
Entity damager = sub.getDamager();
Entity damagee = sub.getEntity();
int damage = sub.getDamage();
if ( ! (damagee instanceof Player)) {
if ( ! (damagee instanceof Player))
{
return true;
}
FPlayer defender = FPlayer.get((Player)damagee);
FPlayer defender = FPlayers.i.get((Player)damagee);
if (defender == null || defender.getPlayer() == null) {
if (defender == null || defender.getPlayer() == null)
{
return true;
}
Location defenderLoc = defender.getPlayer().getLocation();
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) {
if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName()))
{
return true;
}
Faction defLocFaction = Board.getFactionAt(new FLocation(defenderLoc));
// for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source
if (damager instanceof Projectile) {
if (damager instanceof Projectile)
{
damager = ((Projectile)damager).getShooter();
}
// Players can not take attack damage in a SafeZone, or possibly peaceful territory
if (defLocFaction.noPvPInTerritory()) {
if (damager instanceof Player) {
FPlayer attacker = FPlayer.get((Player)damager);
if (damager instanceof Player)
{
FPlayer attacker = FPlayers.i.get((Player)damager);
attacker.sendMessage("You can't hurt other players in "+(defLocFaction.isSafeZone() ? "a SafeZone." : "peaceful territory."));
return false;
}
return !defLocFaction.noMonstersInTerritory();
}
if ( ! (damager instanceof Player)) {
if ( ! (damager instanceof Player))
{
return true;
}
FPlayer attacker = FPlayer.get((Player)damager);
FPlayer attacker = FPlayers.i.get((Player)damager);
if (attacker == null || attacker.getPlayer() == null) {
if (attacker == null || attacker.getPlayer() == null)
{
return true;
}
if (attacker.hasLoginPvpDisabled()) {
if (attacker.hasLoginPvpDisabled())
{
attacker.sendMessage("You can't hurt other players for " + Conf.noPVPDamageToOthersForXSecondsAfterLogin + " seconds after logging in.");
return false;
}
@ -198,37 +273,45 @@ public class FactionsEntityListener extends EntityListener {
Faction locFaction = Board.getFactionAt(new FLocation(attacker));
// so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be?
if (locFaction.noPvPInTerritory()) {
if (locFaction.noPvPInTerritory())
{
attacker.sendMessage("You can't hurt other players while you are in "+(locFaction.isSafeZone() ? "a SafeZone." : "peaceful territory."));
return false;
}
else if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) {
else if (locFaction.isWarZone() && Conf.warZoneFriendlyFire)
{
return true;
}
Faction defendFaction = defender.getFaction();
Faction attackFaction = attacker.getFaction();
if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers) {
if (attackFaction.isNone() && Conf.disablePVPForFactionlessPlayers)
{
attacker.sendMessage("You can't hurt other players until you join a faction.");
return false;
}
else if (defendFaction.isNone()) {
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) {
else if (defendFaction.isNone())
{
if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand)
{
// Allow PVP vs. Factionless in attacker's faction territory
return true;
}
else if (Conf.disablePVPForFactionlessPlayers) {
else if (Conf.disablePVPForFactionlessPlayers)
{
attacker.sendMessage("You can't hurt players who are not currently in a faction.");
return false;
}
}
if (defendFaction.isPeaceful()) {
if (defendFaction.isPeaceful())
{
attacker.sendMessage("You can't hurt players who are in a peaceful faction.");
return false;
}
else if (attackFaction.isPeaceful()) {
else if (attackFaction.isPeaceful())
{
attacker.sendMessage("You can't hurt players while you are in a peaceful faction.");
return false;
}
@ -236,74 +319,84 @@ public class FactionsEntityListener extends EntityListener {
Relation relation = defendFaction.getRelation(attackFaction);
// You can not hurt neutral factions
if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) {
if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral())
{
attacker.sendMessage("You can't hurt neutral factions");
return false;
}
// Players without faction may be hurt anywhere
if (!defender.hasFaction()) {
if (!defender.hasFaction())
{
return true;
}
// You can never hurt faction members or allies
if (relation.isMember() || relation.isAlly()) {
attacker.sendMessage(Conf.colorSystem+"You can't hurt "+defender.getNameAndRelevant(attacker));
if (relation.isMember() || relation.isAlly())
{
attacker.sendMessage(p.txt.parse("<i>You can't hurt "+defender.getNameAndRelevant(attacker)));
return false;
}
boolean ownTerritory = defender.isInOwnTerritory();
// You can not hurt neutrals in their own territory.
if (ownTerritory && relation.isNeutral()) {
attacker.sendMessage(Conf.colorSystem+"You can't hurt "+relation.getColor()+defender.getNameAndRelevant(attacker)+Conf.colorSystem+" in their own territory.");
defender.sendMessage(attacker.getNameAndRelevant(defender)+Conf.colorSystem+" tried to hurt you.");
if (ownTerritory && relation.isNeutral())
{
attacker.sendMessage(p.txt.parse("<i>You can't hurt "+relation.getColor()+defender.getNameAndRelevant(attacker)+"<i> in their own territory."));
defender.sendMessage(p.txt.parse(attacker.getNameAndRelevant(defender)+"<i> tried to hurt you."));
return false;
}
// Damage will be dealt. However check if the damage should be reduced.
if (ownTerritory && Conf.territoryShieldFactor > 0) {
if (ownTerritory && Conf.territoryShieldFactor > 0)
{
int newDamage = (int)Math.ceil(damage * (1D - Conf.territoryShieldFactor));
sub.setDamage(newDamage);
// Send message
String perc = MessageFormat.format("{0,number,#%}", (Conf.territoryShieldFactor)); // TODO does this display correctly??
defender.sendMessage("Enemy damage reduced by "+ChatColor.RED+perc+Conf.colorSystem+".");
defender.sendMessage(p.txt.parse("<i>Enemy damage reduced by "+ChatColor.RED+perc+"<i>."));
}
return true;
}
@Override
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (event.isCancelled() || event.getLocation() == null) {
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (event.isCancelled() || event.getLocation() == null)
{
return;
}
if (Conf.safeZoneNerfedCreatureTypes.contains(event.getCreatureType()) && Board.getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory()) {
if (Conf.safeZoneNerfedCreatureTypes.contains(event.getCreatureType()) && Board.getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory())
{
event.setCancelled(true);
}
}
@Override
public void onEntityTarget(EntityTargetEvent event) {
if (event.isCancelled()) {
return;
}
public void onEntityTarget(EntityTargetEvent event)
{
if (event.isCancelled()) return;
// if there is a target
Entity target = event.getTarget();
if (target == null) {
if (target == null)
{
return;
}
// We are interested in blocking targeting for certain mobs:
if ( ! Conf.safeZoneNerfedCreatureTypes.contains(EntityUtil.creatureTypeFromEntity(event.getEntity()))) {
if ( ! Conf.safeZoneNerfedCreatureTypes.contains(MiscUtil.creatureTypeFromEntity(event.getEntity())))
{
return;
}
// in case the target is in a safe zone.
if (Board.getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) {
if (Board.getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory())
{
event.setCancelled(true);
}
}
@ -311,21 +404,23 @@ public class FactionsEntityListener extends EntityListener {
@Override
public void onPaintingBreak(PaintingBreakEvent event)
{
if (event.isCancelled()) {
return;
}
if (! (event instanceof PaintingBreakByEntityEvent)) {
if (event.isCancelled()) return;
if (! (event instanceof PaintingBreakByEntityEvent))
{
return;
}
Entity breaker = ((PaintingBreakByEntityEvent)event).getRemover();
if (! (breaker instanceof Player)) {
if (! (breaker instanceof Player))
{
return;
}
FLocation loc = new FLocation(event.getPainting().getLocation());
if ( ! this.playerCanDoPaintings((Player)breaker, loc, "remove")) {
if ( ! this.playerCanDoPaintings((Player)breaker, loc, "remove"))
{
event.setCancelled(true);
}
}
@ -333,41 +428,48 @@ public class FactionsEntityListener extends EntityListener {
@Override
public void onPaintingPlace(PaintingPlaceEvent event)
{
if (event.isCancelled()) {
return;
}
if (event.isCancelled()) return;
if ( ! this.playerCanDoPaintings(event.getPlayer(), new FLocation(event.getBlock()), "place")) {
if ( ! this.playerCanDoPaintings(event.getPlayer(), new FLocation(event.getBlock()), "place"))
{
event.setCancelled(true);
}
}
public boolean playerCanDoPaintings(Player player, FLocation loc, String action) {
public boolean playerCanDoPaintings(Player player, FLocation loc, String action)
{
if (Conf.adminBypassPlayers.contains(player.getName())) {
if (Conf.adminBypassPlayers.contains(player.getName()))
{
return true;
}
Faction otherFaction = Board.getFactionAt(loc);
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
if (otherFaction.isNone()) {
if (!Conf.wildernessDenyBuild || Factions.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) {
if (otherFaction.isNone())
{
if (!Conf.wildernessDenyBuild || P.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(player.getWorld().getName()))
{
return true; // This is not faction territory. Use whatever you like here.
}
me.sendMessage("You can't "+action+" paintings in the wilderness.");
return false;
}
if (otherFaction.isSafeZone()) {
if (Factions.hasPermManageSafeZone(player) || !Conf.safeZoneDenyBuild) {
if (otherFaction.isSafeZone())
{
if (P.hasPermManageSafeZone(player) || !Conf.safeZoneDenyBuild)
{
return true;
}
me.sendMessage("You can't "+action+" paintings in a safe zone.");
return false;
}
else if (otherFaction.isWarZone()) {
if (Factions.hasPermManageWarZone(player) || !Conf.warZoneDenyBuild) {
else if (otherFaction.isWarZone())
{
if (P.hasPermManageWarZone(player) || !Conf.warZoneDenyBuild)
{
return true;
}
me.sendMessage("You can't "+action+" paintings in a war zone.");
@ -379,12 +481,14 @@ public class FactionsEntityListener extends EntityListener {
boolean ownershipFail = Conf.ownedAreasEnabled && Conf.ownedAreaDenyBuild && !otherFaction.playerHasOwnershipRights(me, loc);
// Cancel if we are not in our own territory and building should be denied
if (!rel.isMember() && rel.confDenyBuild(otherFaction.hasPlayersOnline())) {
if (!rel.isMember() && rel.confDenyBuild(otherFaction.hasPlayersOnline()))
{
me.sendMessage("You can't "+action+" paintings in the territory of "+otherFaction.getTag(myFaction));
return false;
}
// Also cancel if player doesn't have ownership rights for this claim
else if (rel.isMember() && ownershipFail && !Factions.hasPermOwnershipBypass(player)) {
else if (rel.isMember() && ownershipFail && !P.hasPermOwnershipBypass(player))
{
me.sendMessage("You can't "+action+" paintings in this territory, it is owned by: "+otherFaction.getOwnerListString(loc));
return false;
}
@ -393,54 +497,67 @@ public class FactionsEntityListener extends EntityListener {
}
@Override
public void onEndermanPickup(EndermanPickupEvent event) {
if (event.isCancelled()) {
return;
}
public void onEndermanPickup(EndermanPickupEvent event)
{
if (event.isCancelled()) return;
if (stopEndermanBlockManipulation(event.getBlock().getLocation())) {
if (stopEndermanBlockManipulation(event.getBlock().getLocation()))
{
event.setCancelled(true);
}
}
@Override
public void onEndermanPlace(EndermanPlaceEvent event) {
if (event.isCancelled()) {
return;
}
public void onEndermanPlace(EndermanPlaceEvent event)
{
if (event.isCancelled()) return;
if (stopEndermanBlockManipulation(event.getLocation())) {
if (stopEndermanBlockManipulation(event.getLocation()))
{
event.setCancelled(true);
}
}
private boolean stopEndermanBlockManipulation(Location loc) {
if (loc == null) {
private boolean stopEndermanBlockManipulation(Location loc)
{
if (loc == null)
{
return false;
}
// quick check to see if all Enderman deny options are enabled; if so, no need to check location
if ( Conf.wildernessDenyEndermanBlocks
&& Conf.territoryDenyEndermanBlocks
&& Conf.territoryDenyEndermanBlocksWhenOffline
&& Conf.safeZoneDenyEndermanBlocks
&& Conf.warZoneDenyEndermanBlocks
) {
if
(
Conf.wildernessDenyEndermanBlocks
&&
Conf.territoryDenyEndermanBlocks
&&
Conf.territoryDenyEndermanBlocksWhenOffline
&&
Conf.safeZoneDenyEndermanBlocks
&&
Conf.warZoneDenyEndermanBlocks
)
{
return true;
}
FLocation fLoc = new FLocation(loc);
Faction claimFaction = Board.getFactionAt(fLoc);
if (claimFaction.isNone()) {
if (claimFaction.isNone())
{
return Conf.wildernessDenyEndermanBlocks;
}
else if (claimFaction.isNormal()) {
else if (claimFaction.isNormal())
{
return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline;
}
else if (claimFaction.isSafeZone()) {
else if (claimFaction.isSafeZone())
{
return Conf.safeZoneDenyEndermanBlocks;
}
else if (claimFaction.isWarZone()) {
else if (claimFaction.isWarZone())
{
return Conf.warZoneDenyEndermanBlocks;
}

View File

@ -25,46 +25,56 @@ import org.bukkit.event.player.PlayerRespawnEvent;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.util.TextUtil;
import com.massivecraft.factions.zcore.util.TextUtil;
import java.util.logging.Level;
public class FactionsPlayerListener extends PlayerListener{
public class FactionsPlayerListener extends PlayerListener
{
public P p;
public FactionsPlayerListener(P p)
{
this.p = p;
}
@Override
public void onPlayerChat(PlayerChatEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerChat(PlayerChatEvent event)
{
if (event.isCancelled()) return;
Player talkingPlayer = event.getPlayer();
String msg = event.getMessage();
// ... it was not a command. This means that it is a chat message!
FPlayer me = FPlayer.get(talkingPlayer);
FPlayer me = FPlayers.i.get(talkingPlayer);
// Are we to insert the Faction tag into the format?
// If we are not to insert it - we are done.
if ( ! Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin) {
if ( ! Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin)
{
return;
}
int InsertIndex = 0;
String eventFormat = event.getFormat();
if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) {
if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString))
{
// we're using the "replace" method of inserting the faction tags
// if they stuck "{FACTION_TITLE}" in there, go ahead and do it too
if (eventFormat.contains("{FACTION_TITLE}")) {
if (eventFormat.contains("{FACTION_TITLE}"))
{
eventFormat = eventFormat.replace("{FACTION_TITLE}", me.getTitle());
}
InsertIndex = eventFormat.indexOf(Conf.chatTagReplaceString);
@ -72,15 +82,18 @@ public class FactionsPlayerListener extends PlayerListener{
Conf.chatTagPadAfter = false;
Conf.chatTagPadBefore = false;
}
else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString)) {
else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString))
{
// we're using the "insert after string" method
InsertIndex = eventFormat.indexOf(Conf.chatTagInsertAfterString) + Conf.chatTagInsertAfterString.length();
}
else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) {
else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString))
{
// we're using the "insert before string" method
InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString);
}
else {
else
{
// we'll fall back to using the index place method
InsertIndex = Conf.chatTagInsertIndex;
if (InsertIndex > eventFormat.length())
@ -93,23 +106,27 @@ public class FactionsPlayerListener extends PlayerListener{
String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd;
// Relation Colored?
if (Conf.chatTagRelationColored) {
if (Conf.chatTagRelationColored)
{
// We must choke the standard message and send out individual messages to all players
// Why? Because the relations will differ.
event.setCancelled(true);
for (Player listeningPlayer : event.getRecipients()) {
FPlayer you = FPlayer.get(listeningPlayer);
for (Player listeningPlayer : event.getRecipients())
{
FPlayer you = FPlayers.i.get(listeningPlayer);
String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd;
try {
try
{
listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg));
}
catch (UnknownFormatConversionException ex) {
Factions.log(Level.SEVERE, "Critical error in chat message formatting! Complete format string: "+yourFormat);
Factions.log(Level.SEVERE, "First half of event.getFormat() string: "+formatStart);
Factions.log(Level.SEVERE, "Second half of event.getFormat() string: "+formatEnd);
Factions.log(Level.SEVERE, "NOTE: To fix this quickly, running this command should work: f config chatTagInsertIndex 0");
Factions.log(Level.SEVERE, "For a more proper fix, please read the chat configuration notes on the configuration page of the Factions user guide.");
catch (UnknownFormatConversionException ex)
{
P.p.log(Level.SEVERE, "Critical error in chat message formatting! Complete format string: "+yourFormat);
P.p.log(Level.SEVERE, "First half of event.getFormat() string: "+formatStart);
P.p.log(Level.SEVERE, "Second half of event.getFormat() string: "+formatEnd);
P.p.log(Level.SEVERE, "NOTE: To fix this quickly, running this command should work: f config chatTagInsertIndex 0");
P.p.log(Level.SEVERE, "For a more proper fix, please read the chat configuration notes on the configuration page of the Factions user guide.");
ex.printStackTrace();
return;
}
@ -118,28 +135,31 @@ public class FactionsPlayerListener extends PlayerListener{
// Write to the log... We will write the non colored message.
String nonColoredMsg = ChatColor.stripColor(String.format(nonColoredMsgFormat, talkingPlayer.getDisplayName(), msg));
Logger.getLogger("Minecraft").info(nonColoredMsg);
} else {
}
else
{
// No relation color.
event.setFormat(nonColoredMsgFormat);
}
}
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
public void onPlayerJoin(PlayerJoinEvent event)
{
// Make sure that all online players do have a fplayer.
final FPlayer me = FPlayer.get(event.getPlayer());
final FPlayer me = FPlayers.i.get(event.getPlayer());
// Update the lastLoginTime for this fplayer
me.setLastLoginTime(System.currentTimeMillis());
// Run the member auto kick routine. Twice to get to the admins...
FPlayer.autoLeaveOnInactivityRoutine();
FPlayer.autoLeaveOnInactivityRoutine();
FPlayers.i.autoLeaveOnInactivityRoutine();
FPlayers.i.autoLeaveOnInactivityRoutine();
SpoutFeatures.updateTerritoryDisplay(me);
// Appearance updates which are run when a player joins don't apply properly for other clients, so they need to be delayed slightly
Factions.instance.getServer().getScheduler().scheduleSyncDelayedTask(Factions.instance, new Runnable() {
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, new Runnable() {
public void run() {
SpoutFeatures.updateAppearances(me.getPlayer());
SpoutFeatures.updateTerritoryDisplay(me);
@ -148,27 +168,31 @@ public class FactionsPlayerListener extends PlayerListener{
}
@Override
public void onPlayerQuit(PlayerQuitEvent event) {
public void onPlayerQuit(PlayerQuitEvent event)
{
// Make sure player's power is up to date when they log off.
FPlayer me = FPlayer.get(event.getPlayer());
FPlayer me = FPlayers.i.get(event.getPlayer());
me.getPower();
Faction myFaction = me.getFaction();
if (myFaction != null) {
if (myFaction != null)
{
myFaction.memberLoggedOff();
}
SpoutFeatures.playerDisconnect(me);
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
public void onPlayerMove(PlayerMoveEvent event)
{
Player player = event.getPlayer();
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
// Did we change coord?
FLocation from = me.getLastStoodAt();
FLocation to = new FLocation(player.getLocation());
if (from.equals(to)) {
if (from.equals(to))
{
return;
}
@ -176,73 +200,98 @@ public class FactionsPlayerListener extends PlayerListener{
me.setLastStoodAt(to);
if (me.isMapAutoUpdating()) {
if (me.isMapAutoUpdating())
{
me.sendMessage(Board.getMap(me.getFaction(), to, player.getLocation().getYaw()));
} else {
}
else
{
// Did we change "host"(faction)?
Faction factionFrom = Board.getFactionAt(from);
Faction factionTo = Board.getFactionAt(to);
Faction myFaction = me.getFaction();
String ownersTo = myFaction.getOwnerListString(to);
if (factionFrom != factionTo) {
if (factionFrom != factionTo)
{
me.sendFactionHereMessage();
if (Conf.ownedAreasEnabled && Conf.ownedMessageOnBorder && myFaction == factionTo && !ownersTo.isEmpty()) {
if (Conf.ownedAreasEnabled && Conf.ownedMessageOnBorder && myFaction == factionTo && !ownersTo.isEmpty())
{
me.sendMessage(Conf.ownedLandMessage+ownersTo);
}
}
else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && factionFrom == factionTo && myFaction == factionTo) {
else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && factionFrom == factionTo && myFaction == factionTo)
{
String ownersFrom = myFaction.getOwnerListString(from);
if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) {
if (!ownersTo.isEmpty()) {
if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo))
{
if (!ownersTo.isEmpty())
{
me.sendMessage(Conf.ownedLandMessage+ownersTo);
}
else if (!Conf.publicLandMessage.isEmpty()) {
else if (!Conf.publicLandMessage.isEmpty())
{
me.sendMessage(Conf.publicLandMessage);
}
}
}
}
if (me.autoClaimEnabled()) {
if (me.autoClaimEnabled())
{
Faction myFaction = me.getFaction();
Faction otherFaction = Board.getFactionAt(to);
double cost = Econ.calculateClaimCost(myFaction.getLandRounded(), otherFaction.isNormal());
// TODO: Why is this ("cost") here and unused??? Should it be used somewhere Brettflan? :)
// Olof just commented it out to avoid the error.
//Faction otherFaction = Board.getFactionAt(to);
//double cost = Econ.calculateClaimCost(myFaction.getLandRounded(), otherFaction.isNormal());
if (me.getRole().value < Role.MODERATOR.value) {
if (me.getRole().value < Role.MODERATOR.value)
{
me.sendMessage("You must be "+Role.MODERATOR+" to claim land.");
me.enableAutoClaim(false);
}
else if (Conf.worldsNoClaiming.contains(to.getWorldName())) {
else if (Conf.worldsNoClaiming.contains(to.getWorldName()))
{
me.sendMessage("Sorry, this world has land claiming disabled.");
me.enableAutoClaim(false);
}
else if (myFaction.getLandRounded() >= myFaction.getPowerRounded()) {
else if (myFaction.getLandRounded() >= myFaction.getPowerRounded())
{
me.sendMessage("You can't claim more land! You need more power!");
me.enableAutoClaim(false);
}
else
me.attemptClaim(false);
}
else if (me.autoSafeZoneEnabled()) {
if (!Factions.hasPermManageSafeZone((CommandSender)player)) {
else if (me.autoSafeZoneEnabled())
{
if (!P.hasPermManageSafeZone((CommandSender)player))
{
me.enableAutoSafeZone(false);
} else {
}
else
{
FLocation playerFlocation = new FLocation(me);
if (!Board.getFactionAt(playerFlocation).isSafeZone()) {
Board.setFactionAt(Faction.getSafeZone(), playerFlocation);
if (!Board.getFactionAt(playerFlocation).isSafeZone())
{
Board.setFactionAt(Factions.i.getSafeZone(), playerFlocation);
me.sendMessage("This land is now a safe zone.");
}
}
}
else if (me.autoWarZoneEnabled()) {
if (!Factions.hasPermManageWarZone((CommandSender)player)) {
else if (me.autoWarZoneEnabled())
{
if (!P.hasPermManageWarZone((CommandSender)player))
{
me.enableAutoWarZone(false);
} else {
}
else
{
FLocation playerFlocation = new FLocation(me);
if (!Board.getFactionAt(playerFlocation).isWarZone()) {
Board.setFactionAt(Faction.getWarZone(), playerFlocation);
if (!Board.getFactionAt(playerFlocation).isWarZone())
{
Board.setFactionAt(Factions.i.getWarZone(), playerFlocation);
me.sendMessage("This land is now a war zone.");
}
}
@ -250,36 +299,41 @@ public class FactionsPlayerListener extends PlayerListener{
}
@Override
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.isCancelled()) return;
Block block = event.getClickedBlock();
Player player = event.getPlayer();
if (block == null) {
if (block == null)
{
return; // clicked in air, apparently
}
if ( ! canPlayerUseBlock(player, block, false)) {
if ( ! canPlayerUseBlock(player, block, false))
{
event.setCancelled(true);
return;
}
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK)
{
return; // only interested on right-clicks for below
}
if ( ! this.playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) {
if ( ! playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false))
{
event.setCancelled(true);
return;
}
}
public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) {
public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck)
{
if (Conf.adminBypassPlayers.contains(player.getName())) {
if (Conf.adminBypassPlayers.contains(player.getName()))
{
return true;
}
@ -287,40 +341,54 @@ public class FactionsPlayerListener extends PlayerListener{
Faction otherFaction = Board.getFactionAt(loc);
if (otherFaction.hasPlayersOnline()){
if ( ! Conf.territoryDenyUseageMaterials.contains(material)) {
if ( ! Conf.territoryDenyUseageMaterials.contains(material))
{
return true; // Item isn't one we're preventing for online factions.
}
}else{
if ( ! Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) {
}
else
{
if ( ! Conf.territoryDenyUseageMaterialsWhenOffline.contains(material))
{
return true; // Item isn't one we're preventing for offline factions.
}
}
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
if (otherFaction.isNone()) {
if (!Conf.wildernessDenyUseage || Factions.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) {
if (otherFaction.isNone())
{
if (!Conf.wildernessDenyUseage || P.hasPermAdminBypass(player) || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName()))
{
return true; // This is not faction territory. Use whatever you like here.
}
if (!justCheck) {
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in the wilderness.");
}
return false;
}
else if (otherFaction.isSafeZone()) {
if (!Conf.safeZoneDenyUseage || Factions.hasPermManageSafeZone(player)) {
else if (otherFaction.isSafeZone())
{
if (!Conf.safeZoneDenyUseage || P.hasPermManageSafeZone(player))
{
return true;
}
if (!justCheck) {
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in a safe zone.");
}
return false;
}
else if (otherFaction.isWarZone()) {
if (!Conf.warZoneDenyUseage || Factions.hasPermManageWarZone(player)) {
else if (otherFaction.isWarZone())
{
if (!Conf.warZoneDenyUseage || P.hasPermManageWarZone(player))
{
return true;
}
if (!justCheck) {
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in a war zone.");
}
return false;
@ -331,15 +399,19 @@ public class FactionsPlayerListener extends PlayerListener{
boolean ownershipFail = Conf.ownedAreasEnabled && Conf.ownedAreaDenyUseage && !otherFaction.playerHasOwnershipRights(me, loc);
// Cancel if we are not in our own territory
if (!rel.isMember() && rel.confDenyUseage()) {
if (!justCheck) {
if (!rel.isMember() && rel.confDenyUseage())
{
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in the territory of "+otherFaction.getTag(myFaction));
}
return false;
}
// Also cancel if player doesn't have ownership rights for this claim
else if (rel.isMember() && ownershipFail && !Factions.hasPermOwnershipBypass(player)) {
if (!justCheck) {
else if (rel.isMember() && ownershipFail && !P.hasPermOwnershipBypass(player))
{
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in this territory, it is owned by: "+myFaction.getOwnerListString(loc));
}
return false;
@ -348,9 +420,11 @@ public class FactionsPlayerListener extends PlayerListener{
return true;
}
public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) {
public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck)
{
if (Conf.adminBypassPlayers.contains(player.getName())) {
if (Conf.adminBypassPlayers.contains(player.getName()))
{
return true;
}
@ -359,36 +433,46 @@ public class FactionsPlayerListener extends PlayerListener{
Faction otherFaction = Board.getFactionAt(loc);
// no door/chest/whatever protection in wilderness, war zones, or safe zones
if (!otherFaction.isNormal()) {
if (!otherFaction.isNormal())
{
return true;
}
// We only care about some material types.
if (otherFaction.hasPlayersOnline()){
if ( ! Conf.territoryProtectedMaterials.contains(material)) {
if (otherFaction.hasPlayersOnline())
{
if ( ! Conf.territoryProtectedMaterials.contains(material))
{
return true;
}
} else {
if ( ! Conf.territoryProtectedMaterialsWhenOffline.contains(material)) {
}
else
{
if ( ! Conf.territoryProtectedMaterialsWhenOffline.contains(material))
{
return true;
}
}
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
Faction myFaction = me.getFaction();
Relation rel = myFaction.getRelation(otherFaction);
boolean ownershipFail = Conf.ownedAreasEnabled && Conf.ownedAreaProtectMaterials && !otherFaction.playerHasOwnershipRights(me, loc);
// You may use any block unless it is another faction's territory...
if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials)) {
if (!justCheck) {
if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials))
{
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in the territory of "+otherFaction.getTag(myFaction));
}
return false;
}
// Also cancel if player doesn't have ownership rights for this claim
else if (rel.isMember() && ownershipFail && !Factions.hasPermOwnershipBypass(player)) {
if (!justCheck) {
else if (rel.isMember() && ownershipFail && !P.hasPermOwnershipBypass(player))
{
if (!justCheck)
{
me.sendMessage("You can't use "+TextUtil.getMaterialName(material)+" in this territory, it is owned by: "+myFaction.getOwnerListString(loc));
}
return false;
@ -398,12 +482,25 @@ public class FactionsPlayerListener extends PlayerListener{
}
@Override
public void onPlayerRespawn(PlayerRespawnEvent event) {
FPlayer me = FPlayer.get(event.getPlayer());
public void onPlayerRespawn(PlayerRespawnEvent event)
{
FPlayer me = FPlayers.i.get(event.getPlayer());
Location home = me.getFaction().getHome();
if ( Conf.homesEnabled && Conf.homesTeleportToOnDeath && home != null &&
(Conf.homesRespawnFromNoPowerLossWorlds || !Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()))
) {
if
(
Conf.homesEnabled
&&
Conf.homesTeleportToOnDeath
&&
home != null
&&
(
Conf.homesRespawnFromNoPowerLossWorlds
||
! Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName())
)
)
{
event.setRespawnLocation(home);
}
}
@ -411,100 +508,118 @@ public class FactionsPlayerListener extends PlayerListener{
// For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected),
// but these separate bucket events below always fire without fail
@Override
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
if (event.isCancelled()) return;
Block block = event.getBlockClicked();
Player player = event.getPlayer();
if ( ! this.playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) {
if ( ! playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false))
{
event.setCancelled(true);
return;
}
}
@Override
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerBucketFill(PlayerBucketFillEvent event)
{
if (event.isCancelled()) return;
Block block = event.getBlockClicked();
Player player = event.getPlayer();
if ( ! this.playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) {
if ( ! playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false))
{
event.setCancelled(true);
return;
}
}
@Override
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
if (event.isCancelled()) return;
if (preventCommand(event.getMessage().toLowerCase(), event.getPlayer())) {
if (preventCommand(event.getMessage().toLowerCase(), event.getPlayer()))
{
event.setCancelled(true);
}
}
public static boolean preventCommand(String fullCmd, Player player) {
if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty())) {
public static boolean preventCommand(String fullCmd, Player player)
{
if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty()))
{
return false;
}
FPlayer me = FPlayer.get(player);
FPlayer me = FPlayers.i.get(player);
if (!me.isInOthersTerritory()) {
if (!me.isInOthersTerritory())
{
return false;
}
Relation rel = me.getRelationToLocation();
if (rel.isAtLeast(Relation.ALLY)) {
if (rel.isAtLeast(Relation.ALLY))
{
return false;
}
String shortCmd = fullCmd.substring(1); // Get rid of the slash at the beginning
if (
if
(
rel.isNeutral()
&& !Conf.territoryNeutralDenyCommands.isEmpty()
&& !Conf.adminBypassPlayers.contains(me.getName())
) {
&&
! Conf.territoryNeutralDenyCommands.isEmpty()
&&
! Conf.adminBypassPlayers.contains(me.getName())
)
{
Iterator<String> iter = Conf.territoryNeutralDenyCommands.iterator();
String cmdCheck;
while (iter.hasNext()) {
while (iter.hasNext())
{
cmdCheck = iter.next();
if (cmdCheck == null) {
if (cmdCheck == null)
{
iter.remove();
continue;
}
cmdCheck = cmdCheck.toLowerCase();
if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) {
if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck))
{
me.sendMessage("You can't use the command \""+fullCmd+"\" in neutral territory.");
return true;
}
}
}
else if (
else if
(
rel.isEnemy()
&& !Conf.territoryEnemyDenyCommands.isEmpty()
&& !Conf.adminBypassPlayers.contains(me.getName())
) {
&&
! Conf.territoryEnemyDenyCommands.isEmpty()
&&
! Conf.adminBypassPlayers.contains(me.getName())
)
{
Iterator<String> iter = Conf.territoryEnemyDenyCommands.iterator();
String cmdCheck;
while (iter.hasNext()) {
while (iter.hasNext())
{
cmdCheck = iter.next();
if (cmdCheck == null) {
if (cmdCheck == null)
{
iter.remove();
continue;
}
cmdCheck = cmdCheck.toLowerCase();
if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) {
if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck))
{
me.sendMessage("You can't use the command \""+fullCmd+"\" in enemy territory.");
return true;
}
@ -514,20 +629,21 @@ public class FactionsPlayerListener extends PlayerListener{
}
@Override
public void onPlayerKick(PlayerKickEvent event) {
if (event.isCancelled()) {
return;
}
public void onPlayerKick(PlayerKickEvent event)
{
if (event.isCancelled()) return;
FPlayer badGuy = FPlayer.get(event.getPlayer());
if (badGuy == null) {
FPlayer badGuy = FPlayers.i.get(event.getPlayer());
if (badGuy == null)
{
return;
}
SpoutFeatures.playerDisconnect(badGuy);
// if player was banned (not just kicked), get rid of their stored info
if (event.getReason().equals("Banned by admin.")) {
if (event.getReason().equals("Banned by admin."))
{
badGuy.leave(false);
badGuy.markForDeletion(true);
}

View File

@ -5,42 +5,60 @@ import org.bukkit.event.server.ServerListener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import com.massivecraft.factions.P;
import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.integration.SpoutFeatures;
public class FactionsServerListener extends ServerListener {
public class FactionsServerListener extends ServerListener
{
public P p;
public FactionsServerListener(P p)
{
this.p = p;
}
@Override
public void onPluginDisable(PluginDisableEvent event) {
public void onPluginDisable(PluginDisableEvent event)
{
String name = event.getPlugin().getDescription().getName();
if (Econ.registerHooked() && name.equals("Register")) {
if (Econ.registerHooked() && name.equals("Register"))
{
Econ.registerSet(false);
}
else if (Econ.iConomyHooked() && name.equals("iConomy")) {
else if (Econ.iConomyHooked() && name.equals("iConomy"))
{
Econ.iConomySet(false);
}
else if (Econ.essentialsEcoHooked() && name.equals("Essentials")) {
else if (Econ.essentialsEcoHooked() && name.equals("Essentials"))
{
Econ.essentialsEcoSet(false);
}
else if (name.equals("Spout")) {
else if (name.equals("Spout"))
{
SpoutFeatures.setAvailable(false, "");
}
}
@Override
public void onPluginEnable(PluginEnableEvent event) {
public void onPluginEnable(PluginEnableEvent event)
{
Plugin plug = event.getPlugin();
String name = plug.getDescription().getName();
if (!Econ.registerHooked() && name.equals("Register") && plug.getClass().getName().equals("com.nijikokun.register.Register")) {
if ( ! Econ.registerHooked() && name.equals("Register") && plug.getClass().getName().equals("com.nijikokun.register.Register"))
{
Econ.registerSet(true);
}
else if (!Econ.iConomyHooked() && name.equals("iConomy") && plug.getClass().getName().equals("com.iConomy.iConomy")) {
else if ( ! Econ.iConomyHooked() && name.equals("iConomy") && plug.getClass().getName().equals("com.iConomy.iConomy"))
{
Econ.iConomySet(true);
}
else if (!Econ.essentialsEcoHooked() && name.equals("Essentials")) {
else if ( ! Econ.essentialsEcoHooked() && name.equals("Essentials"))
{
Econ.essentialsEcoSet(true);
}
else if (name.equals("Spout")) {
else if (name.equals("Spout"))
{
SpoutFeatures.setAvailable(true, plug.getDescription().getFullName());
}
}

View File

@ -5,7 +5,8 @@ import org.bukkit.ChatColor;
import com.massivecraft.factions.Conf;
public enum Relation {
public enum Relation
{
MEMBER(3, "member"),
ALLY(2, "ally"),
NEUTRAL(1, "neutral"),
@ -20,107 +21,145 @@ public enum Relation {
}
@Override
public String toString() {
public String toString()
{
return this.nicename;
}
public boolean isMember() {
// TODO: Insane way to use enums!!!?
public boolean isMember()
{
return this.value == MEMBER.value;
}
public boolean isAlly() {
public boolean isAlly()
{
return this.value == ALLY.value;
}
public boolean isNeutral() {
public boolean isNeutral()
{
return this.value == NEUTRAL.value;
}
public boolean isEnemy() {
public boolean isEnemy()
{
return this.value == ENEMY.value;
}
public boolean isAtLeast(Relation relation) {
public boolean isAtLeast(Relation relation)
{
return this.value >= relation.value;
}
public boolean isAtMost(Relation relation) {
public boolean isAtMost(Relation relation)
{
return this.value <= relation.value;
}
public ChatColor getColor() {
if (this.value == MEMBER.value) {
public ChatColor getColor()
{
if (this.value == MEMBER.value)
{
return Conf.colorMember;
} else if (this.value == ALLY.value) {
}
else if (this.value == ALLY.value)
{
return Conf.colorAlly;
} else if (this.value == NEUTRAL.value) {
}
else if (this.value == NEUTRAL.value)
{
return Conf.colorNeutral;
} else {
}
else
{
return Conf.colorEnemy;
}
}
// return appropriate Conf setting for DenyBuild based on this relation and their online status
public boolean confDenyBuild(boolean online) {
if (online) {
if (isEnemy()) {
public boolean confDenyBuild(boolean online)
{
if (online)
{
if (isEnemy())
{
return Conf.territoryEnemyDenyBuild;
}
else if (isAlly()) {
else if (isAlly())
{
return Conf.territoryAllyDenyBuild;
}
else {
else
{
return Conf.territoryDenyBuild;
}
}
else {
if (isEnemy()) {
else
{
if (isEnemy())
{
return Conf.territoryEnemyDenyBuildWhenOffline;
}
else if (isAlly()) {
else if (isAlly())
{
return Conf.territoryAllyDenyBuildWhenOffline;
}
else {
else
{
return Conf.territoryDenyBuildWhenOffline;
}
}
}
// return appropriate Conf setting for PainBuild based on this relation and their online status
public boolean confPainBuild(boolean online) {
if (online) {
if (isEnemy()) {
public boolean confPainBuild(boolean online)
{
if (online)
{
if (isEnemy())
{
return Conf.territoryEnemyPainBuild;
}
else if (isAlly()) {
else if (isAlly())
{
return Conf.territoryAllyPainBuild;
}
else {
else
{
return Conf.territoryPainBuild;
}
}
else {
if (isEnemy()) {
else
{
if (isEnemy())
{
return Conf.territoryEnemyPainBuildWhenOffline;
}
else if (isAlly()) {
else if (isAlly())
{
return Conf.territoryAllyPainBuildWhenOffline;
}
else {
else
{
return Conf.territoryPainBuildWhenOffline;
}
}
}
// return appropriate Conf setting for DenyUseage based on this relation
public boolean confDenyUseage() {
if (isEnemy()) {
public boolean confDenyUseage()
{
if (isEnemy())
{
return Conf.territoryEnemyDenyUseage;
}
else if (isAlly()) {
else if (isAlly())
{
return Conf.territoryAllyDenyUseage;
}
else {
else
{
return Conf.territoryDenyUseage;
}
}

View File

@ -1,33 +0,0 @@
package com.massivecraft.factions.util;
import java.io.*;
/**
* Harddisc related methods such as read and write.
*/
public class DiscUtil {
/**
* Convenience function for writing a string to a file.
*/
public static void write(File file, String content) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
out.write(content);
out.close();
}
/**
* Convenience function for reading a file as a string.
*/
public static String read(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null) {
ret += line;
}
in.close();
return ret;
}
}

View File

@ -1,18 +0,0 @@
package com.massivecraft.factions.util;
import org.bukkit.entity.Creature;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
public class EntityUtil {
public static CreatureType creatureTypeFromEntity(Entity entity) {
if ( ! (entity instanceof Creature)) {
return null;
}
String name = entity.getClass().getSimpleName();
name = name.substring(5); // Remove "Craft"
return CreatureType.fromName(name);
}
}

View File

@ -1,59 +0,0 @@
package com.massivecraft.factions.util;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JarLoader {
private static URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
public static boolean load(String filename) {
return load(new File(filename));
}
public static boolean load(File file) {
if ( ! file.exists()) {
log("This file does not exist: " + file);
return false;
}
try {
return load(file.toURI().toURL());
} catch (MalformedURLException e) {
log("The url for \""+file+"\" was malformed." + e);
return false;
}
}
public static boolean load(URL url) {
// If the file already is loaded we can skip it
for (URL otherUrl : sysloader.getURLs()) {
if (otherUrl.sameFile(url)) {
return true;
}
}
try {
Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class });
addURLMethod.setAccessible(true);
addURLMethod.invoke(sysloader, new Object[]{ url });
return true;
} catch (Exception e) {
log("Failed to load \""+url+"\":" + e);
return false;
}
}
// -------------------------------------------- //
// Logger
// -------------------------------------------- //
private static void log(Object o) {
Logger.getLogger("Minecraft").log(Level.SEVERE, "[JAR-LOADER] " + o);
}
}

View File

@ -19,16 +19,19 @@ import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLocation, Set<String>>>, JsonSerializer<Map<FLocation, Set<String>>> {
public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLocation, Set<String>>>, JsonSerializer<Map<FLocation, Set<String>>>
{
@Override
public Map<FLocation, Set<String>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
public Map<FLocation, Set<String>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
try {
JsonObject obj = json.getAsJsonObject();
if (obj == null) {
if (obj == null)
{
return null;
}
@ -39,16 +42,19 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
String[] coords;
int x, z;
for (Entry<String, JsonElement> entry : obj.entrySet()) {
for (Entry<String, JsonElement> entry : obj.entrySet())
{
worldName = entry.getKey();
for (Entry<String, JsonElement> entry2 : entry.getValue().getAsJsonObject().entrySet()) {
for (Entry<String, JsonElement> entry2 : entry.getValue().getAsJsonObject().entrySet())
{
coords = entry2.getKey().trim().split("[,\\s]+");
x = Integer.parseInt(coords[0]);
z = Integer.parseInt(coords[1]);
nameSet = new HashSet<String>();
iter = entry2.getValue().getAsJsonArray().iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
nameSet.add(iter.next().getAsString());
}
@ -58,19 +64,23 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
return locationMap;
} catch (Exception ex) {
}
catch (Exception ex)
{
ex.printStackTrace();
Factions.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets.");
P.p.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets.");
return null;
}
}
@Override
public JsonElement serialize(Map<FLocation, Set<String>> src, Type typeOfSrc, JsonSerializationContext context) {
public JsonElement serialize(Map<FLocation, Set<String>> src, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject obj = new JsonObject();
try {
if (src != null) {
if (src != null)
{
FLocation loc;
String locWorld;
Set<String> nameSet;
@ -78,23 +88,27 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
JsonArray nameArray;
JsonPrimitive nameElement;
for (Entry<FLocation, Set<String>> entry : src.entrySet()) {
for (Entry<FLocation, Set<String>> entry : src.entrySet())
{
loc = entry.getKey();
locWorld = loc.getWorldName();
nameSet = entry.getValue();
if (nameSet == null || nameSet.isEmpty()) {
if (nameSet == null || nameSet.isEmpty())
{
continue;
}
nameArray = new JsonArray();
iter = nameSet.iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
nameElement = new JsonPrimitive(iter.next());
nameArray.add(nameElement);
}
if ( ! obj.has(locWorld)) {
if ( ! obj.has(locWorld))
{
obj.add(locWorld, new JsonObject());
}
@ -103,9 +117,11 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
}
return obj;
} catch (Exception ex) {
}
catch (Exception ex)
{
ex.printStackTrace();
Factions.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets.");
P.p.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets.");
return obj;
}
}

View File

@ -1,6 +1,27 @@
package com.massivecraft.factions.util;
public class MiscUtil {
import java.util.Arrays;
import java.util.HashSet;
import org.bukkit.entity.Creature;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
public class MiscUtil
{
public static CreatureType creatureTypeFromEntity(Entity entity)
{
if ( ! (entity instanceof Creature))
{
return null;
}
String name = entity.getClass().getSimpleName();
name = name.substring(5); // Remove "Craft"
return CreatureType.fromName(name);
}
// Inclusive range
public static long[] range(long start, long end) {
@ -12,8 +33,6 @@ public class MiscUtil {
end = oldstart;
}
for (long i = start; i <= end; i++) {
values[(int) (i - start)] = i;
}
@ -21,5 +40,27 @@ public class MiscUtil {
return values;
}
/// TODO create tag whitelist!!
public static HashSet<String> substanceChars = new HashSet<String>(Arrays.asList(new String []{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z"
}));
public static String getComparisonString(String str)
{
String ret = "";
for (char c : str.toCharArray())
{
if (substanceChars.contains(String.valueOf(c)))
{
ret += c;
}
}
return ret.toLowerCase();
}
}

View File

@ -13,10 +13,11 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSerializer<Location> {
public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSerializer<Location>
{
private static final String WORLD = "world";
private static final String X = "x";
private static final String Y = "y";
@ -25,14 +26,16 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
private static final String PITCH = "pitch";
@Override
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
try
{
JsonObject obj = json.getAsJsonObject();
String worldname = obj.get(WORLD).getAsString();
World world = Factions.instance.getServer().getWorld(worldname);
World world = P.p.getServer().getWorld(worldname);
if (world == null) {
Factions.log(Level.WARNING, "Stored location's world \"" + worldname + "\" not found on server; dropping the location.");
P.p.log(Level.WARNING, "Stored location's world \"" + worldname + "\" not found on server; dropping the location.");
return null;
}
@ -44,9 +47,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
return new Location(world, x, y, z, yaw, pitch);
} catch (Exception ex) {
}
catch (Exception ex)
{
ex.printStackTrace();
Factions.log(Level.WARNING, "Error encountered while deserializing a location.");
P.p.log(Level.WARNING, "Error encountered while deserializing a location.");
return null;
}
}
@ -55,10 +60,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
try {
try
{
if (src.getWorld() == null)
{
Factions.log(Level.WARNING, "Passed location's world was not found on the server. Dropping the location.");
P.p.log(Level.WARNING, "Passed location's world was not found on the server. Dropping the location.");
return obj;
}
@ -71,9 +77,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
return obj;
} catch (Exception ex) {
}
catch (Exception ex)
{
ex.printStackTrace();
Factions.log(Level.WARNING, "Error encountered while serializing a location.");
P.p.log(Level.WARNING, "Error encountered while serializing a location.");
return obj;
}
}

View File

@ -1,88 +0,0 @@
package com.massivecraft.factions.util;
import java.util.*;
import org.bukkit.Material;
import com.massivecraft.factions.Conf;
public class TextUtil {
public static String titleize(String str) {
String line = Conf.colorChrome+repeat("_", 60);
String center = ".[ " + Conf.colorSystem + str + Conf.colorChrome + " ].";
int pivot = line.length() / 2;
int eatLeft = center.length() / 2;
int eatRight = center.length() - eatLeft;
if (eatLeft < pivot)
return line.substring(0, pivot - eatLeft) + center + line.substring(pivot + eatRight);
else
return center;
}
public static String repeat(String s, int times) {
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
public static ArrayList<String> split(String str) {
return new ArrayList<String>(Arrays.asList(str.trim().split("\\s+")));
}
public static String implode(List<String> list, String glue) {
String ret = "";
for (int i=0; i<list.size(); i++) {
if (i!=0) {
ret += glue;
}
ret += list.get(i);
}
return ret;
}
public static String implode(List<String> list) {
return implode(list, " ");
}
/*public static String commandHelp(List<String> aliases, String param, String desc) {
ArrayList<String> parts = new ArrayList<String>();
parts.add(Conf.colorCommand+Conf.aliasBase.get(0));
parts.add(TextUtil.implode(aliases, ", "));
if (param.length() > 0) {
parts.add(Conf.colorParameter+param);
}
if (desc.length() > 0) {
parts.add(Conf.colorSystem+desc);
}
//Log.debug(TextUtil.implode(parts, " "));
return TextUtil.implode(parts, " ");
}*/
public static String getMaterialName(Material material) {
String ret = material.toString();
ret = ret.replace('_', ' ');
ret = ret.toLowerCase();
return ret.substring(0, 1).toUpperCase()+ret.substring(1);
}
/// TODO create tag whitelist!!
public static HashSet<String> substanceChars = new HashSet<String>(Arrays.asList(new String []{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z"
}));
public static String getComparisonString(String str) {
String ret = "";
for (char c : str.toCharArray()) {
if (substanceChars.contains(String.valueOf(c))) {
ret += c;
}
}
return ret.toLowerCase();
}
}

View File

@ -0,0 +1,9 @@
package com.massivecraft.factions.zcore;
public enum CommandVisibility
{
VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type.
SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands.
INVISIBLE, // Invisible commands are invisible to everyone, even those who can use the command.
;
}

View File

@ -0,0 +1,429 @@
package com.massivecraft.factions.zcore;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.massivecraft.factions.zcore.MCommand;
import com.massivecraft.factions.zcore.MPlugin;
import com.massivecraft.factions.zcore.util.TextUtil;
public abstract class MCommand<T extends MPlugin>
{
public T p;
// The sub-commands to this command
public List<MCommand<?>> subCommands;
// The different names this commands will react to
public List<String> aliases;
public boolean allowNoSlashAccess;
// Information on the args
public List<String> requiredArgs;
public LinkedHashMap<String, String> optionalArgs;
// Help info
public String helpShort;
public List<String> helpLong;
public CommandVisibility visibility;
// Some information on permissions
public boolean senderMustBePlayer;
public String permission;
// Information available on execution of the command
public CommandSender sender; // Will always be set
public Player player; // Will only be set when the sender is a player
public List<String> args; // Will contain the arguments, or and empty list if there are none.
public List<MCommand<?>> commandChain; // The command chain used to execute this command
public MCommand(T p)
{
this.p = p;
this.permission = null;
this.allowNoSlashAccess = false;
this.subCommands = new ArrayList<MCommand<?>>();
this.aliases = new ArrayList<String>();
this.requiredArgs = new ArrayList<String>();
this.optionalArgs = new LinkedHashMap<String, String>();
this.helpShort = "*Default helpShort*";
this.helpLong = new ArrayList<String>();
this.visibility = CommandVisibility.VISIBLE;
}
// The commandChain is a list of the parent command chain used to get to this command.
public void execute(CommandSender sender, List<String> args, List<MCommand<?>> commandChain)
{
// Set the execution-time specific variables
this.sender = sender;
if (sender instanceof Player)
{
this.player = (Player)sender;
}
else
{
this.player = null;
}
this.args = args;
this.commandChain = commandChain;
// Is there a matching sub command?
if (args.size() > 0 )
{
for (MCommand<?> subCommand: this.subCommands)
{
if (subCommand.aliases.contains(args.get(0)))
{
args.remove(0);
commandChain.add(this);
subCommand.execute(sender, args, commandChain);
return;
}
}
}
if ( ! validCall(this.sender, this.args))
{
return;
}
perform();
}
public void execute(CommandSender sender, List<String> args)
{
execute(sender, args, new ArrayList<MCommand<?>>());
}
// This is where the command action is performed.
public abstract void perform();
// -------------------------------------------- //
// Call Validation
// -------------------------------------------- //
/**
* In this method we validate that all prerequisites to perform this command has been met.
*/
// TODO: There should be a boolean for silence
public boolean validCall(CommandSender sender, List<String> args)
{
if ( ! validSenderType(sender, true))
{
return false;
}
if ( ! validSenderPermissions(sender, true))
{
return false;
}
if ( ! validArgs(args, sender))
{
return false;
}
return true;
}
public boolean validSenderType(CommandSender sender, boolean informSenderIfNot)
{
if (this.senderMustBePlayer && ! (sender instanceof Player))
{
if (informSenderIfNot)
{
sender.sendMessage(p.txt.get("command.sender_must_me_player"));
}
return false;
}
return true;
}
public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot)
{
if (this.permission == null) return true;
return p.perm.has(sender, this.permission, informSenderIfNot);
}
public boolean validArgs(List<String> args, CommandSender sender)
{
if (args.size() < this.requiredArgs.size())
{
if (sender != null)
{
sender.sendMessage(p.txt.get("command.to_few_args"));
sender.sendMessage(this.getUseageTemplate());
}
return false;
}
if (args.size() > this.requiredArgs.size() + this.optionalArgs.size())
{
if (sender != null)
{
// Get the to many string slice
List<String> theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size());
sender.sendMessage(String.format(p.txt.get("command.to_many_args"), TextUtil.implode(theToMany, " ")));
sender.sendMessage(this.getUseageTemplate());
}
return false;
}
return true;
}
public boolean validArgs(List<String> args)
{
return this.validArgs(args, null);
}
// -------------------------------------------- //
// Help and Usage information
// -------------------------------------------- //
public String getUseageTemplate(List<MCommand<?>> commandChain, boolean addShortHelp)
{
StringBuilder ret = new StringBuilder();
ret.append(p.txt.tags("<c>"));
ret.append('/');
for (MCommand<?> mc : commandChain)
{
ret.append(TextUtil.implode(mc.aliases, ","));
ret.append(' ');
}
ret.append(TextUtil.implode(this.aliases, ","));
List<String> args = new ArrayList<String>();
for (String requiredArg : this.requiredArgs)
{
args.add("<"+requiredArg+">");
}
for (Entry<String, String> optionalArg : this.optionalArgs.entrySet())
{
String val = optionalArg.getValue();
if (val == null)
{
val = "";
}
else
{
val = "="+val;
}
args.add("["+optionalArg.getKey()+val+"]");
}
if (args.size() > 0)
{
ret.append(p.txt.tags("<p> "));
ret.append(TextUtil.implode(args, " "));
}
if (addShortHelp)
{
ret.append(p.txt.tags(" <i>"));
ret.append(this.helpShort);
}
return ret.toString();
}
public String getUseageTemplate(boolean addShortHelp)
{
return getUseageTemplate(this.commandChain, addShortHelp);
}
public String getUseageTemplate()
{
return getUseageTemplate(false);
}
// -------------------------------------------- //
// Message Sending Helpers
// -------------------------------------------- //
public void msg(String msg, boolean parseColors)
{
if (parseColors)
{
sender.sendMessage(p.txt.tags(msg));
return;
}
sender.sendMessage(msg);
}
public void msg(String msg)
{
this.msg(msg, false);
}
public void msg(List<String> msgs, boolean parseColors)
{
for(String msg : msgs)
{
this.msg(msg, parseColors);
}
}
public void msg(List<String> msgs)
{
msg(msgs, false);
}
// -------------------------------------------- //
// Argument Readers
// -------------------------------------------- //
// STRING
public String argAsString(int idx, String def)
{
if (this.args.size() < idx+1)
{
return def;
}
return this.args.get(idx);
}
public String argAsString(int idx)
{
return this.argAsString(idx, null);
}
// INT
public int argAsInt(int idx, int def)
{
String str = this.argAsString(idx);
if (str == null) return def;
try
{
int ret = Integer.parseInt(str);
return ret;
}
catch (Exception e)
{
return def;
}
}
public int argAsInt(int idx)
{
return this.argAsInt(idx, -1);
}
// Double
public double argAsDouble(int idx, double def)
{
String str = this.argAsString(idx);
if (str == null) return def;
try
{
double ret = Double.parseDouble(str);
return ret;
}
catch (Exception e)
{
return def;
}
}
public double argAsDouble(int idx)
{
return this.argAsDouble(idx, -1d);
}
// Boolean
public boolean argAsBool(int idx, boolean def)
{
String str = this.argAsString(idx);
if (str == null) return def;
str = str.toLowerCase();
if (str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1"))
{
return true;
}
return false;
}
public boolean argAsBool(int idx)
{
return this.argAsBool(idx, false);
}
// PLAYER
public Player argAsPlayer(int idx, Player def, boolean msg)
{
Player ret = def;
String name = this.argAsString(idx);
if (name != null)
{
Player player = Bukkit.getServer().getPlayer(name);
if (player != null)
{
ret = player;
}
}
if (msg && ret == null)
{
// TODO: Fix this injection risk!
this.msg(p.txt.tags("<b>The player \"<p>"+name+"<b>\" could not be found."));
}
return ret;
}
public Player argAsPlayer(int idx, Player def)
{
return this.argAsPlayer(idx, def, true);
}
public Player argAsPlayer(int idx)
{
return this.argAsPlayer(idx, null);
}
// BEST PLAYER MATCH
public Player argAsBestPlayerMatch(int idx, Player def, boolean msg)
{
Player ret = def;
String name = this.argAsString(idx);
if (name != null)
{
List<Player> players = Bukkit.getServer().matchPlayer(name);
if (players.size() > 0)
{
ret = players.get(0);
}
}
if (msg && ret == null)
{
// TODO: Fix this injection risk!
this.msg(p.txt.tags("<b>No player match found for \"<p>"+name+"<b>\"."));
}
return ret;
}
public Player argAsBestPlayerMatch(int idx, Player def)
{
return this.argAsBestPlayerMatch(idx, def, true);
}
public Player argAsBestPlayerMatch(int idx)
{
return this.argAsPlayer(idx, null);
}
}

View File

@ -0,0 +1,236 @@
package com.massivecraft.factions.zcore;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.massivecraft.factions.zcore.persist.EM;
import com.massivecraft.factions.zcore.persist.SaveTask;
import com.massivecraft.factions.zcore.util.LibLoader;
import com.massivecraft.factions.zcore.util.PermUtil;
import com.massivecraft.factions.zcore.util.Persist;
import com.massivecraft.factions.zcore.util.TextUtil;
public abstract class MPlugin extends JavaPlugin
{
// Some utils
public Persist persist;
public TextUtil txt;
public LibLoader lib;
public PermUtil perm;
// Persist related
public Gson gson;
private Integer saveTask = null;
// Listeners
private MPluginSecretPlayerListener mPluginSecretPlayerListener;
private MPluginSecretServerListener mPluginSecretServerListener;
// Our stored base commands
private List<MCommand<?>> baseCommands = new ArrayList<MCommand<?>>();
public List<MCommand<?>> getBaseCommands() { return this.baseCommands; }
// -------------------------------------------- //
// ENABLE
// -------------------------------------------- //
private long timeEnableStart;
public boolean preEnable()
{
log("=== ENABLE START ===");
timeEnableStart = System.currentTimeMillis();
// Ensure basefolder exists!
this.getDataFolder().mkdirs();
// Create Utility Instances
this.perm = new PermUtil(this);
this.persist = new Persist(this);
this.lib = new LibLoader(this);
if ( ! lib.require("gson.jar", "http://search.maven.org/remotecontent?filepath=com/google/code/gson/gson/1.7.1/gson-1.7.1.jar")) return false;
this.gson = this.getGsonBuilder().create();
initTXT();
// Create and register listeners
this.mPluginSecretPlayerListener = new MPluginSecretPlayerListener(this);
this.mPluginSecretServerListener = new MPluginSecretServerListener(this);
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_PRELOGIN, this.mPluginSecretPlayerListener, Event.Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, this.mPluginSecretPlayerListener, Event.Priority.Low, this);
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, this.mPluginSecretPlayerListener, Event.Priority.Lowest, this);
pm.registerEvent(Event.Type.SERVER_COMMAND, this.mPluginSecretServerListener, Event.Priority.Lowest, this);
// Register recurring tasks
long saveTicks = 20 * 60 * 30; // Approximately every 30 min
if (saveTask == null)
{
saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(), saveTicks, saveTicks);
}
return true;
}
public void postEnable()
{
log("=== ENABLE DONE (Took "+(System.currentTimeMillis()-timeEnableStart)+"ms) ===");
}
public void onDisable()
{
if (saveTask != null)
{
this.getServer().getScheduler().cancelTask(saveTask);
saveTask = null;
}
EM.saveAllToDisc();
log("Disabled");
}
public void suicide()
{
log("Now I suicide!");
this.getServer().getPluginManager().disablePlugin(this);
}
// -------------------------------------------- //
// Some inits...
// You are supposed to override these in the plugin if you aren't satisfied with the defaults
// The goal is that you always will be satisfied though.
// -------------------------------------------- //
public GsonBuilder getGsonBuilder()
{
return new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.serializeNulls()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE);
}
// -------------------------------------------- //
// LANG AND TAGS
// -------------------------------------------- //
// These are not supposed to be used directly.
// They are loaded and used through the TextUtil instance for the plugin.
public Map<String, String> tags = new LinkedHashMap<String, String>();
public Map<String, String> lang = new LinkedHashMap<String, String>();
public void addLang()
{
this.lang.put("perm.forbidden", "<b>You don't have permission to %s.");
this.lang.put("perm.dothat", "do that");
this.lang.put("command.sender_must_me_player", "<b>This command can only be used by ingame players.");
this.lang.put("command.to_few_args", "<b>To few arguments. <i>Use like this:");
this.lang.put("command.to_many_args", "<b>Strange argument \"<p>%s<b>\". <i>Use the command like this:");
}
public void addTags()
{
this.tags.put("black", "§0");
this.tags.put("navy", "§1");
this.tags.put("green", "§2");
this.tags.put("teal", "§3");
this.tags.put("red", "§4");
this.tags.put("purple", "§5");
this.tags.put("gold", "§6");
this.tags.put("silver", "§7");
this.tags.put("gray", "§8");
this.tags.put("blue", "§9");
this.tags.put("white", "§f");
this.tags.put("lime", "§a");
this.tags.put("aqua", "§b");
this.tags.put("rose", "§c");
this.tags.put("pink", "§d");
this.tags.put("yellow", "§e");
this.tags.put("l", "§2"); // logo
this.tags.put("a", "§6"); // art
this.tags.put("n", "§7"); // notice
this.tags.put("i", "§e"); // info
this.tags.put("g", "§a"); // good
this.tags.put("b", "§c"); // bad
this.tags.put("h", "§d"); // highligh
this.tags.put("c", "§b"); // command
this.tags.put("p", "§3"); // parameter
}
public void initTXT()
{
this.addLang();
this.addTags();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> langFromFile = this.persist.load(type, "lang");
if (langFromFile != null) this.lang.putAll(langFromFile);
this.persist.save(this.lang, "lang");
Map<String, String> tagsFromFile = this.persist.load(type, "tags");
if (tagsFromFile != null) this.tags.putAll(tagsFromFile);
this.persist.save(this.tags, "tags");
this.txt = new TextUtil(this.tags, this.lang);
}
// -------------------------------------------- //
// COMMAND HANDLING
// -------------------------------------------- //
public boolean handleCommand(CommandSender sender, String commandString)
{
boolean noSlash = false;
if (commandString.startsWith("/"))
{
noSlash = true;
commandString = commandString.substring(1);
}
for (MCommand<?> command : this.getBaseCommands())
{
if (noSlash && ! command.allowNoSlashAccess) continue;
for (String alias : command.aliases)
{
if (commandString.startsWith(alias) || commandString.equals(alias+" "))
{
List<String> args = new ArrayList<String>(Arrays.asList(commandString.split("\\s+")));
args.remove(0);
command.execute(sender, args);
return true;
}
}
}
return false;
}
// -------------------------------------------- //
// LOGGING
// -------------------------------------------- //
public void log(Object msg)
{
log(Level.INFO, msg);
}
public void log(Level level, Object msg)
{
Logger.getLogger("Minecraft").log(level, "["+this.getDescription().getFullName()+"] "+msg);
}
}

View File

@ -0,0 +1,55 @@
package com.massivecraft.factions.zcore;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerPreLoginEvent;
import com.massivecraft.factions.zcore.persist.EM;
import com.massivecraft.factions.zcore.persist.Entity;
import com.massivecraft.factions.zcore.persist.EntityCollection;
import com.massivecraft.factions.zcore.persist.PlayerEntityCollection;
public class MPluginSecretPlayerListener extends PlayerListener
{
private MPlugin p;
public MPluginSecretPlayerListener(MPlugin p)
{
this.p = p;
}
@Override
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
if (event.isCancelled()) return;
if (p.handleCommand(event.getPlayer(), event.getMessage()))
{
event.setCancelled(true);
}
}
@Override
public void onPlayerChat(PlayerChatEvent event)
{
if (event.isCancelled()) return;
if (p.handleCommand(event.getPlayer(), event.getMessage()))
{
event.setCancelled(true);
}
}
@Override
public void onPlayerPreLogin(PlayerPreLoginEvent event)
{
for (EntityCollection<? extends Entity> ecoll : EM.class2Entities.values())
{
if (ecoll instanceof PlayerEntityCollection)
{
ecoll.get(event.getName());
}
}
}
}

View File

@ -0,0 +1,26 @@
package com.massivecraft.factions.zcore;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.server.ServerListener;
public class MPluginSecretServerListener extends ServerListener
{
private MPlugin p;
public MPluginSecretServerListener(MPlugin p)
{
this.p = p;
}
// This method is not perfect. It says unknown console command.
@Override
public void onServerCommand(ServerCommandEvent event)
{
if (event.getCommand().length() == 0) return;
if (p.handleCommand(event.getSender(), event.getCommand()))
{
event.setCommand("");
}
}
}

View File

@ -0,0 +1,74 @@
package com.massivecraft.factions.zcore.persist;
import java.util.*;
import com.massivecraft.factions.zcore.persist.Entity;
import com.massivecraft.factions.zcore.persist.EntityCollection;
public class EM
{
public static Map<Class<? extends Entity>, EntityCollection<? extends Entity>> class2Entities = new LinkedHashMap<Class<? extends Entity>, EntityCollection<? extends Entity>>();
@SuppressWarnings("unchecked")
public static <T extends Entity> EntityCollection<T> getEntitiesCollectionForEntityClass(Class<T> entityClass)
{
return (EntityCollection<T>) class2Entities.get(entityClass);
}
public static void setEntitiesCollectionForEntityClass(Class<? extends Entity> entityClass, EntityCollection<? extends Entity> entities)
{
class2Entities.put(entityClass, entities);
}
// -------------------------------------------- //
// ATTACH AND DETACH
// -------------------------------------------- //
@SuppressWarnings("unchecked")
public static <T extends Entity> void attach(T entity)
{
EntityCollection<T> ec = (EntityCollection<T>) getEntitiesCollectionForEntityClass(entity.getClass());
ec.attach(entity);
}
@SuppressWarnings("unchecked")
public static <T extends Entity> void detach(T entity)
{
EntityCollection<T> ec = (EntityCollection<T>) getEntitiesCollectionForEntityClass(entity.getClass());
ec.detach(entity);
}
@SuppressWarnings("unchecked")
public static <T extends Entity> boolean attached(T entity)
{
EntityCollection<T> ec = (EntityCollection<T>) getEntitiesCollectionForEntityClass(entity.getClass());
return ec.attached(entity);
}
@SuppressWarnings("unchecked")
public static <T extends Entity> boolean detached(T entity)
{
EntityCollection<T> ec = (EntityCollection<T>) getEntitiesCollectionForEntityClass(entity.getClass());
return ec.detached(entity);
}
// -------------------------------------------- //
// DISC
// -------------------------------------------- //
public static void saveAllToDisc()
{
for (EntityCollection<? extends Entity> ec : class2Entities.values())
{
ec.saveToDisc();
}
}
public static void loadAllFromDisc()
{
for (EntityCollection<? extends Entity> ec : class2Entities.values())
{
ec.loadFromDisc();
}
}
}

View File

@ -0,0 +1,65 @@
package com.massivecraft.factions.zcore.persist;
public abstract class Entity
{
public Entity()
{
}
protected transient String id = null;
public String getId()
{
return id;
}
protected void setId(String id)
{
this.id = id;
}
public boolean shouldBeSaved()
{
return true;
}
// -------------------------------------------- //
// ATTACH AND DETACH
// -------------------------------------------- //
public void attach()
{
EM.attach(this);
}
public void detach()
{
EM.detach(this);
}
public boolean attached()
{
return EM.attached(this);
}
public boolean detached()
{
return EM.detached(this);
}
// -------------------------------------------- //
// EVENTS
// -------------------------------------------- //
public void preDetach()
{
}
public void postDetach()
{
}
}

View File

@ -0,0 +1,250 @@
package com.massivecraft.factions.zcore.persist;
import java.io.File;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.massivecraft.factions.zcore.util.DiscUtil;
public abstract class EntityCollection<E extends Entity>
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
// These must be instantiated in order to allow for different configuration (orders, comparators etc)
private Collection<E> entities;
private Map<String, E> id2entity;
// If the entities are creative they will create a new instance if a non existent id was requested
private boolean creative;
public boolean isCreative() { return creative; }
public void setCreative(boolean creative) { this.creative = creative; }
// This is the auto increment for the primary key "id"
private int nextId;
// This ugly crap is necessary due to java type erasure
private Class<E> entityClass;
public abstract Type getMapType(); // This is special stuff for GSON.
// Info on how to persist
private Gson gson;
public Gson getGson() { return gson; }
public void setGson(Gson gson) { this.gson = gson; }
private File file;
public File getFile() { return file; }
public void setFile(File file) { this.file = file; }
// -------------------------------------------- //
// CONSTRUCTORS
// -------------------------------------------- //
public EntityCollection(Class<E> entityClass, Collection<E> entities, Map<String, E> id2entity, File file, Gson gson, boolean creative)
{
this.entityClass = entityClass;
this.entities = entities;
this.id2entity = id2entity;
this.file = file;
this.gson = gson;
this.creative = creative;
this.nextId = 1;
EM.setEntitiesCollectionForEntityClass(this.entityClass, this);
}
public EntityCollection(Class<E> entityClass, Collection<E> entities, Map<String, E> id2entity, File file, Gson gson)
{
this(entityClass, entities, id2entity, file, gson, false);
}
// -------------------------------------------- //
// GET
// -------------------------------------------- //
public Collection<E> get()
{
return entities;
}
public Map<String, E> getMap()
{
return this.id2entity;
}
public E get(String id)
{
if (this.creative) return this.getCreative(id);
return id2entity.get(id);
}
public E getCreative(String id)
{
E e = id2entity.get(id);
if (e != null) return e;
return this.create(id);
}
public boolean exists(String id)
{
return id2entity.get(id) != null;
}
// -------------------------------------------- //
// CREATE
// -------------------------------------------- //
public E create()
{
return this.create(this.getNextId());
}
public E create(String id)
{
if ( ! this.isIdFree(id)) return null;
E e = null;
try
{
e = this.entityClass.newInstance();
} catch (Exception ignored) {}
e.setId(id);
this.entities.add(e);
this.id2entity.put(e.getId(), e);
this.updateNextIdForId(id);
return e;
}
// -------------------------------------------- //
// ATTACH AND DETACH
// -------------------------------------------- //
public void attach(E entity)
{
if (entity.getId() != null) return;
entity.setId(this.getNextId());
this.entities.add(entity);
this.id2entity.put(entity.getId(), entity);
}
public void detach(E entity)
{
entity.preDetach();
this.entities.remove(entity);
this.id2entity.remove(entity.getId());
entity.postDetach();
}
public void detach(String id)
{
E entity = this.id2entity.get(id);
if (entity == null) return;
this.detach(entity);
}
public boolean attached(E entity)
{
return this.entities.contains(entity);
}
public boolean detached(E entity)
{
return ! this.attached(entity);
}
// -------------------------------------------- //
// DISC
// -------------------------------------------- //
public boolean saveToDisc()
{
Map<String, E> entitiesThatShouldBeSaved = new HashMap<String, E>();
for (E entity : this.entities)
{
if (entity.shouldBeSaved())
{
entitiesThatShouldBeSaved.put(entity.getId(), entity);
}
}
return this.saveCore(entitiesThatShouldBeSaved);
}
private boolean saveCore(Map<String, E> entities)
{
return DiscUtil.writeCatch(this.file, this.gson.toJson(entities));
}
public boolean loadFromDisc()
{
Map<String, E> id2entity = this.loadCore();
if (id2entity == null) return false;
this.entities.clear();
this.entities.addAll(id2entity.values());
this.id2entity.clear();
this.id2entity.putAll(id2entity);
this.fillIds();
return true;
}
private Map<String, E> loadCore()
{
if ( ! this.file.exists())
{
return new HashMap<String, E>();
}
String content = DiscUtil.readCatch(this.file);
if (content == null)
{
return null;
}
Type type = this.getMapType();
return this.gson.fromJson(content, type);
}
// -------------------------------------------- //
// ID MANAGEMENT
// -------------------------------------------- //
public String getNextId()
{
this.nextId += 1;
return "" + (nextId - 1);
}
public boolean isIdFree(String id)
{
return ! this.id2entity.containsKey(id);
}
protected void fillIds()
{
this.nextId = 1;
for(Entry<String, E> entry : this.id2entity.entrySet())
{
String id = entry.getKey();
E entity = entry.getValue();
entity.id = id;
this.updateNextIdForId(id);
}
}
protected void updateNextIdForId(String id)
{
try
{
int idAsInt = Integer.parseInt(id);
if (this.nextId < idAsInt)
{
this.nextId = idAsInt + 1;
}
} catch (Exception ignored) {}
}
}

View File

@ -0,0 +1,44 @@
package com.massivecraft.factions.zcore.persist;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class PlayerEntity extends Entity
{
public Player getPlayer()
{
return Bukkit.getPlayer(this.getId());
}
public boolean isOnline()
{
return this.getPlayer() != null;
}
public boolean isOffline()
{
return ! isOnline();
}
// -------------------------------------------- //
// Message Sending Helpers
// -------------------------------------------- //
public void sendMessage(String msg)
{
Player player = this.getPlayer();
if (player == null) return;
player.sendMessage(msg);
}
public void sendMessage(List<String> msgs)
{
for(String msg : msgs)
{
this.sendMessage(msg);
}
}
}

View File

@ -0,0 +1,46 @@
package com.massivecraft.factions.zcore.persist;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.google.gson.Gson;
/**
* The PlayerEntityCollection is an EntityCollection with the extra features
* a player skin usually requires.
*
* This entity collection is not only creative. It even creates the instance for the player
* when the player logs in to the server.
*
* This way we can be sure that PlayerEntityCollection.get() will contain
* all entities in PlayerEntityCollection.getOnline()
*/
public abstract class PlayerEntityCollection<E extends Entity> extends EntityCollection<E>
{
public PlayerEntityCollection(Class<E> entityClass, Collection<E> entities, Map<String, E> id2entity, File file, Gson gson)
{
super(entityClass, entities, id2entity, file, gson, true);
}
public E get(Player player)
{
return this.get(player.getName());
}
public Set<E> getOnline()
{
Set<E> entities = new HashSet<E>();
for (Player player : Bukkit.getServer().getOnlinePlayers())
{
entities.add(this.get(player));
}
return entities;
}
}

View File

@ -0,0 +1,9 @@
package com.massivecraft.factions.zcore.persist;
public class SaveTask implements Runnable
{
public void run()
{
EM.saveAllToDisc();
}
}

View File

@ -0,0 +1,51 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class ClassLoadHack {
private static URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
public static boolean load(String filename)
{
return load(new File(filename));
}
public static boolean load(File file)
{
try
{
return load(file.toURI().toURL());
}
catch (MalformedURLException e)
{
return false;
}
}
public static boolean load(URL url)
{
// If the file already is loaded we can skip it
for (URL otherUrl : sysloader.getURLs())
{
if (otherUrl.sameFile(url)) return true;
}
try
{
Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class });
addURLMethod.setAccessible(true);
addURLMethod.invoke(sysloader, new Object[]{ url });
return true;
}
catch (Exception e)
{
return false;
}
}
}

View File

@ -0,0 +1,78 @@
package com.massivecraft.factions.zcore.util;
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class DiscUtil
{
public static void write(File file, String content) throws IOException
{
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
out.write(content);
out.close();
}
public static String read(File file) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null)
{
ret += line;
}
in.close();
return ret;
}
public static boolean writeCatch(File file, String content)
{
try
{
write(file, content);
return true;
}
catch (Exception e)
{
return false;
}
}
public static String readCatch(File file)
{
try
{
return read(file);
}
catch (IOException e)
{
return null;
}
}
public static boolean downloadUrl(String urlstring, File file)
{
try
{
URL url = new URL(urlstring);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public static boolean downloadUrl(String urlstring, String filename)
{
return downloadUrl(urlstring, new File(filename));
}
}

View File

@ -0,0 +1,50 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import com.massivecraft.factions.zcore.MPlugin;
public class LibLoader
{
MPlugin p;
public LibLoader(MPlugin p)
{
this.p = p;
new File("./lib").mkdirs();
}
public boolean require(String filename, String url)
{
if ( ! include(filename, url))
{
p.log("Failed to load the required library "+filename);
p.suicide();
return false;
}
return true;
}
public boolean include (String filename, String url)
{
File file = getFile(filename);
if ( ! file.exists())
{
p.log("Downloading library "+filename);
if ( ! DiscUtil.downloadUrl(url, file))
{
p.log("Failed to download "+filename);
return false;
}
}
return ClassLoadHack.load(file);
}
private static File getFile(String filename)
{
return new File("./lib/"+filename);
}
}

View File

@ -0,0 +1,128 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import com.massivecraft.factions.zcore.MPlugin;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
public class PermUtil {
public PermissionManager pex = null;
public PermissionHandler perm2or3 = null;
public Map<String, String> permissionDescriptions = new HashMap<String, String>();
protected MPlugin p;
public PermUtil(MPlugin p)
{
this.p = p;
this.setup();
}
public String getForbiddenMessage(String perm)
{
return p.txt.get("perm.forbidden", getPermissionDescription(perm));
}
/**
* This method hooks into all permission plugins we are supporting
*/
public void setup()
{
for(Permission permission : p.getDescription().getPermissions())
{
this.permissionDescriptions.put(permission.getName(), permission.getDescription());
}
if ( Bukkit.getServer().getPluginManager().isPluginEnabled("PermissionsEx"))
{
pex = PermissionsEx.getPermissionManager();
p.log("Will use this plugin for permissions: " + Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx").getDescription().getFullName());
return;
}
if ( Bukkit.getServer().getPluginManager().isPluginEnabled("Permissions"))
{
Plugin permissionsPlugin = Bukkit.getServer().getPluginManager().getPlugin("Permissions");
perm2or3 = ((Permissions) permissionsPlugin).getHandler();
p.log("Will use this plugin for permissions: " + permissionsPlugin.getDescription().getFullName());
return;
}
p.log("No permission plugin detected. Defaulting to native bukkit permissions.");
}
public String getPermissionDescription (String perm)
{
String desc = permissionDescriptions.get(perm);
if (desc == null)
{
return p.txt.get("perm.dothat");
}
return desc;
}
/**
* This method tests if me has a certain permission and returns
* true if me has. Otherwise false
*/
public boolean has (CommandSender me, String perm)
{
if ( ! (me instanceof Player))
{
return me.hasPermission(perm);
}
if (pex != null)
{
return pex.has((Player)me, perm);
}
if (perm2or3 != null)
{
return perm2or3.has((Player)me, perm);
}
return me.hasPermission(perm);
}
public boolean has (CommandSender me, String perm, boolean informSenderIfNot)
{
if (has(me, perm))
{
return true;
}
else if (informSenderIfNot)
{
me.sendMessage(this.getForbiddenMessage(perm));
}
return false;
}
public <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val)
{
if (perm2val == null) return null;
T ret = null;
for ( Entry<String, T> entry : perm2val.entrySet())
{
ret = entry.getValue();
if (has(me, entry.getKey())) break;
}
return ret;
}
}

View File

@ -0,0 +1,154 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import java.lang.reflect.Type;
import java.util.logging.Level;
import com.massivecraft.factions.zcore.MPlugin;
// TODO: Give better name and place to differenciate from the entity-orm-ish system in "com.massivecraft.core.persist".
public class Persist {
private MPlugin p;
public Persist(MPlugin p)
{
this.p = p;
}
// ------------------------------------------------------------ //
// GET NAME - What should we call this type of object?
// ------------------------------------------------------------ //
public static String getName(Class<?> clazz)
{
return clazz.getSimpleName().toLowerCase();
}
public static String getName(Object o)
{
return getName(o.getClass());
}
public static String getName(Type type)
{
return getName(type.getClass());
}
// ------------------------------------------------------------ //
// GET FILE - In which file would we like to store this object?
// ------------------------------------------------------------ //
public File getFile(String name)
{
return new File(p.getDataFolder(), name+".json");
}
public File getFile(Class<?> clazz)
{
return getFile(getName(clazz));
}
public File getFile(Object obj)
{
return getFile(getName(obj));
}
public File getFile(Type type)
{
return getFile(getName(type));
}
// NICE WRAPPERS
public <T> T loadOrSaveDefault(T def, Class<T> clazz)
{
return loadOrSaveDefault(def, clazz, getFile(clazz));
}
public <T> T loadOrSaveDefault(T def, Class<T> clazz, String name)
{
return loadOrSaveDefault(def, clazz, getFile(name));
}
public <T> T loadOrSaveDefault(T def, Class<T> clazz, File file)
{
if ( ! file.exists())
{
p.log("Creating default: "+file);
this.save(def, file);
return def;
}
T loaded = this.load(clazz, file);
if (loaded == null)
{
p.log(Level.WARNING, "Using default as I failed to load: "+file);
return def;
}
return loaded;
}
// SAVE
public boolean save(Object instance)
{
return save(instance, getFile(instance));
}
public boolean save(Object instance, String name)
{
return save(instance, getFile(name));
}
public boolean save(Object instance, File file)
{
return DiscUtil.writeCatch(file, p.gson.toJson(instance));
}
// LOAD BY CLASS
public <T> T load(Class<T> clazz)
{
return load(clazz, getFile(clazz));
}
public <T> T load(Class<T> clazz, String name)
{
return load(clazz, getFile(name));
}
public <T> T load(Class<T> clazz, File file)
{
String content = DiscUtil.readCatch(file);
if (content == null)
{
return null;
}
T instance = p.gson.fromJson(content, clazz);
return instance;
}
// LOAD BY TYPE
public <T> T load(Type typeOfT, String name)
{
return load(typeOfT, getFile(name));
}
public <T> T load(Type typeOfT, File file)
{
String content = DiscUtil.readCatch(file);
if (content == null) {
return null;
}
return p.gson.fromJson(content, typeOfT);
}
}

View File

@ -0,0 +1,245 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Material;
public class TextUtil
{
private Map<String, String> tags = new HashMap<String, String>();
private Map<String, String> lang = new HashMap<String, String>();
public TextUtil(Map<String, String> tags, Map<String, String> lang)
{
if (tags != null)
{
this.tags.putAll(tags);
}
if (lang != null)
{
this.lang.putAll(lang);
}
}
// Get is supposed to be the way we reach registered lang
// TODO: Is the parse
public String get(String name)
{
String str = lang.get(name);
if (str == null) str = name;
return this.parse(str);
}
public String get(String name, Object... args)
{
String str = lang.get(name);
if (str == null) str = name;
return this.parse(str, args);
}
// Parse is used to handle non registered text
public String parse(String str, Object... args)
{
return String.format(this.tags(str), args);
}
public String parse(String str)
{
return this.tags(str);
}
public Map<String, String> getTags()
{
return tags;
}
public Map<String, String> getLang()
{
return lang;
}
public String tags(String str)
{
return replaceTags(str, this.tags);
}
public static final transient Pattern patternTag = Pattern.compile("<([^<>]*)>");
public static String replaceTags(String str, Map<String, String> tags)
{
StringBuffer ret = new StringBuffer();
Matcher matcher = patternTag.matcher(str);
while (matcher.find())
{
String tag = matcher.group(1);
String repl = tags.get(tag);
if (repl == null)
{
matcher.appendReplacement(ret, "<"+tag+">");
}
else
{
matcher.appendReplacement(ret, repl);
}
}
matcher.appendTail(ret);
return ret.toString();
}
public static String implode(List<String> list, String glue)
{
StringBuilder ret = new StringBuilder();
for (int i=0; i<list.size(); i++)
{
if (i!=0)
{
ret.append(glue);
}
ret.append(list.get(i));
}
return ret.toString();
}
public static String repeat(String s, int times)
{
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
public static String getMaterialName(Material material)
{
return material.toString().replace('_', ' ').toLowerCase();
}
public static String getMaterialName(int materialId)
{
return getMaterialName(Material.getMaterial(materialId));
}
public static String upperCaseFirst(String string)
{
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
// TODO: Make part of layout configuration.
private final static String titleizeLine = repeat("_", 52);
private final static int titleizeBalance = -1;
public String titleize(String str)
{
String center = ".[ "+ tags("<l>") + str + tags("<a>")+ " ].";
int centerlen = ChatColor.stripColor(center).length();
int pivot = titleizeLine.length() / 2;
int eatLeft = (centerlen / 2) - titleizeBalance;
int eatRight = (centerlen - eatLeft) + titleizeBalance;
if (eatLeft < pivot)
return tags("<a>")+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight);
else
return tags("<a>")+center;
}
public ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title)
{
ArrayList<String> ret = new ArrayList<String>();
int pageZeroBased = pageHumanBased - 1;
int pageheight = 9;
int pagecount = (lines.size() / pageheight)+1;
ret.add(this.titleize(title+" "+pageHumanBased+"/"+pagecount));
if (pagecount == 0)
{
ret.add(this.tags("<i>Sorry. No Pages available."));
return ret;
}
else if (pageZeroBased < 0 || pageHumanBased > pagecount)
{
ret.add(this.tags("<i>Invalid page. Must be between 1 and "+pagecount));
return ret;
}
int from = pageZeroBased * pageheight;
int to = from+pageheight;
if (to > lines.size())
{
to = lines.size();
}
ret.addAll(lines.subList(from, to));
return ret;
}
/**
* Using this function you transform a delta in milliseconds
* to a String like "2 weeks from now" or "7 days ago".
*/
public static final long millisPerSecond = 1000;
public static final long millisPerMinute = 60 * millisPerSecond;
public static final long millisPerHour = 60 * millisPerMinute;
public static final long millisPerDay = 24 * millisPerHour;
public static final long millisPerWeek = 7 * millisPerDay;
public static final long millisPerMonth = 31 * millisPerDay;
public static final long millisPerYear = 365 * millisPerDay;
public static String getTimeDeltaDescriptionRelNow(long millis)
{
double absmillis = (double) Math.abs(millis);
String agofromnow = "from now";
String unit;
long num;
if (millis <= 0)
{
agofromnow = "ago";
}
// We use a factor 3 below for a reason... why do you think?
// Answer: it is a way to make our round of error smaller.
if (absmillis < 3 * millisPerSecond)
{
unit = "milliseconds";
num = (long) (absmillis);
}
else if (absmillis < 3 * millisPerMinute)
{
unit = "seconds";
num = (long) (absmillis / millisPerSecond);
}
else if (absmillis < 3 * millisPerHour)
{
unit = "minutes";
num = (long) (absmillis / millisPerMinute);
}
else if (absmillis < 3 * millisPerDay)
{
unit = "hours";
num = (long) (absmillis / millisPerHour);
}
else if (absmillis < 3 * millisPerWeek)
{
unit = "days";
num = (long) (absmillis / millisPerDay);
}
else if (absmillis < 3 * millisPerMonth)
{
unit = "weeks";
num = (long) (absmillis / millisPerWeek);
}
else if (absmillis < 3 * millisPerYear)
{
unit = "months";
num = (long) (absmillis / millisPerMonth);
}
else
{
unit = "years";
num = (long) (absmillis / millisPerYear);
}
return ""+num+" "+unit+" "+agofromnow;
}
}

View File

@ -0,0 +1,39 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import org.bukkit.Bukkit;
public class WorldUtil
{
// Previously We had crappy support for multiworld management.
// This should however be handled by an external plugin!
/*public static boolean load(String name) {
if (isWorldLoaded(name)) {
return true;
}
if ( ! doesWorldExist(name)) {
return false;
}
Environment env = WorldEnv.get(name);
if (env == null) {
P.log(Level.WARNING, "Failed to load world. Environment was unknown.");
return false;
}
P.p.getServer().createWorld(name, env);
return true;
}*/
public static boolean isWorldLoaded(String name)
{
return Bukkit.getServer().getWorld(name) != null;
}
public static boolean doesWorldExist(String name)
{
return new File(name, "level.dat").exists();
}
}

View File

@ -1,7 +1,8 @@
name: Factions
version: 1.5.1_dev
main: com.massivecraft.factions.Factions
version: 1.6.0_dev
main: com.massivecraft.factions.P
softdepend:
- PermissionsEx
- Permissions
- Essentials
- EssentialsChat
@ -16,10 +17,6 @@ softdepend:
- Spout
- WorldEdit
- WorldGuard
commands:
f:
description: All of the Factions commands
usage: See documentation.
permissions:
factions.*:
description: Grants all Factions permissions