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

View File

@ -1,27 +1,28 @@
package com.massivecraft.factions; package com.massivecraft.factions;
import java.io.File;
import java.util.*; import java.util.*;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.entity.CreatureType; import org.bukkit.entity.CreatureType;
import com.massivecraft.factions.util.DiscUtil; public class Conf
{
// track players with admin access who have enabled "admin bypass" mode, and should therefore be able to build anywhere
public class Conf { // not worth saving between server restarts, I think
public static final transient File file = new File(Factions.instance.getDataFolder(), "conf.json"); public static transient Set<String> adminBypassPlayers = Collections.synchronizedSet(new HashSet<String>());
// Colors // Colors
public static ChatColor colorMember = ChatColor.GREEN; public static ChatColor colorMember = ChatColor.GREEN;
public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE;
public static ChatColor colorNeutral = ChatColor.WHITE; public static ChatColor colorNeutral = ChatColor.WHITE;
public static ChatColor colorEnemy = ChatColor.RED; public static ChatColor colorEnemy = ChatColor.RED;
/*
public static ChatColor colorSystem = ChatColor.YELLOW; public static ChatColor colorSystem = ChatColor.YELLOW;
public static ChatColor colorChrome = ChatColor.GOLD; public static ChatColor colorChrome = ChatColor.GOLD;
public static ChatColor colorCommand = ChatColor.AQUA; public static ChatColor colorCommand = ChatColor.AQUA;
public static ChatColor colorParameter = ChatColor.DARK_AQUA; public static ChatColor colorParameter = ChatColor.DARK_AQUA;
*/
// Power // Power
public static double powerPlayerMax = 10.0; public static double powerPlayerMax = 10.0;
public static double powerPlayerMin = -10.0; public static double powerPlayerMin = -10.0;
@ -39,10 +40,10 @@ public class Conf {
public static int factionTagLengthMax = 10; public static int factionTagLengthMax = 10;
public static boolean factionTagForceUpperCase = false; 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" // 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 showMapFactionKey = true;
public static boolean showNeutralFactionsOnMap = true; public static boolean showNeutralFactionsOnMap = true;
@ -183,7 +184,7 @@ public class Conf {
// Spout features // Spout features
public static boolean spoutFactionTagsOverNames = true; public static boolean spoutFactionTagsOverNames = true;
public static boolean spoutFactionTitlesOverNames = 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 boolean spoutFactionModeratorCapes = true;
public static int spoutTerritoryDisplayPosition = 3; public static int spoutTerritoryDisplayPosition = 3;
public static String capeAlly = "https://github.com/MassiveCraft/Factions/raw/master/capes/ally.png"; 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 int mapWidth = 39;
public static transient char[] mapKeyChrs = "\\/#?$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz".toCharArray(); public static transient char[] mapKeyChrs = "\\/#?$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz".toCharArray();
static { static
{
territoryEnemyDenyCommands.add("home"); territoryEnemyDenyCommands.add("home");
territoryEnemyDenyCommands.add("sethome"); territoryEnemyDenyCommands.add("sethome");
territoryEnemyDenyCommands.add("spawn"); territoryEnemyDenyCommands.add("spawn");
@ -281,45 +283,17 @@ public class Conf {
safeZoneNerfedCreatureTypes.add(CreatureType.ZOMBIE); 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 // Persistance
// -------------------------------------------- // // -------------------------------------------- //
private static transient Conf i = new Conf();
public static boolean save() { public static void load()
//Factions.log("Saving config to disk."); {
P.p.persist.loadOrSaveDefault(i, Conf.class, "conf");
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;
}
return true;
} }
public static void save()
public static boolean load() { {
Factions.log("Loading conf from disk"); P.p.persist.save(i);
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;
} }
} }

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.Relation;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.*; 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;
// -------------------------------------------- // // FIELD: claimOwnership
// 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;
private Map<FLocation, Set<String>> claimOwnership = new ConcurrentHashMap<FLocation, Set<String>>(); 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; 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; private boolean peaceful;
public boolean isPeaceful() { return this.peaceful; }
public void setPeaceful(boolean isPeaceful) { this.peaceful = isPeaceful; }
// FIELD: peacefulExplosionsEnabled
private boolean 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; private boolean permanent;
public boolean isPermanent() { return permanent; }
public void setPermanent(boolean isPermanent) { permanent = isPermanent; }
// FIELD: tag
private String 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; private String description;
public String getDescription() { return this.description; }
public void setDescription(String value) { this.description = value; }
// FIELD: home
private Location 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; private transient long lastPlayerLoggedOffTime;
// FIELD: money
// Bank functions
private double money; 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 // Construct
// -------------------------------------------- // // -------------------------------------------- //
public Faction() { public Faction()
this.relationWish = new HashMap<Integer, Relation>(); {
this.relationWish = new HashMap<String, Relation>();
this.invites = new HashSet<String>(); this.invites = new HashSet<String>();
this.open = Conf.newFactionsDefaultOpen; this.open = Conf.newFactionsDefaultOpen;
this.tag = "???"; this.tag = "???";
@ -59,188 +150,97 @@ public class Faction {
} }
// -------------------------------------------- // // -------------------------------------------- //
// Getters And Setters // Extra Getters And Setters
// -------------------------------------------- // // -------------------------------------------- //
public int getId() {
return this.id;
}
public boolean getOpen() {
return open;
}
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() { public boolean noPvPInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); }
confirmValidHome();
return home;
}
public boolean hasHome() {
confirmValidHome();
return this.home != null;
}
public void confirmValidHome() { public boolean noMonstersInTerritory() { return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); }
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."); public boolean noExplosionsInTerritory() { return peaceful && !peacefulExplosionsEnabled; }
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;
}
// ------------------------------- // -------------------------------
// Understand the types // Understand the types
// ------------------------------- // -------------------------------
public boolean isNormal() { public boolean isNormal()
return this.getId() > 0; {
return ! (this.isNone() || this.isSafeZone() || this.isWarZone());
} }
public boolean isNone() { public boolean isNone()
return this.getId() == 0; {
return this.getId().equals("0");
} }
public boolean isSafeZone() { public boolean isSafeZone()
return this.getId() == -1; {
return this.getId().equals("-1");
} }
public boolean isWarZone() { public boolean isWarZone()
return this.getId() == -2; {
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 // Relation and relation colors TODO
// ------------------------------- // -------------------------------
public Relation getRelationWish(Faction otherFaction) { public Relation getRelationWish(Faction otherFaction)
if (this.relationWish.containsKey(otherFaction.getId())){ {
if (this.relationWish.containsKey(otherFaction.getId()))
{
return this.relationWish.get(otherFaction.getId()); return this.relationWish.get(otherFaction.getId());
} }
return Relation.NEUTRAL; return Relation.NEUTRAL;
} }
public void setRelationWish(Faction otherFaction, Relation relation) { public void setRelationWish(Faction otherFaction, Relation relation)
if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)){ {
if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL))
{
this.relationWish.remove(otherFaction.getId()); this.relationWish.remove(otherFaction.getId());
} else { }
else
{
this.relationWish.put(otherFaction.getId(), relation); this.relationWish.put(otherFaction.getId(), relation);
} }
} }
public Relation getRelation(Faction otherFaction) { public Relation getRelation(Faction otherFaction)
{
return getRelation(otherFaction, false); return getRelation(otherFaction, false);
} }
public Relation getRelation(Faction otherFaction, boolean ignorePeaceful) { public Relation getRelation(Faction otherFaction, boolean ignorePeaceful)
if (!otherFaction.isNormal() || !this.isNormal()) { {
if (!otherFaction.isNormal() || !this.isNormal())
{
return Relation.NEUTRAL; return Relation.NEUTRAL;
} }
if (otherFaction.equals(this)) {
if (otherFaction.equals(this))
{
return Relation.MEMBER; return Relation.MEMBER;
} }
if (!ignorePeaceful && (this.peaceful || otherFaction.isPeaceful())) {
if (!ignorePeaceful && (this.peaceful || otherFaction.isPeaceful()))
{
return Relation.NEUTRAL; 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 otherFaction.getRelationWish(this);
} }
return this.getRelationWish(otherFaction); return this.getRelationWish(otherFaction);
} }
public Relation getRelation(FPlayer fplayer) { public Relation getRelation(FPlayer fplayer)
{
if (fplayer == null) if (fplayer == null)
return Relation.NEUTRAL; return Relation.NEUTRAL;
else else
@ -250,7 +250,8 @@ public class Faction {
//----------------------------------------------// //----------------------------------------------//
// Power // Power
//----------------------------------------------// //----------------------------------------------//
public double getPower() { public double getPower()
{
double ret = 0; double ret = 0;
for (FPlayer fplayer : this.getFPlayers()) { for (FPlayer fplayer : this.getFPlayers()) {
ret += fplayer.getPower(); ret += fplayer.getPower();
@ -296,13 +297,15 @@ public class Faction {
// Fplayers // Fplayers
// ------------------------------- // -------------------------------
public ArrayList<FPlayer> getFPlayers() { public ArrayList<FPlayer> getFPlayers()
{
ArrayList<FPlayer> ret = new ArrayList<FPlayer>(); ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id < 0) if (id < 0) return ret;
return ret;
for (FPlayer fplayer : FPlayer.getAll()) { for (FPlayer fplayer : FPlayers.i.get())
if (fplayer.getFaction() == this) { {
if (fplayer.getFaction() == this)
{
ret.add(fplayer); ret.add(fplayer);
} }
} }
@ -310,13 +313,15 @@ public class Faction {
return ret; return ret;
} }
public ArrayList<FPlayer> getFPlayersWhereOnline(boolean online) { public ArrayList<FPlayer> getFPlayersWhereOnline(boolean online)
{
ArrayList<FPlayer> ret = new ArrayList<FPlayer>(); ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id < 0) if (id < 0) return ret;
return ret;
for (FPlayer fplayer : FPlayer.getAll()) { for (FPlayer fplayer : FPlayers.i.get())
if (fplayer.getFaction() == this && fplayer.isOnline() == online) { {
if (fplayer.getFaction() == this && fplayer.isOnline() == online)
{
ret.add(fplayer); ret.add(fplayer);
} }
} }
@ -324,12 +329,14 @@ public class Faction {
return ret; return ret;
} }
public FPlayer getFPlayerAdmin() { public FPlayer getFPlayerAdmin()
if (id <= 0) {
return null; if (id <= 0) return null;
for (FPlayer fplayer : FPlayer.getAll()) { for (FPlayer fplayer : FPlayers.i.get())
if (fplayer.getFaction() == this && fplayer.getRole() == Role.ADMIN) { {
if (fplayer.getFaction() == this && fplayer.getRole() == Role.ADMIN)
{
return fplayer; return fplayer;
} }
} }
@ -338,10 +345,9 @@ public class Faction {
public ArrayList<FPlayer> getFPlayersWhereRole(Role role) { public ArrayList<FPlayer> getFPlayersWhereRole(Role role) {
ArrayList<FPlayer> ret = new ArrayList<FPlayer>(); ArrayList<FPlayer> ret = new ArrayList<FPlayer>();
if (id <= 0) if (id <= 0) return ret;
return ret;
for (FPlayer fplayer : FPlayer.getAll()) { for (FPlayer fplayer : FPlayers.i.get()) {
if (fplayer.getFaction() == this && fplayer.getRole() == role) { if (fplayer.getFaction() == this && fplayer.getRole() == role) {
ret.add(fplayer); ret.add(fplayer);
} }
@ -350,14 +356,16 @@ public class Faction {
return ret; return ret;
} }
public ArrayList<Player> getOnlinePlayers() { public ArrayList<Player> getOnlinePlayers()
{
ArrayList<Player> ret = new ArrayList<Player>(); ArrayList<Player> ret = new ArrayList<Player>();
if (id < 0) if (id < 0) return ret;
return ret;
for (Player player: Factions.instance.getServer().getOnlinePlayers()) { for (Player player: P.p.getServer().getOnlinePlayers())
FPlayer fplayer = FPlayer.get(player); {
if (fplayer.getFaction() == this) { FPlayer fplayer = FPlayers.i.get(player);
if (fplayer.getFaction() == this)
{
ret.add(player); 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 // 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 // only real factions can have players online, not safe zone / war zone
if (id < 0) if (id < 0) return false;
return false;
for (Player player: Factions.instance.getServer().getOnlinePlayers()) { for (Player player: P.p.getServer().getOnlinePlayers())
FPlayer fplayer = FPlayer.get(player); {
if (fplayer.getFaction() == this) { FPlayer fplayer = FPlayers.i.get(player);
if (fplayer.getFaction() == this)
{
return true; return true;
} }
} }
// even if all players are technically logged off, maybe someone was on recently enough to not consider them officially offline yet // 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 && if (Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000))
System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000)) { {
return true; return true;
} }
return false; return false;
} }
public void memberLoggedOff() { public void memberLoggedOff()
if (this.isNormal()) { {
if (this.isNormal())
{
lastPlayerLoggedOffTime = System.currentTimeMillis(); 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 // Messages
//----------------------------------------------// //----------------------------------------------//
public void sendMessage(String message) { public void sendMessage(String message)
for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { {
for (FPlayer fplayer : this.getFPlayersWhereOnline(true))
{
fplayer.sendMessage(message); fplayer.sendMessage(message);
} }
} }
public void sendMessage(List<String> messages) { public void sendMessage(List<String> messages)
for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { {
for (FPlayer fplayer : this.getFPlayersWhereOnline(true))
{
fplayer.sendMessage(messages); fplayer.sendMessage(messages);
} }
} }
@ -453,11 +429,13 @@ public class Faction {
// Mudd TODO // Mudd TODO
//----------------------------------------------// //----------------------------------------------//
public ChatColor getRelationColor(Faction otherFaction) { public ChatColor getRelationColor(Faction otherFaction)
{
return this.getRelation(otherFaction).getColor(); return this.getRelation(otherFaction).getColor();
} }
public ChatColor getRelationColor(FPlayer fplayer) { public ChatColor getRelationColor(FPlayer fplayer)
{
return this.getRelation(fplayer).getColor(); return this.getRelation(fplayer).getColor();
} }
@ -465,78 +443,96 @@ public class Faction {
// Ownership of specific claims // Ownership of specific claims
//----------------------------------------------// //----------------------------------------------//
public void clearAllClaimOwnership() { public void clearAllClaimOwnership()
{
claimOwnership.clear(); claimOwnership.clear();
} }
public void clearClaimOwnership(FLocation loc) { public void clearClaimOwnership(FLocation loc)
{
claimOwnership.remove(loc); claimOwnership.remove(loc);
} }
public void clearClaimOwnership(String playerName) { public void clearClaimOwnership(String playerName)
if (playerName == null || playerName.isEmpty()) { {
if (playerName == null || playerName.isEmpty())
{
return; return;
} }
Set<String> ownerData; Set<String> ownerData;
String player = playerName.toLowerCase(); String player = playerName.toLowerCase();
for (Entry<FLocation, Set<String>> entry : claimOwnership.entrySet()) { for (Entry<FLocation, Set<String>> entry : claimOwnership.entrySet())
{
ownerData = entry.getValue(); ownerData = entry.getValue();
if (ownerData == null) { if (ownerData == null) continue;
continue;
}
Iterator<String> iter = ownerData.iterator(); Iterator<String> iter = ownerData.iterator();
while (iter.hasNext()) { while (iter.hasNext())
if (iter.next().equals(player)) { {
if (iter.next().equals(player))
{
iter.remove(); iter.remove();
} }
} }
if (ownerData.isEmpty()) { if (ownerData.isEmpty())
{
claimOwnership.remove(entry.getKey()); claimOwnership.remove(entry.getKey());
} }
} }
} }
public int getCountOfClaimsWithOwners() { public int getCountOfClaimsWithOwners()
{
return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); return claimOwnership.isEmpty() ? 0 : claimOwnership.size();
} }
public boolean doesLocationHaveOwnersSet(FLocation loc) { public boolean doesLocationHaveOwnersSet(FLocation loc)
if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { {
if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc))
{
return false; return false;
} }
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
return ownerData != null && !ownerData.isEmpty(); return ownerData != null && !ownerData.isEmpty();
} }
public boolean isPlayerInOwnerList(String playerName, FLocation loc) { public boolean isPlayerInOwnerList(String playerName, FLocation loc)
if (claimOwnership.isEmpty()) { {
if (claimOwnership.isEmpty())
{
return false; return false;
} }
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) { if (ownerData == null)
{
return false; return false;
} }
if (ownerData.contains(playerName.toLowerCase())) { if (ownerData.contains(playerName.toLowerCase()))
{
return true; return true;
} }
return false; return false;
} }
public void setPlayerAsOwner(String playerName, FLocation loc) { public void setPlayerAsOwner(String playerName, FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) { if (ownerData == null)
{
ownerData = new HashSet<String>(); ownerData = new HashSet<String>();
} }
ownerData.add(playerName.toLowerCase()); ownerData.add(playerName.toLowerCase());
claimOwnership.put(loc, ownerData); claimOwnership.put(loc, ownerData);
} }
public void removePlayerAsOwner(String playerName, FLocation loc) { public void removePlayerAsOwner(String playerName, FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null) { if (ownerData == null) {
return; return;
@ -545,13 +541,16 @@ public class Faction {
claimOwnership.put(loc, ownerData); claimOwnership.put(loc, ownerData);
} }
public Set<String> getOwnerList(FLocation loc) { public Set<String> getOwnerList(FLocation loc)
{
return claimOwnership.get(loc); return claimOwnership.get(loc);
} }
public String getOwnerListString(FLocation loc) { public String getOwnerListString(FLocation loc)
{
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
if (ownerData == null || ownerData.isEmpty()) { if (ownerData == null || ownerData.isEmpty())
{
return ""; return "";
} }
@ -559,7 +558,8 @@ public class Faction {
Iterator<String> iter = ownerData.iterator(); Iterator<String> iter = ownerData.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
if (!ownerList.isEmpty()) { if (!ownerList.isEmpty())
{
ownerList += ", "; ownerList += ", ";
} }
ownerList += iter.next(); ownerList += iter.next();
@ -567,19 +567,23 @@ public class Faction {
return ownerList; return ownerList;
} }
public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc)
{
// different faction? // different faction?
if (fplayer.getFactionId() != id) { if (fplayer.getFactionId() != this.getId())
{
return false; return false;
} }
// sufficient role to bypass ownership? // 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; return true;
} }
// make sure claimOwnership is initialized // make sure claimOwnership is initialized
if (claimOwnership.isEmpty()) { if (claimOwnership.isEmpty())
{
return true; return true;
} }
@ -587,7 +591,8 @@ public class Faction {
Set<String> ownerData = claimOwnership.get(loc); Set<String> ownerData = claimOwnership.get(loc);
// if no owner list, owner list is empty, or player is in owner list, they're allowed // 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())) { if (ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getName().toLowerCase()))
{
return true; return true;
} }
@ -595,74 +600,48 @@ public class Faction {
} }
//----------------------------------------------//
// Bank functions
//----------------------------------------------//
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;
}
//----------------------------------------------// //----------------------------------------------//
// Persistance and entity management // Persistance and entity management
//----------------------------------------------// //----------------------------------------------//
public static boolean save() { /*public static boolean save() {
//Factions.log("Saving factions to disk"); //Factions.log("Saving factions to disk");
try { try {
DiscUtil.write(file, Factions.instance.gson.toJson(instances)); DiscUtil.write(file, P.p.gson.toJson(instances));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); 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; return false;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Factions.log("Failed to save the factions to disk."); P.log("Failed to save the factions to disk.");
return false; return false;
} }
return true; return true;
} }
*/
public static boolean load() { /*public static boolean load() {
Factions.log("Loading factions from disk"); P.log("Loading factions from disk");
if ( ! file.exists()) { if ( ! file.exists()) {
if ( ! loadOld()) 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(); save();
} }
try { try {
Type type = new TypeToken<Map<Integer, Faction>>(){}.getType(); 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.clear();
instances.putAll(instancesFromFile); instances.putAll(instancesFromFile);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Factions.log("Failed to load the factions from disk."); P.log("Failed to load the factions from disk.");
return false; return false;
} }
@ -696,28 +675,31 @@ public class Faction {
} }
return true; return true;
}*/
@Override
public void postDetach()
{
// Clean the board
Board.clean();
// Clean the fplayers
FPlayers.i.clean();
} }
public static void fillIds() { /*public static Faction get(Integer factionId)
nextId = 1; {
for(Entry<Integer, Faction> entry : instances.entrySet()) { if ( ! instances.containsKey(factionId))
entry.getValue().id = entry.getKey(); {
if (nextId < entry.getKey()) { P.log(Level.WARNING, "Non existing factionId "+factionId+" requested! Issuing cleaning!");
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!");
Board.clean(); Board.clean();
FPlayer.clean(); FPlayer.clean();
} }
return instances.get(factionId); return instances.get(factionId);
} }*/
/*
public static Faction getNone() { public static Faction getNone() {
return instances.get(0); return instances.get(0);
} }
@ -728,23 +710,22 @@ public class Faction {
public static Faction getWarZone() { public static Faction getWarZone() {
return instances.get(-2); return instances.get(-2);
} }*/
/*
public static boolean exists(Integer factionId) { public static boolean exists(Integer factionId) {
return instances.containsKey(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. //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 faction = new Faction();
faction.id = nextId; faction.id = nextId;
nextId += 1; nextId += 1;
instances.put(faction.id, faction); instances.put(faction.id, faction);
Factions.log("created new faction "+faction.id); P.log("created new faction "+faction.id);
//faction.save(); //faction.save();
return faction; return faction;
} }
@ -761,12 +742,12 @@ public class Faction {
} }
private static boolean loadOld() { private static boolean loadOld() {
File folderFaction = new File(Factions.instance.getDataFolder(), "faction"); File folderFaction = new File(P.p.getDataFolder(), "faction");
if ( ! folderFaction.isDirectory()) if ( ! folderFaction.isDirectory())
return false; 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"; String ext = ".json";
@ -785,15 +766,15 @@ public class Faction {
int id = Integer.parseInt(name); int id = Integer.parseInt(name);
try { 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; faction.id = id;
instances.put(faction.id, faction); instances.put(faction.id, faction);
Factions.log("loaded pre-1.1 faction "+id); P.log("loaded pre-1.1 faction "+id);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Factions.log(Level.WARNING, "Failed to load faction "+id); P.log(Level.WARNING, "Failed to load faction "+id);
} }
} }
return true; return true;
} }*/
} }

View File

@ -1,538 +1,157 @@
package com.massivecraft.factions; package com.massivecraft.factions;
import java.io.File; import java.io.File;
import java.lang.reflect.Modifier; import java.lang.reflect.Type;
import java.lang.reflect.Type; import java.util.*;
import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap;
import java.util.Arrays; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.HashSet; import java.util.logging.Level;
import java.util.List;
import java.util.Map; import org.bukkit.ChatColor;
import java.util.Set;
import java.util.logging.Level; import com.google.gson.reflect.TypeToken;
import java.util.logging.Logger; import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.persist.EntityCollection;
import org.bukkit.block.Block;
import org.bukkit.Location; public class Factions extends EntityCollection<Faction>
import org.bukkit.Material; {
import org.bukkit.command.Command; public static Factions i = new Factions();
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; P p = P.p;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerChatEvent; private Factions()
import org.bukkit.plugin.Plugin; {
import org.bukkit.plugin.PluginManager; super
import org.bukkit.plugin.java.JavaPlugin; (
Faction.class,
import com.massivecraft.factions.commands.*; new CopyOnWriteArrayList<Faction>(),
import com.massivecraft.factions.integration.Econ; new ConcurrentHashMap<String, Faction>(),
import com.massivecraft.factions.integration.SpoutFeatures; new File(P.p.getDataFolder(), "factions.json"),
import com.massivecraft.factions.integration.Worldguard; P.p.gson
import com.massivecraft.factions.listeners.FactionsBlockListener; );
import com.massivecraft.factions.listeners.FactionsChatEarlyListener; }
import com.massivecraft.factions.listeners.FactionsEntityListener;
import com.massivecraft.factions.listeners.FactionsPlayerListener; @Override
import com.massivecraft.factions.struct.ChatMode; public Type getMapType()
import com.massivecraft.factions.util.JarLoader; {
import com.massivecraft.factions.util.MapFLocToStringSetTypeAdapter; return new TypeToken<Map<String, Faction>>(){}.getType();
import com.massivecraft.factions.util.MyLocationTypeAdapter; }
import com.nijiko.permissions.PermissionHandler; @Override
import com.nijikokun.bukkit.Permissions.Permissions; public boolean loadFromDisc()
import com.earth2me.essentials.chat.EssentialsChat; {
import com.google.gson.Gson; if ( ! super.loadFromDisc()) return false;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken; // Make sure the default neutral faction exists
import com.massivecraft.factions.integration.EssentialsFeatures; if ( ! this.exists("0"))
{
/** Faction faction = this.create("0");
* The data is saved to disk every 30min and on plugin disable. faction.setTag(ChatColor.DARK_GREEN+"Wilderness");
*/ faction.setDescription("");
public class Factions extends JavaPlugin { }
// -------------------------------------------- //
// Fields // Make sure the safe zone faction exists
// -------------------------------------------- // if ( ! this.exists("-1"))
public static Factions instance; {
private Integer saveTask = null; Faction faction = this.create("-1");
faction.setTag(ChatColor.GOLD+"Safe Zone");
public Gson gson; faction.setDescription("Free from PVP and monsters");
}
private final FactionsPlayerListener playerListener = new FactionsPlayerListener();
private final FactionsChatEarlyListener chatEarlyListener = new FactionsChatEarlyListener(); // Make sure the war zone faction exists
private final FactionsEntityListener entityListener = new FactionsEntityListener(); if ( ! this.exists("-2"))
private final FactionsBlockListener blockListener = new FactionsBlockListener(); {
Faction faction = this.create("-2");
public static PermissionHandler Permissions; faction.setTag(ChatColor.DARK_RED+"War Zone");
private static EssentialsChat essChat; faction.setDescription("Not the safest place to be");
}
// Commands
public List<FBaseCommand> commands = new ArrayList<FBaseCommand>(); return true;
}
private String baseCommand;
public Factions() { //----------------------------------------------//
Factions.instance = this; // GET
} //----------------------------------------------//
@Override
@Override public Faction get(String id)
public void onEnable() { {
log("=== ENABLE START ==="); if ( ! this.exists(id))
long timeInitStart = System.currentTimeMillis(); {
p.log(Level.WARNING, "Non existing factionId "+id+" requested! Issuing cleaning!");
// Load the gson library we require Board.clean();
File gsonfile = new File("./lib/gson.jar"); FPlayers.i.clean();
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 super.get(id);
return; }
}
public Faction getNone()
Type mapFLocToStringSetType = new TypeToken<Map<FLocation, Set<String>>>(){}.getType(); {
return this.get("0");
gson = new GsonBuilder() }
.setPrettyPrinting()
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) public Faction getSafeZone()
.registerTypeAdapter(Location.class, new MyLocationTypeAdapter()) {
.registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()) return this.get("-1");
.create(); }
// Add the commands public Faction getWarZone()
commands.add(new FCommandHelp()); {
commands.add(new FCommandAdmin()); return this.get("-2");
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()); // Faction tag
commands.add(new FCommandDeinvite()); //----------------------------------------------//
commands.add(new FCommandDeposit());
commands.add(new FCommandDescription()); public static ArrayList<String> validateTag(String str)
commands.add(new FCommandDisband()); {
commands.add(new FCommandHome()); ArrayList<String> errors = new ArrayList<String>();
commands.add(new FCommandInvite());
commands.add(new FCommandJoin()); if(MiscUtil.getComparisonString(str).length() < Conf.factionTagLengthMin)
commands.add(new FCommandKick()); {
commands.add(new FCommandLeave()); errors.add(P.p.txt.parse("<i>The faction tag can't be shorter than "+Conf.factionTagLengthMin+ " chars."));
commands.add(new FCommandList()); }
commands.add(new FCommandLock());
commands.add(new FCommandMap()); if(str.length() > Conf.factionTagLengthMax)
commands.add(new FCommandMod()); {
commands.add(new FCommandNoBoom()); errors.add(P.p.txt.parse("<i>The faction tag can't be longer than "+Conf.factionTagLengthMax+ " chars."));
commands.add(new FCommandOpen()); }
commands.add(new FCommandOwner());
commands.add(new FCommandOwnerList()); for (char c : str.toCharArray())
commands.add(new FCommandPay()); {
commands.add(new FCommandPower()); if ( ! MiscUtil.substanceChars.contains(String.valueOf(c)))
commands.add(new FCommandPeaceful()); {
commands.add(new FCommandPermanent()); errors.add(P.p.txt.parse("<i>Faction tag must be alphanumeric. \""+c+"\" is not allowed."));
commands.add(new FCommandRelationAlly()); }
commands.add(new FCommandRelationEnemy()); }
commands.add(new FCommandRelationNeutral());
commands.add(new FCommandReload()); return errors;
commands.add(new FCommandSafeclaim()); }
commands.add(new FCommandSafeunclaimall());
commands.add(new FCommandSaveAll()); public Faction findByTag(String str)
commands.add(new FCommandSethome()); {
commands.add(new FCommandShow()); String compStr = MiscUtil.getComparisonString(str);
commands.add(new FCommandTag()); for (Faction faction : this.get())
commands.add(new FCommandTitle()); {
commands.add(new FCommandUnclaim()); if (faction.getComparisonTag().equals(compStr))
commands.add(new FCommandUnclaimall()); {
commands.add(new FCommandVersion()); return faction;
commands.add(new FCommandWarclaim()); }
commands.add(new FCommandWarunclaimall()); }
commands.add(new FCommandWithdraw()); return null;
}
// Ensure base folder exists!
this.getDataFolder().mkdirs(); public boolean isTagTaken(String str)
{
Conf.load(); return this.findByTag(str) != null;
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) ===");
}
@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;
}
@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");
}
// -------------------------------------------- //
// Logging
// -------------------------------------------- //
public static void log(String msg) {
log(Level.INFO, msg);
}
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();
}
}

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 @Override
public void run() { 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.integration.Econ;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; 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.struct.Role;
import com.massivecraft.factions.util.TextUtil; 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 // make sure player doesn't have their access to the command revoked
Iterator<String> iter = aliases.iterator(); Iterator<String> iter = aliases.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
if (Factions.isCommandDisabled(sender, iter.next())) { if (P.isCommandDisabled(sender, iter.next())) {
sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+"."); sendMessage("You lack the permissions to "+this.helpDescription.toLowerCase()+".");
return false; return false;
} }
@ -114,7 +114,7 @@ public class FBaseCommand {
} }
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermParticipate(sender); return P.hasPermParticipate(sender);
} }
// -------------------------------------------- // // -------------------------------------------- //
@ -126,7 +126,7 @@ public class FBaseCommand {
ret += Conf.colorCommand; 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>(); 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.Board;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandAutoSafeclaim extends FBaseCommand { public class FCommandAutoSafeclaim extends FBaseCommand {
@ -19,7 +19,7 @@ public class FCommandAutoSafeclaim extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageSafeZone(sender); return P.hasPermManageSafeZone(sender);
} }
@Override @Override

View File

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

View File

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

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandBypass extends FBaseCommand { public class FCommandBypass extends FBaseCommand {
@ -16,7 +16,7 @@ public class FCommandBypass extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermAdminBypass(sender); return P.hasPermAdminBypass(sender);
} }
@Override @Override
@ -24,11 +24,11 @@ public class FCommandBypass extends FBaseCommand {
if ( ! Conf.adminBypassPlayers.contains(player.getName())) { if ( ! Conf.adminBypassPlayers.contains(player.getName())) {
Conf.adminBypassPlayers.add(player.getName()); Conf.adminBypassPlayers.add(player.getName());
me.sendMessage("You have enabled admin bypass mode. You will be able to build or destroy anywhere."); 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 { } else {
Conf.adminBypassPlayers.remove(player.getName()); Conf.adminBypassPlayers.remove(player.getName());
me.sendMessage("You have disabled admin bypass mode."); 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 org.bukkit.entity.Player;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.integration.SpoutFeatures;
public class FCommandConfig extends FBaseCommand { public class FCommandConfig extends FBaseCommand {
@ -32,7 +32,7 @@ public class FCommandConfig extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermConfigure(sender); return P.hasPermConfigure(sender);
} }
@Override @Override
@ -222,7 +222,7 @@ public class FCommandConfig extends FBaseCommand {
if (!success.isEmpty()) { if (!success.isEmpty()) {
sendMessage(success); sendMessage(success);
if (sender instanceof Player) { 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 // save change to disk

View File

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

View File

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

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
@ -34,7 +34,7 @@ public class FCommandDisband extends FBaseCommand {
return; return;
} }
if ( ! Factions.hasPermDisband(sender)) { if ( ! P.hasPermDisband(sender)) {
if (me.getFaction() == faction) { if (me.getFaction() == faction) {
parameters.clear(); parameters.clear();
} }
@ -54,7 +54,7 @@ public class FCommandDisband extends FBaseCommand {
faction = me.getFaction(); 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."); sendMessage("Your faction is designated as permanent, so you cannot disband it.");
return; return;
} }
@ -75,7 +75,7 @@ public class FCommandDisband extends FBaseCommand {
if (amount > 0.0) { if (amount > 0.0) {
String amountString = Econ.moneyString(amount); String amountString = Econ.moneyString(amount);
sendMessage("You have been given the disbanded faction's bank, totaling "+amountString+"."); 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.Conf;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandKick extends FBaseCommand { public class FCommandKick extends FBaseCommand {
@ -40,7 +40,7 @@ public class FCommandKick extends FBaseCommand {
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();
// players with admin-level "disband" permission can bypass these requirements // players with admin-level "disband" permission can bypass these requirements
if (!Factions.hasPermDisband(sender)) { if (!P.hasPermDisband(sender)) {
if (yourFaction != myFaction) { if (yourFaction != myFaction) {
sendMessage(you.getNameAndRelevant(me)+Conf.colorSystem+" is not a member of "+myFaction.getTag(me)); sendMessage(you.getNameAndRelevant(me)+Conf.colorSystem+" is not a member of "+myFaction.getTag(me));
return; return;

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.commands;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
@ -63,7 +63,7 @@ public class FCommandPay extends FBaseCommand {
them.addMoney(amount); them.addMoney(amount);
sendMessage("You have paid "+amountString+" from "+us.getTag()+"'s bank to "+them.getTag()+"'s bank."); sendMessage("You have paid "+amountString+" from "+us.getTag()+"'s bank to "+them.getTag()+"'s bank.");
sendMessage(us.getTag()+" now has "+Econ.moneyString(us.getMoney())); 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()) { for (FPlayer fplayer : FPlayer.getAllOnline()) {
if (fplayer.getFaction() == us || fplayer.getFaction() == them) { 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.Conf;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.integration.SpoutFeatures;
@ -22,7 +22,7 @@ public class FCommandPeaceful extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermSetPeaceful(sender); return P.hasPermSetPeaceful(sender);
} }
@Override @Override

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandSaveAll extends FBaseCommand { public class FCommandSaveAll extends FBaseCommand {
@ -17,12 +17,12 @@ public class FCommandSaveAll extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermSaveAll(sender); return P.hasPermSaveAll(sender);
} }
@Override @Override
public void perform() { public void perform() {
Factions.saveAll(); P.saveAll();
sendMessage("Factions saved to disk!"); 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.Conf;
import com.massivecraft.factions.Faction; 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.struct.Role;
public class FCommandSethome extends FBaseCommand { public class FCommandSethome extends FBaseCommand {
@ -38,7 +38,7 @@ public class FCommandSethome extends FBaseCommand {
Faction myFaction = me.getFaction(); Faction myFaction = me.getFaction();
if (parameters.size() > 0) { 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."); me.sendMessage("You cannot set the home of another faction without adminBypass permission.");
return; 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."); me.sendMessage("Sorry, your faction home can only be set inside your own claimed territory.");
return; return;
} }

View File

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

View File

@ -2,7 +2,7 @@ package com.massivecraft.factions.commands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandVersion extends FBaseCommand { public class FCommandVersion extends FBaseCommand {
@ -22,7 +22,7 @@ public class FCommandVersion extends FBaseCommand {
@Override @Override
public void perform() { 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.Board;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions; import com.massivecraft.factions.P;
public class FCommandWarclaim extends FBaseCommand { public class FCommandWarclaim extends FBaseCommand {
@ -20,7 +20,7 @@ public class FCommandWarclaim extends FBaseCommand {
@Override @Override
public boolean hasPermission(CommandSender sender) { public boolean hasPermission(CommandSender sender) {
return Factions.hasPermManageWarZone(sender); return P.hasPermManageWarZone(sender);
} }
public void perform() { public void perform() {

View File

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

View File

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

View File

@ -4,7 +4,7 @@ import org.bukkit.ChatColor;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction; 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.integration.SpoutFeatures;
import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role; 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()); myFaction.sendMessage(Conf.colorSystem+"Your faction is now "+currentRelationColor+whishedRelation.toString()+Conf.colorSystem+" to "+currentRelationColor+otherFaction.getTag());
} else { } else {
otherFaction.sendMessage(currentRelationColor+myFaction.getTag()+Conf.colorSystem+ " wishes to be your "+whishedRelation.getColor()+whishedRelation.toString()); 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); myFaction.sendMessage(currentRelationColor+otherFaction.getTag()+Conf.colorSystem+ " were informed that you wish to be "+whishedRelation.getColor()+whishedRelation);
} }
if (!whishedRelation.isNeutral() && otherFaction.isPeaceful()) { if (!whishedRelation.isNeutral() && otherFaction.isPeaceful()) {

View File

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

View File

@ -2,39 +2,45 @@ package com.massivecraft.factions.integration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent; 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.EssentialsChat;
import com.earth2me.essentials.chat.IEssentialsChatListener; import com.earth2me.essentials.chat.IEssentialsChatListener;
public class EssentialsFeatures { public class EssentialsFeatures
{
private static EssentialsChat essChat; private static EssentialsChat essChat;
public static void integrateChat(EssentialsChat instance) { public static void integrateChat(EssentialsChat instance)
{
essChat = instance; essChat = instance;
try { try
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener() { {
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener()
{
public boolean shouldHandleThisChat(PlayerChatEvent event) public boolean shouldHandleThisChat(PlayerChatEvent event)
{ {
return Factions.instance.shouldLetFactionsHandleThisChat(event); return P.p.shouldLetFactionsHandleThisChat(event);
} }
public String modifyMessage(PlayerChatEvent event, Player target, String message) 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; essChat = null;
} }
} }
public static void unhookChat() { public static void unhookChat()
if (essChat != null) { {
if (essChat != null)
{
essChat.removeEssentialsChatListener("Factions"); essChat.removeEssentialsChatListener("Factions");
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,8 @@ import org.bukkit.ChatColor;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
public enum Relation { public enum Relation
{
MEMBER(3, "member"), MEMBER(3, "member"),
ALLY(2, "ally"), ALLY(2, "ally"),
NEUTRAL(1, "neutral"), NEUTRAL(1, "neutral"),
@ -20,107 +21,145 @@ public enum Relation {
} }
@Override @Override
public String toString() { public String toString()
{
return this.nicename; return this.nicename;
} }
public boolean isMember() { // TODO: Insane way to use enums!!!?
public boolean isMember()
{
return this.value == MEMBER.value; return this.value == MEMBER.value;
} }
public boolean isAlly() { public boolean isAlly()
{
return this.value == ALLY.value; return this.value == ALLY.value;
} }
public boolean isNeutral() { public boolean isNeutral()
{
return this.value == NEUTRAL.value; return this.value == NEUTRAL.value;
} }
public boolean isEnemy() { public boolean isEnemy()
{
return this.value == ENEMY.value; return this.value == ENEMY.value;
} }
public boolean isAtLeast(Relation relation) { public boolean isAtLeast(Relation relation)
{
return this.value >= relation.value; return this.value >= relation.value;
} }
public boolean isAtMost(Relation relation) { public boolean isAtMost(Relation relation)
{
return this.value <= relation.value; return this.value <= relation.value;
} }
public ChatColor getColor() { public ChatColor getColor()
if (this.value == MEMBER.value) { {
if (this.value == MEMBER.value)
{
return Conf.colorMember; return Conf.colorMember;
} else if (this.value == ALLY.value) { }
else if (this.value == ALLY.value)
{
return Conf.colorAlly; return Conf.colorAlly;
} else if (this.value == NEUTRAL.value) { }
else if (this.value == NEUTRAL.value)
{
return Conf.colorNeutral; return Conf.colorNeutral;
} else { }
else
{
return Conf.colorEnemy; return Conf.colorEnemy;
} }
} }
// return appropriate Conf setting for DenyBuild based on this relation and their online status // return appropriate Conf setting for DenyBuild based on this relation and their online status
public boolean confDenyBuild(boolean online) { public boolean confDenyBuild(boolean online)
if (online) { {
if (isEnemy()) { if (online)
{
if (isEnemy())
{
return Conf.territoryEnemyDenyBuild; return Conf.territoryEnemyDenyBuild;
} }
else if (isAlly()) { else if (isAlly())
{
return Conf.territoryAllyDenyBuild; return Conf.territoryAllyDenyBuild;
} }
else { else
{
return Conf.territoryDenyBuild; return Conf.territoryDenyBuild;
} }
} }
else { else
if (isEnemy()) { {
if (isEnemy())
{
return Conf.territoryEnemyDenyBuildWhenOffline; return Conf.territoryEnemyDenyBuildWhenOffline;
} }
else if (isAlly()) { else if (isAlly())
{
return Conf.territoryAllyDenyBuildWhenOffline; return Conf.territoryAllyDenyBuildWhenOffline;
} }
else { else
{
return Conf.territoryDenyBuildWhenOffline; return Conf.territoryDenyBuildWhenOffline;
} }
} }
} }
// return appropriate Conf setting for PainBuild based on this relation and their online status // return appropriate Conf setting for PainBuild based on this relation and their online status
public boolean confPainBuild(boolean online) { public boolean confPainBuild(boolean online)
if (online) { {
if (isEnemy()) { if (online)
{
if (isEnemy())
{
return Conf.territoryEnemyPainBuild; return Conf.territoryEnemyPainBuild;
} }
else if (isAlly()) { else if (isAlly())
{
return Conf.territoryAllyPainBuild; return Conf.territoryAllyPainBuild;
} }
else { else
{
return Conf.territoryPainBuild; return Conf.territoryPainBuild;
} }
} }
else { else
if (isEnemy()) { {
if (isEnemy())
{
return Conf.territoryEnemyPainBuildWhenOffline; return Conf.territoryEnemyPainBuildWhenOffline;
} }
else if (isAlly()) { else if (isAlly())
{
return Conf.territoryAllyPainBuildWhenOffline; return Conf.territoryAllyPainBuildWhenOffline;
} }
else { else
{
return Conf.territoryPainBuildWhenOffline; return Conf.territoryPainBuildWhenOffline;
} }
} }
} }
// return appropriate Conf setting for DenyUseage based on this relation // return appropriate Conf setting for DenyUseage based on this relation
public boolean confDenyUseage() { public boolean confDenyUseage()
if (isEnemy()) { {
if (isEnemy())
{
return Conf.territoryEnemyDenyUseage; return Conf.territoryEnemyDenyUseage;
} }
else if (isAlly()) { else if (isAlly())
{
return Conf.territoryAllyDenyUseage; return Conf.territoryAllyDenyUseage;
} }
else { else
{
return Conf.territoryDenyUseage; 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.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import com.massivecraft.factions.FLocation; 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 @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 { try {
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
if (obj == null) { if (obj == null)
{
return null; return null;
} }
@ -39,16 +42,19 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
String[] coords; String[] coords;
int x, z; int x, z;
for (Entry<String, JsonElement> entry : obj.entrySet()) { for (Entry<String, JsonElement> entry : obj.entrySet())
{
worldName = entry.getKey(); 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]+"); coords = entry2.getKey().trim().split("[,\\s]+");
x = Integer.parseInt(coords[0]); x = Integer.parseInt(coords[0]);
z = Integer.parseInt(coords[1]); z = Integer.parseInt(coords[1]);
nameSet = new HashSet<String>(); nameSet = new HashSet<String>();
iter = entry2.getValue().getAsJsonArray().iterator(); iter = entry2.getValue().getAsJsonArray().iterator();
while (iter.hasNext()) { while (iter.hasNext())
{
nameSet.add(iter.next().getAsString()); nameSet.add(iter.next().getAsString());
} }
@ -58,19 +64,23 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
return locationMap; return locationMap;
} catch (Exception ex) { }
catch (Exception ex)
{
ex.printStackTrace(); 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; return null;
} }
} }
@Override @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(); JsonObject obj = new JsonObject();
try { try {
if (src != null) { if (src != null)
{
FLocation loc; FLocation loc;
String locWorld; String locWorld;
Set<String> nameSet; Set<String> nameSet;
@ -78,23 +88,27 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
JsonArray nameArray; JsonArray nameArray;
JsonPrimitive nameElement; JsonPrimitive nameElement;
for (Entry<FLocation, Set<String>> entry : src.entrySet()) { for (Entry<FLocation, Set<String>> entry : src.entrySet())
{
loc = entry.getKey(); loc = entry.getKey();
locWorld = loc.getWorldName(); locWorld = loc.getWorldName();
nameSet = entry.getValue(); nameSet = entry.getValue();
if (nameSet == null || nameSet.isEmpty()) { if (nameSet == null || nameSet.isEmpty())
{
continue; continue;
} }
nameArray = new JsonArray(); nameArray = new JsonArray();
iter = nameSet.iterator(); iter = nameSet.iterator();
while (iter.hasNext()) { while (iter.hasNext())
{
nameElement = new JsonPrimitive(iter.next()); nameElement = new JsonPrimitive(iter.next());
nameArray.add(nameElement); nameArray.add(nameElement);
} }
if ( ! obj.has(locWorld)) { if ( ! obj.has(locWorld))
{
obj.add(locWorld, new JsonObject()); obj.add(locWorld, new JsonObject());
} }
@ -103,9 +117,11 @@ public class MapFLocToStringSetTypeAdapter implements JsonDeserializer<Map<FLoca
} }
return obj; return obj;
} catch (Exception ex) { }
catch (Exception ex)
{
ex.printStackTrace(); 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; return obj;
} }
} }

View File

@ -1,6 +1,27 @@
package com.massivecraft.factions.util; 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 // Inclusive range
public static long[] range(long start, long end) { public static long[] range(long start, long end) {
@ -12,8 +33,6 @@ public class MiscUtil {
end = oldstart; end = oldstart;
} }
for (long i = start; i <= end; i++) { for (long i = start; i <= end; i++) {
values[(int) (i - start)] = i; values[(int) (i - start)] = i;
} }
@ -21,5 +40,27 @@ public class MiscUtil {
return values; 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.JsonParseException;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; 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 WORLD = "world";
private static final String X = "x"; private static final String X = "x";
private static final String Y = "y"; private static final String Y = "y";
@ -25,14 +26,16 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
private static final String PITCH = "pitch"; private static final String PITCH = "pitch";
@Override @Override
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
try { {
try
{
JsonObject obj = json.getAsJsonObject(); JsonObject obj = json.getAsJsonObject();
String worldname = obj.get(WORLD).getAsString(); String worldname = obj.get(WORLD).getAsString();
World world = Factions.instance.getServer().getWorld(worldname); World world = P.p.getServer().getWorld(worldname);
if (world == null) { 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; return null;
} }
@ -44,9 +47,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
return new Location(world, x, y, z, yaw, pitch); return new Location(world, x, y, z, yaw, pitch);
} catch (Exception ex) { }
catch (Exception ex)
{
ex.printStackTrace(); 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; return null;
} }
} }
@ -55,10 +60,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
try { try
{
if (src.getWorld() == null) 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; return obj;
} }
@ -71,9 +77,11 @@ public class MyLocationTypeAdapter implements JsonDeserializer<Location>, JsonSe
return obj; return obj;
} catch (Exception ex) { }
catch (Exception ex)
{
ex.printStackTrace(); 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; 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 name: Factions
version: 1.5.1_dev version: 1.6.0_dev
main: com.massivecraft.factions.Factions main: com.massivecraft.factions.P
softdepend: softdepend:
- PermissionsEx
- Permissions - Permissions
- Essentials - Essentials
- EssentialsChat - EssentialsChat
@ -16,10 +17,6 @@ softdepend:
- Spout - Spout
- WorldEdit - WorldEdit
- WorldGuard - WorldGuard
commands:
f:
description: All of the Factions commands
usage: See documentation.
permissions: permissions:
factions.*: factions.*:
description: Grants all Factions permissions description: Grants all Factions permissions