Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

First commit of TownyPerms - Not tested saving/loading to sql or leaving

towns/nations yet (but should work).
Bug fix commits to follow.
  • Loading branch information...
commit 9860eb2239f6f9725ea28ed21261ec7a4cdf74ba 1 parent 3203146
ElgarL authored
6 .classpath
View
@@ -10,7 +10,11 @@
<classpathentry kind="lib" path="../lib/PermissionsEx.jar"/>
<classpathentry kind="lib" path="../lib/Questioner.jar"/>
<classpathentry kind="lib" path="../lib/Register.jar"/>
- <classpathentry kind="lib" path="../lib/bukkit.jar"/>
+ <classpathentry kind="lib" path="../lib/bukkit.jar">
+ <attributes>
+ <attribute name="javadoc_location" value="http://jd.bukkit.org/apidocs/"/>
+ </attributes>
+ </classpathentry>
<classpathentry kind="lib" path="../lib/citizensapi-2.0-SNAPSHOT.jar"/>
<classpathentry kind="lib" path="../lib/Vault.jar"/>
<classpathentry kind="output" path="bin"/>
3  build.xml
View
@@ -39,7 +39,8 @@
<fileset dir="./src" includes="english.yml"/>
<fileset dir="./src" includes="german.yml"/>
<fileset dir="./src" includes="plugin.yml"/>
- <fileset dir="./src" includes="spanish.yml"/>
+ <fileset dir="./src" includes="spanish.yml"/>
+ <fileset dir="./src" includes="townyperms.yml"/>
<fileset dir="./src" includes="ToDo.txt"/>
</jar>
</target>
1  src/com/palmergames/bukkit/towny/Towny.java
View
@@ -85,6 +85,7 @@ public void onEnable() {
TownyFormatter.initialize(this);
TownyRegenAPI.initialize(this);
PlayerCacheUtil.initialize(this);
+ TownyPerms.initialize(this);
if (load()) {
// Setup bukkit command interfaces
2  src/com/palmergames/bukkit/towny/TownySettings.java
View
@@ -213,7 +213,7 @@ public static void loadLanguage(String filepath, String defaultRes) throws IOExc
String res = getString(ConfigNodes.LANGUAGE.getRoot(), defaultRes);
String fullPath = filepath + FileMgmt.fileSeparator() + res;
- File file = FileMgmt.unpackLanguageFile(fullPath, res, defaultRes);
+ File file = FileMgmt.unpackResourceFile(fullPath, res, defaultRes);
if (file != null) {
// read the (language).yml into memory
107 src/com/palmergames/bukkit/towny/command/NationCommand.java
View
@@ -31,6 +31,7 @@
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownyUniverse;
import com.palmergames.bukkit.towny.permissions.PermissionNodes;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.questioner.JoinNationTask;
import com.palmergames.bukkit.towny.questioner.ResidentNationQuestionTask;
import com.palmergames.bukkit.util.ChatTools;
@@ -164,7 +165,9 @@ else if (split[0].equalsIgnoreCase("withdraw")) {
} else {
String[] newSplit = StringMgmt.remFirstArg(split);
- if (split[0].equalsIgnoreCase("king"))
+ if (split[0].equalsIgnoreCase("rank"))
+ nationRank(player, newSplit);
+ else if (split[0].equalsIgnoreCase("king"))
nationKing(player, newSplit);
else if (split[0].equalsIgnoreCase("add"))
nationAdd(player, newSplit);
@@ -200,6 +203,102 @@ else if (split[0].equalsIgnoreCase("online")) {
}
}
}
+
+ public void nationRank(Player player, String[] split) {
+
+ if (split.length == 0) {
+ //Help output.
+ player.sendMessage(ChatTools.formatTitle("/nation rank"));
+ player.sendMessage(ChatTools.formatCommand("", "/nation rank", "add/remove [resident] rank", ""));
+
+ } else {
+
+ Resident resident, target;
+ Town town = null;
+ Town targetTown = null;
+ String rank;
+
+ /*
+ * Does the command have enough arguments?
+ */
+ if (split.length < 3) {
+ TownyMessaging.sendErrorMsg(player, "Eg: /town rank add/remove [resident] [rank]");
+ return;
+ }
+
+ try {
+ resident = TownyUniverse.getDataSource().getResident(player.getName());
+ target = TownyUniverse.getDataSource().getResident(split[1]);
+ town = resident.getTown();
+ targetTown = target.getTown();
+
+ if (town.getNation() != targetTown.getNation())
+ throw new TownyException("This resident is not a member of your Town!");
+
+ } catch (TownyException x) {
+ TownyMessaging.sendErrorMsg(player, x.getMessage());
+ return;
+ }
+
+ rank = split[2].toLowerCase();
+ /*
+ * Is this a known rank?
+ */
+ if (!TownyPerms.getNationRanks().contains(rank)) {
+ TownyMessaging.sendErrorMsg(player, "Unknown rank '" + rank + "'. Permissible ranks are :- " + StringMgmt.join(TownyPerms.getNationRanks(), ",") + ".");
+ return;
+ }
+ /*
+ * Only allow the player to assign ranks if they have the grant perm for it.
+ */
+ if (!TownyUniverse.getPermissionSource().has(player, "towny.nation.grant-" + rank)) {
+ TownyMessaging.sendErrorMsg(player, "You do not have permission to grant this rank.");
+ return;
+ }
+
+ if (split[0].equalsIgnoreCase("add")) {
+ try {
+ if (target.addNationRank(rank)) {
+ TownyMessaging.sendMsg(target, "You have been granted the Nation rank of '" + rank + "'.");
+ TownyMessaging.sendMsg(player, "You have granted the Nation rank of '" + rank + "' to " + target.getName() + ".");
+ } else {
+ // Not in a nation or Rank doesn't exist
+ TownyMessaging.sendErrorMsg(player, "That resident isn't a member of a town!");
+ return;
+ }
+ } catch (AlreadyRegisteredException e) {
+ // Must already have this rank
+ TownyMessaging.sendMsg(player, target.getName() + " already holds this Nation rank.");
+ return;
+ }
+
+ } else if (split[0].equalsIgnoreCase("remove")) {
+ try {
+ if (target.removeTownRank(rank)) {
+ TownyMessaging.sendMsg(target, "You have been demoted from the Nation rank of '" + rank + "'.");
+ TownyMessaging.sendMsg(player, "You have removed the Nation rank of '" + rank + "' from " + target.getName() + ".");
+ }
+ } catch (NotRegisteredException e) {
+ // Must already have this rank
+ TownyMessaging.sendMsg(player, target.getName() + " doesn't hold this Nation rank.");
+ return;
+ }
+
+
+ } else {
+ TownyMessaging.sendErrorMsg(player, String.format(TownySettings.getLangString("msg_err_invalid_property"), split[0]));
+ return;
+ }
+
+ /*
+ * If we got here we have made a change
+ * Save the altered resident data.
+ */
+ TownyUniverse.getDataSource().saveResident(target);
+
+ }
+
+ }
private void nationWithdraw(Player player, int amount) {
@@ -632,7 +731,8 @@ public void nationAssistantsAdd(Player player, Nation nation, List<Resident> inv
ArrayList<Resident> remove = new ArrayList<Resident>();
for (Resident newMember : invited)
try {
- nation.addAssistant(newMember);
+ //nation.addAssistant(newMember);
+ newMember.addNationRank("assistant");
plugin.deleteCache(newMember.getName());
TownyUniverse.getDataSource().saveResident(newMember);
} catch (AlreadyRegisteredException e) {
@@ -686,7 +786,8 @@ public void nationAssistantsRemove(Player player, Resident resident, Nation nati
ArrayList<Resident> remove = new ArrayList<Resident>();
for (Resident member : kicking)
try {
- nation.removeAssistant(member);
+ //nation.removeAssistant(member);
+ member.removeNationRank("assistant");
plugin.deleteCache(member.getName());
TownyUniverse.getDataSource().saveResident(member);
TownyUniverse.getDataSource().saveNation(nation);
123 src/com/palmergames/bukkit/towny/command/TownCommand.java
View
@@ -11,6 +11,7 @@
import com.palmergames.bukkit.towny.exceptions.*;
import com.palmergames.bukkit.towny.object.*;
import com.palmergames.bukkit.towny.permissions.PermissionNodes;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.questioner.JoinTownTask;
import com.palmergames.bukkit.towny.questioner.ResidentTownQuestionTask;
import com.palmergames.bukkit.towny.regen.PlotBlockData;
@@ -62,6 +63,7 @@
output.add(ChatTools.formatCommand("", "/town", "new [town]", TownySettings.getLangString("town_help_6")));
output.add(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/town", "new [town] " + TownySettings.getLangString("town_help_2"), TownySettings.getLangString("town_help_7")));
output.add(ChatTools.formatCommand(TownySettings.getLangString("res_sing"), "/town", "deposit [$]", ""));
+ output.add(ChatTools.formatCommand(TownySettings.getLangString("res_sing"), "/town", "rank add/remove [resident] [rank]", ""));
output.add(ChatTools.formatCommand(TownySettings.getLangString("mayor_sing"), "/town", "mayor ?", TownySettings.getLangString("town_help_8")));
output.add(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/town", "delete [town]", ""));
}
@@ -133,7 +135,9 @@ else if (split.length == 2)
} else {
String[] newSplit = StringMgmt.remFirstArg(split);
- if (split[0].equalsIgnoreCase("set"))
+ if (split[0].equalsIgnoreCase("rank"))
+ townRank(player, newSplit);
+ else if (split[0].equalsIgnoreCase("set"))
townSet(player, newSplit);
else if (split[0].equalsIgnoreCase("buy"))
townBuy(player, newSplit);
@@ -394,6 +398,100 @@ private void toggleTest(Player player, Town town, String split) throws TownyExce
}
}
+ public void townRank(Player player, String[] split) {
+
+ if (split.length == 0) {
+ //Help output.
+ player.sendMessage(ChatTools.formatTitle("/town rank"));
+ player.sendMessage(ChatTools.formatCommand("", "/town rank", "add/remove [resident] rank", ""));
+
+ } else {
+
+ Resident resident, target;
+ Town town = null;
+ String rank;
+
+ /*
+ * Does the command have enough arguments?
+ */
+ if (split.length < 3) {
+ TownyMessaging.sendErrorMsg(player, "Eg: /town rank add/remove [resident] [rank]");
+ return;
+ }
+
+ try {
+ resident = TownyUniverse.getDataSource().getResident(player.getName());
+ target = TownyUniverse.getDataSource().getResident(split[1]);
+ town = resident.getTown();
+
+ if (town != target.getTown())
+ throw new TownyException("This resident is not a member of your Town!");
+
+ } catch (TownyException x) {
+ TownyMessaging.sendErrorMsg(player, x.getMessage());
+ return;
+ }
+
+ rank = split[2].toLowerCase();
+ /*
+ * Is this a known rank?
+ */
+ if (!TownyPerms.getTownRanks().contains(rank)) {
+ TownyMessaging.sendErrorMsg(player, "Unknown rank '" + rank + "'. Permissible ranks are :- " + StringMgmt.join(TownyPerms.getTownRanks(), ",") + ".");
+ return;
+ }
+ /*
+ * Only allow the player to assign ranks if they have the grant perm for it.
+ */
+ if (!TownyUniverse.getPermissionSource().has(player, "towny.town.grant-" + rank)) {
+ TownyMessaging.sendErrorMsg(player, "You do not have permission to grant this rank.");
+ return;
+ }
+
+ if (split[0].equalsIgnoreCase("add")) {
+ try {
+ if (target.addTownRank(rank)) {
+ TownyMessaging.sendMsg(target, "You have been granted the Town rank of '" + rank + "'.");
+ TownyMessaging.sendMsg(player, "You have granted the Town rank of '" + rank + "' to " + target.getName() + ".");
+ } else {
+ // Not in a town or Rank doesn't exist
+ TownyMessaging.sendErrorMsg(player, "That resident isn't a member of a town!");
+ return;
+ }
+ } catch (AlreadyRegisteredException e) {
+ // Must already have this rank
+ TownyMessaging.sendMsg(player, target.getName() + " already holds this Town rank.");
+ return;
+ }
+
+ } else if (split[0].equalsIgnoreCase("remove")) {
+ try {
+ if (target.removeTownRank(rank)) {
+ TownyMessaging.sendMsg(target, "You have been demoted from the Town rank of '" + rank + "'.");
+ TownyMessaging.sendMsg(player, "You have removed the Town rank of '" + rank + "' from " + target.getName() + ".");
+ }
+ } catch (NotRegisteredException e) {
+ // Must already have this rank
+ TownyMessaging.sendMsg(player, target.getName() + " doesn't hold this Town rank.");
+ return;
+ }
+
+
+ } else {
+ TownyMessaging.sendErrorMsg(player, String.format(TownySettings.getLangString("msg_err_invalid_property"), split[0]));
+ return;
+ }
+
+ /*
+ * If we got here we have made a change
+ * Save the altered resident data.
+ */
+ TownyUniverse.getDataSource().saveResident(target);
+
+ }
+
+ }
+
public void townSet(Player player, String[] split) {
if (split.length == 0) {
@@ -1358,16 +1456,20 @@ public void townAssistantsAdd(Player player, Town town, List<Resident> invited)
//TODO: change variable names from townAdd copypasta
ArrayList<Resident> remove = new ArrayList<Resident>();
for (Resident newMember : invited)
- try {
- town.addAssistant(newMember);
- plugin.deleteCache(newMember.getName());
- TownyUniverse.getDataSource().saveResident(newMember);
- } catch (AlreadyRegisteredException e) {
- remove.add(newMember);
- } catch (NotRegisteredException e) {
+ if (town.hasResident(newMember)) {
+ try {
+ //town.addAssistant(newMember);
+ newMember.addTownRank("assistant");
+ plugin.deleteCache(newMember.getName());
+ TownyUniverse.getDataSource().saveResident(newMember);
+ } catch (AlreadyRegisteredException e) {
+ remove.add(newMember);
+ }
+ } else {
remove.add(newMember);
- TownyMessaging.sendErrorMsg(player, e.getMessage());
+ TownyMessaging.sendErrorMsg(player, newMember.getName() + " doesn't belong to your town.");
}
+
for (Resident newMember : remove)
invited.remove(newMember);
@@ -1416,7 +1518,8 @@ public void townAssistantsRemove(Player player, Resident resident, Town town, Li
for (Resident member : toKick)
try {
- town.removeAssistant(member);
+ //town.removeAssistant(member);
+ member.removeTownRank("assistant");
plugin.deleteCache(member.getName());
TownyUniverse.getDataSource().saveResident(member);
TownyUniverse.getDataSource().saveTown(town);
58 src/com/palmergames/bukkit/towny/db/TownyFlatFileSource.java
View
@@ -14,6 +14,7 @@
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
@@ -464,6 +465,14 @@ public boolean loadResident(Resident resident) {
line = kvFile.get("town");
if (line != null)
resident.setTown(getTown(line));
+
+ line = kvFile.get("town-ranks");
+ if (line != null)
+ resident.setTownRanks(new ArrayList<String>(Arrays.asList((line.split(",")))));
+
+ line = kvFile.get("nation-ranks");
+ if (line != null)
+ resident.setNationRanks(new ArrayList<String>(Arrays.asList((line.split(",")))));
line = kvFile.get("friends");
if (line != null) {
@@ -522,17 +531,17 @@ public boolean loadTown(Town town) {
if (line != null)
town.setMayor(getResident(line));
- line = kvFile.get("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- if (!token.isEmpty()) {
- Resident assistant = getResident(token);
- if ((assistant != null) && (town.hasResident(assistant)))
- town.addAssistant(assistant);
- }
- }
- }
+// line = kvFile.get("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// if (!token.isEmpty()) {
+// Resident assistant = getResident(token);
+// if ((assistant != null) && (town.hasResident(assistant)))
+// town.addAssistant(assistant);
+// }
+// }
+// }
town.setTownBoard(kvFile.get("townBoard"));
@@ -800,17 +809,17 @@ public boolean loadNation(Nation nation) {
if (line != null)
nation.setCapital(getTown(line));
- line = kvFile.get("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- if (!token.isEmpty()) {
- Resident assistant = getResident(token);
- if (assistant != null)
- nation.addAssistant(assistant);
- }
- }
- }
+// line = kvFile.get("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// if (!token.isEmpty()) {
+// Resident assistant = getResident(token);
+// if (assistant != null)
+// nation.addAssistant(assistant);
+// }
+// }
+// }
line = kvFile.get("tag");
if (line != null)
@@ -1393,8 +1402,11 @@ public boolean saveResident(Resident resident) {
fout.write("title=" + resident.getTitle() + newLine);
// surname
fout.write("surname=" + resident.getSurname() + newLine);
- if (resident.hasTown())
+ if (resident.hasTown()) {
fout.write("town=" + resident.getTown().getName() + newLine);
+ fout.write("town-ranks=" + StringMgmt.join(resident.getTownRanks(), ",") + newLine);
+ fout.write("nation-ranks=" + StringMgmt.join(resident.getNationRanks(), ",") + newLine);
+ }
// Friends
fout.write("friends=");
for (Resident friend : resident.getFriends())
36 src/com/palmergames/bukkit/towny/db/TownyHModFlatFileSource.java
View
@@ -202,15 +202,15 @@ public boolean loadTown(Town town) {
if (line != null)
town.setMayor(getResident(line));
- line = kvFile.get("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- Resident assistant = getResident(token);
- if (assistant != null)
- town.addAssistant(assistant);
- }
- }
+// line = kvFile.get("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// Resident assistant = getResident(token);
+// if (assistant != null)
+// town.addAssistant(assistant);
+// }
+// }
town.setTownBoard(kvFile.get("townBoard"));
@@ -322,15 +322,15 @@ public boolean loadNation(Nation nation) {
line = kvFile.get("capital");
nation.setCapital(getTown(line));
- line = kvFile.get("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- Resident assistant = getResident(token);
- if (assistant != null)
- nation.addAssistant(assistant);
- }
- }
+// line = kvFile.get("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// Resident assistant = getResident(token);
+// if (assistant != null)
+// nation.addAssistant(assistant);
+// }
+// }
line = kvFile.get("allies");
if (line != null) {
88 src/com/palmergames/bukkit/towny/db/TownySQLSource.java
View
@@ -178,6 +178,8 @@ public void initialize(Towny plugin, TownyUniverse universe) {
String resident_create = "CREATE TABLE IF NOT EXISTS " + tb_prefix + "RESIDENTS ("
+ " `name` VARCHAR(16) NOT NULL,"
+ "`town` mediumtext,"
+ + "`town-ranks` mediumtext,"
+ + "`nation-ranks` mediumtext,"
+ "`lastOnline` BIGINT NOT NULL,"
+ "`registered` BIGINT NOT NULL,"
+ "`isNPC` bool NOT NULL DEFAULT '0',"
@@ -195,6 +197,28 @@ public void initialize(Towny plugin, TownyUniverse universe) {
} catch (SQLException ee) {
TownyMessaging.sendErrorMsg("Error Creating table RESIDENTS :" + ee.getMessage());
}
+
+ /*
+ * Update the table structure for older databases.
+ */
+ String resident_update = "IF EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS "
+ + "WHERE table_name = '" + tb_prefix + "RESIDENTS' "
+ + "AND table_schema = '" + db_name + "' "
+ + "AND column_name != 'town-ranks') THEN "
+ + "ALTER TABLE " + tb_prefix + "RESIDENTS (ADD "
+ + "`town-ranks` mediumtext,"
+ + "`nation-ranks` mediumtext"
+ + ");";
+
+ try {
+ Statement s = cntx.createStatement();
+ s.executeUpdate(resident_update);
+ TownyMessaging.sendDebugMsg("Table RESIDENTS is updated!");
+ } catch (SQLException ee) {
+ TownyMessaging.sendErrorMsg("Error updating table RESIDENTS :" + ee.getMessage());
+ }
+
+
String nation_create = "CREATE TABLE IF NOT EXISTS " + tb_prefix + "NATIONS ("
+ "`name` VARCHAR(32) NOT NULL,"
@@ -599,7 +623,19 @@ public boolean loadResident(Resident resident) {
String line = rs.getString("town");
if ((line != null) && (!line.isEmpty())) {
resident.setTown(getTown(line));
- TownyMessaging.sendDebugMsg("Resident " + resident.getName() + " set to Town " + rs.getString("town"));
+ TownyMessaging.sendDebugMsg("Resident " + resident.getName() + " set to Town " + line);
+ }
+
+ line = rs.getString("town-rank");
+ if ((line != null) && (!line.isEmpty())) {
+ resident.setTownRanks(new ArrayList<String>(Arrays.asList((line.split(",")))));
+ TownyMessaging.sendDebugMsg("Resident " + resident.getName() + " set Town-ranks " + line);
+ }
+
+ line = rs.getString("nation-rank");
+ if ((line != null) && (!line.isEmpty())) {
+ resident.setNationRanks(new ArrayList<String>(Arrays.asList((line.split(",")))));
+ TownyMessaging.sendDebugMsg("Resident " + resident.getName() + " set Nation-ranks " + line);
}
try {
@@ -651,7 +687,7 @@ public boolean loadTown(Town town) {
try {
Statement s = cntx.createStatement();
- ResultSet rs = s.executeQuery("SELECT " + "residents,mayor,assistants,townBoard,nation,tag,protectionStatus,bonus,purchased,plotPrice,hasUpkeep,taxpercent,taxes" + ",plotTax,commercialPlotPrice,commercialPlotTax,embassyPlotPrice,embassyPlotTax" + ",open,public,townBlocks,homeBlock,spawn,outpostSpawns" + " FROM " + tb_prefix + "TOWNS " + " WHERE name='" + town.getName() + "'");
+ ResultSet rs = s.executeQuery("SELECT " + "residents,mayor,townBoard,nation,tag,protectionStatus,bonus,purchased,plotPrice,hasUpkeep,taxpercent,taxes" + ",plotTax,commercialPlotPrice,commercialPlotTax,embassyPlotPrice,embassyPlotTax" + ",open,public,townBlocks,homeBlock,spawn,outpostSpawns" + " FROM " + tb_prefix + "TOWNS " + " WHERE name='" + town.getName() + "'");
while (rs.next()) {
@@ -667,17 +703,17 @@ public boolean loadTown(Town town) {
}
}
town.setMayor(getResident(rs.getString("mayor")));
- line = rs.getString("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- if (!token.isEmpty()) {
- Resident assistant = getResident(token);
- if ((assistant != null) && (town.hasResident(assistant)))
- town.addAssistant(assistant);
- }
- }
- }
+// line = rs.getString("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// if (!token.isEmpty()) {
+// Resident assistant = getResident(token);
+// if ((assistant != null) && (town.hasResident(assistant)))
+// town.addAssistant(assistant);
+// }
+// }
+// }
town.setTownBoard(rs.getString("townBoard"));
line = rs.getString("tag");
if (line != null)
@@ -803,7 +839,7 @@ public boolean loadNation(Nation nation) {
return false;
try {
Statement s = cntx.createStatement();
- ResultSet rs = s.executeQuery("SELECT towns,capital,assistants,tag,allies,enemies,taxes,neutral FROM " + tb_prefix + "NATIONS WHERE name='" + nation.getName() + "'");
+ ResultSet rs = s.executeQuery("SELECT towns,capital,tag,allies,enemies,taxes,neutral FROM " + tb_prefix + "NATIONS WHERE name='" + nation.getName() + "'");
while (rs.next()) {
line = rs.getString("towns");
@@ -818,17 +854,17 @@ public boolean loadNation(Nation nation) {
}
}
nation.setCapital(getTown(rs.getString("capital")));
- line = rs.getString("assistants");
- if (line != null) {
- tokens = line.split(",");
- for (String token : tokens) {
- if (!token.isEmpty()) {
- Resident assistant = getResident(token);
- if (assistant != null)
- nation.addAssistant(assistant);
- }
- }
- }
+// line = rs.getString("assistants");
+// if (line != null) {
+// tokens = line.split(",");
+// for (String token : tokens) {
+// if (!token.isEmpty()) {
+// Resident assistant = getResident(token);
+// if (assistant != null)
+// nation.addAssistant(assistant);
+// }
+// }
+// }
nation.setTag(rs.getString("tag"));
@@ -1231,6 +1267,8 @@ public synchronized boolean saveResident(Resident resident) {
res_hm.put("title", resident.getTitle());
res_hm.put("surname", resident.getSurname());
res_hm.put("town", resident.hasTown() ? resident.getTown().getName() : "");
+ res_hm.put("town-ranks", resident.hasTown() ? StringMgmt.join(resident.getTownRanks(), ",") : "");
+ res_hm.put("nation-ranks", resident.hasTown() ? StringMgmt.join(resident.getNationRanks(), ",") : "");
String fstr = "";
for (Resident friend : resident.getFriends())
fstr += friend.getName() + ",";
8 src/com/palmergames/bukkit/towny/listeners/TownyPlayerListener.java
View
@@ -10,6 +10,7 @@
import com.palmergames.bukkit.towny.object.*;
import com.palmergames.bukkit.towny.object.PlayerCache.TownBlockStatus;
import com.palmergames.bukkit.towny.permissions.PermissionNodes;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.regen.TownyRegenAPI;
import com.palmergames.bukkit.towny.regen.block.BlockLocation;
import com.palmergames.bukkit.towny.utils.PlayerCacheUtil;
@@ -80,6 +81,7 @@ public void onPlayerQuit(PlayerQuitEvent event) {
}
plugin.deleteCache(event.getPlayer());
+ TownyPerms.removeAttachment(event.getPlayer().getName());
}
@EventHandler(priority = EventPriority.NORMAL)
@@ -305,6 +307,12 @@ public void onPlayerTeleport(PlayerTeleportEvent event) {
}
onPlayerMove(event);
}
+
+ @EventHandler(priority = EventPriority.LOWEST)
+ public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { // has changed worlds
+
+ TownyPerms.assignPermissions(null, event.getPlayer());
+ }
public boolean onPlayerInteract(Player player, Block block, ItemStack item) {
96 src/com/palmergames/bukkit/towny/object/Nation.java
View
@@ -2,6 +2,7 @@
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.exceptions.*;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.war.flagwar.TownyWar;
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.util.StringMgmt;
@@ -15,7 +16,7 @@
private static final String ECONOMY_ACCOUNT_PREFIX = "nation-";
- private List<Resident> assistants = new ArrayList<Resident>();
+ //private List<Resident> assistants = new ArrayList<Resident>();
private List<Town> towns = new ArrayList<Town>();
private List<Nation> allies = new ArrayList<Nation>();
private List<Nation> enemies = new ArrayList<Nation>();
@@ -175,25 +176,26 @@ else if (town.hasNation())
}
}
- public void addAssistant(Resident resident) throws AlreadyRegisteredException {
+// public void addAssistant(Resident resident) throws AlreadyRegisteredException {
+//
+// if (hasAssistant(resident))
+// throw new AlreadyRegisteredException();
+// else
+// getAssistants().add(resident);
+// }
- if (hasAssistant(resident))
- throw new AlreadyRegisteredException();
- else
- getAssistants().add(resident);
- }
-
- public void removeAssistant(Resident resident) throws NotRegisteredException {
-
- if (!hasAssistant(resident))
- throw new NotRegisteredException();
- else
- assistants.remove(resident);
- }
+// public void removeAssistant(Resident resident) throws NotRegisteredException {
+//
+// if (!hasAssistant(resident))
+// throw new NotRegisteredException();
+// else
+// assistants.remove(resident);
+// }
public void setCapital(Town capital) {
this.capital = capital;
+ TownyPerms.assignPermissions(capital.getMayor(), null);
}
public Town getCapital() {
@@ -230,13 +232,20 @@ public boolean setAliegeance(String type, Nation nation) {
return false;
}
- public void setAssistants(List<Resident> assistants) {
-
- this.assistants = assistants;
- }
-
+// public void setAssistants(List<Resident> assistants) {
+//
+// this.assistants = assistants;
+// }
+//
public List<Resident> getAssistants() {
+ List<Resident> assistants = new ArrayList<Resident>();
+
+ for (Town town: towns)
+ for (Resident assistant: town.getResidents()) {
+ if (assistant.hasNationRank("assistant"))
+ assistants.add(assistant);
+ }
return assistants;
}
@@ -303,7 +312,7 @@ public void removeTown(Town town) throws EmptyNationException, NotRegisteredExce
private void remove(Town town) {
- removeAssistantsIn(town);
+ //removeAssistantsIn(town);
try {
town.setNation(null);
} catch (AlreadyRegisteredException e) {
@@ -317,23 +326,23 @@ private void removeAllTowns() {
remove(town);
}
- public boolean hasAssistantIn(Town town) {
-
- for (Resident resident : town.getResidents())
- if (hasAssistant(resident))
- return true;
- return false;
- }
-
- private void removeAssistantsIn(Town town) {
-
- for (Resident resident : new ArrayList<Resident>(town.getResidents()))
- if (hasAssistant(resident))
- try {
- removeAssistant(resident);
- } catch (NotRegisteredException e) {
- }
- }
+// public boolean hasAssistantIn(Town town) {
+//
+// for (Resident resident : town.getResidents())
+// if (hasAssistant(resident))
+// return true;
+// return false;
+// }
+//
+// private void removeAssistantsIn(Town town) {
+//
+// for (Resident resident : new ArrayList<Resident>(town.getResidents()))
+// if (hasAssistant(resident))
+// try {
+// removeAssistant(resident);
+// } catch (NotRegisteredException e) {
+// }
+// }
public void setTaxes(double taxes) {
@@ -356,7 +365,7 @@ public void clear() {
removeAllEnemies();
removeAllTowns();
capital = null;
- assistants.clear();
+ //assistants.clear();
}
public void setNeutral(boolean neutral) throws TownyException {
@@ -397,7 +406,7 @@ public boolean hasResident(Resident resident) {
public void withdrawFromBank(Resident resident, int amount) throws EconomyException, TownyException {
- if (!isKing(resident) && !hasAssistant(resident))
+ if (!isKing(resident))// && !hasAssistant(resident))
throw new TownyException(TownySettings.getLangString("msg_no_access_nation_bank"));
if (TownySettings.isUsingEconomy()) {
@@ -422,8 +431,11 @@ public void withdrawFromBank(Resident resident, int amount) throws EconomyExcept
List<String> out = new ArrayList<String>();
out.add(getTreeDepth(depth) + "Nation (" + getName() + ")");
out.add(getTreeDepth(depth + 1) + "Capital: " + getCapital().getName());
- if (getAssistants().size() > 0)
- out.add(getTreeDepth(depth + 1) + "Assistants (" + getAssistants().size() + "): " + Arrays.toString(getAssistants().toArray(new Resident[0])));
+
+ List<Resident> assistants = getAssistants();
+
+ if (assistants.size() > 0)
+ out.add(getTreeDepth(depth + 1) + "Assistants (" + assistants.size() + "): " + Arrays.toString(assistants.toArray(new Resident[0])));
if (getAllies().size() > 0)
out.add(getTreeDepth(depth + 1) + "Allies (" + getAllies().size() + "): " + Arrays.toString(getAllies().toArray(new Nation[0])));
if (getEnemies().size() > 0)
92 src/com/palmergames/bukkit/towny/object/Resident.java
View
@@ -5,6 +5,7 @@
import com.palmergames.bukkit.towny.exceptions.EmptyTownException;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.exceptions.TownyException;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.regen.TownyRegenAPI;
import com.palmergames.bukkit.towny.tasks.SetDefaultModes;
import com.palmergames.bukkit.util.BukkitTools;
@@ -30,6 +31,9 @@
private double teleportCost;
private String chatFormattedName;
private List<String> modes = new ArrayList<String>();
+
+ private List<String> townRanks = new ArrayList<String>();
+ private List<String> nationRanks = new ArrayList<String>();
public Resident(String name) {
@@ -136,15 +140,20 @@ public void setTown(Town town) throws AlreadyRegisteredException {
this.town = null;
setTitle("");
setSurname("");
+ updatePerms();
return;
}
+
if (this.town == town)
return;
+
if (hasTown())
throw new AlreadyRegisteredException();
+
this.town = town;
setTitle("");
setSurname("");
+ updatePerms();
}
public void setFriends(List<Resident> newFriends) {
@@ -197,9 +206,16 @@ public void clear() throws EmptyTownException {
town.removeResident(this);
setTitle("");
setSurname("");
+ updatePerms();
} catch (NotRegisteredException e) {
}
}
+
+ private void updatePerms() {
+ setTownRanks(new ArrayList<String>());
+ setNationRanks(new ArrayList<String>());
+ TownyPerms.assignPermissions(this, null);
+ }
public void setRegistered(long registered) {
@@ -361,6 +377,82 @@ public void clearModes() {
TownyMessaging.sendErrorMsg("Could not set default modes for " + getName() + ".");
}
+
+
+ public boolean addTownRank(String rank) throws AlreadyRegisteredException {
+
+ if (this.hasTown() && TownyPerms.getTownRanks().contains(rank)) {
+ if (townRanks.contains(rank))
+ throw new AlreadyRegisteredException();
+
+ townRanks.add(rank);
+ TownyPerms.assignPermissions(this, null);
+ return true;
+ }
+
+ return false;
+ }
+
+ public void setTownRanks(List<String> ranks) {
+ townRanks.addAll(ranks);
+ }
+
+ public boolean hasTownRank(String rank) {
+ return townRanks.contains(rank.toLowerCase());
+ }
+
+ public List<String> getTownRanks() {
+ return townRanks;
+ }
+
+ public boolean removeTownRank(String rank) throws NotRegisteredException {
+
+ if (townRanks.contains(rank)) {
+ townRanks.remove(rank);
+ TownyPerms.assignPermissions(this, null);
+ return true;
+ }
+
+ throw new NotRegisteredException();
+ }
+
+ public boolean addNationRank(String rank) throws AlreadyRegisteredException {
+
+ if (this.hasNation() && TownyPerms.getNationRanks().contains(rank)) {
+ if (nationRanks.contains(rank))
+ throw new AlreadyRegisteredException();
+
+ nationRanks.add(rank);
+ TownyPerms.assignPermissions(this, null);
+ return true;
+ }
+
+ return false;
+ }
+
+ public void setNationRanks(List<String> ranks) {
+ nationRanks.addAll(ranks);
+ }
+
+ public boolean hasNationRank(String rank) {
+ return nationRanks.contains(rank.toLowerCase());
+ }
+
+ public List<String> getNationRanks() {
+ return nationRanks;
+ }
+
+ public boolean removeNationRank(String rank) throws NotRegisteredException {
+
+ if (nationRanks.contains(rank)) {
+ nationRanks.remove(rank);
+ TownyPerms.assignPermissions(this, null);
+ return true;
+ }
+
+ throw new NotRegisteredException();
+
+ }
@Override
protected World getBukkitWorld() {
80 src/com/palmergames/bukkit/towny/object/Town.java
View
@@ -2,6 +2,7 @@
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.exceptions.*;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.bukkit.wallgen.Wall;
import com.palmergames.bukkit.wallgen.WallSection;
@@ -20,7 +21,7 @@
private static final String ECONOMY_ACCOUNT_PREFIX = "town-";
private List<Resident> residents = new ArrayList<Resident>();
- private List<Resident> assistants = new ArrayList<Resident>();
+ //private List<Resident> assistants = new ArrayList<Resident>();
private List<Location> outpostSpawns = new ArrayList<Location>();
private Wall wall = new Wall();
private Resident mayor;
@@ -129,6 +130,7 @@ public void setNation(Nation nation) throws AlreadyRegisteredException {
if (nation == null) {
this.nation = null;
+ TownyPerms.updateTownPerms(this);
return;
}
if (this.nation == nation)
@@ -136,6 +138,7 @@ public void setNation(Nation nation) throws AlreadyRegisteredException {
if (hasNation())
throw new AlreadyRegisteredException();
this.nation = nation;
+ TownyPerms.updateTownPerms(this);
}
@Override
@@ -146,6 +149,12 @@ public void setNation(Nation nation) throws AlreadyRegisteredException {
public List<Resident> getAssistants() {
+ List<Resident> assistants = new ArrayList<Resident>();
+
+ for (Resident assistant: residents) {
+ if (assistant.hasTownRank("assistant"))
+ assistants.add(assistant);
+ }
return assistants;
}
@@ -165,7 +174,7 @@ public boolean hasResident(Resident resident) {
public boolean hasAssistant(Resident resident) {
- return assistants.contains(resident);
+ return getAssistants().contains(resident);
}
public void addResident(Resident resident) throws AlreadyRegisteredException {
@@ -189,16 +198,16 @@ else if (resident.hasTown())
}
}
- public void addAssistant(Resident resident) throws AlreadyRegisteredException, NotRegisteredException {
-
- if (hasAssistant(resident))
- throw new AlreadyRegisteredException();
-
- if (!hasResident(resident))
- throw new NotRegisteredException(resident.getName() + " doesn't belong to your town.");
-
- assistants.add(resident);
- }
+// public void addAssistant(Resident resident) throws AlreadyRegisteredException, NotRegisteredException {
+//
+// if (hasAssistant(resident))
+// throw new AlreadyRegisteredException();
+//
+// if (!hasResident(resident))
+// throw new NotRegisteredException(resident.getName() + " doesn't belong to your town.");
+//
+// assistants.add(resident);
+// }
public boolean isMayor(Resident resident) {
@@ -457,7 +466,7 @@ private void remove(Resident resident) {
if (residents.size() > 1) {
for (Resident assistant : new ArrayList<Resident>(getAssistants()))
- if (assistant != resident) {
+ if ((assistant != resident) && (resident.hasTownRank("assistant"))) {
try {
setMayor(assistant);
continue;
@@ -483,16 +492,16 @@ private void remove(Resident resident) {
}
- if (hasNation() && nation.hasAssistant(resident))
- try {
- nation.removeAssistant(resident);
- } catch (NotRegisteredException e) {
- }
- if (hasAssistant(resident))
- try {
- removeAssistant(resident);
- } catch (NotRegisteredException e) {
- }
+// if (hasNation() && nation.hasAssistant(resident))
+// try {
+// nation.removeAssistant(resident);
+// } catch (NotRegisteredException e) {
+// }
+// if (hasAssistant(resident))
+// try {
+// removeAssistant(resident);
+// } catch (NotRegisteredException e) {
+// }
try {
resident.setTown(null);
@@ -501,13 +510,13 @@ private void remove(Resident resident) {
residents.remove(resident);
}
- public void removeAssistant(Resident resident) throws NotRegisteredException {
-
- if (!hasAssistant(resident))
- throw new NotRegisteredException();
- else
- assistants.remove(resident);
- }
+// public void removeAssistant(Resident resident) throws NotRegisteredException {
+//
+// if (!hasAssistant(resident))
+// throw new NotRegisteredException();
+// else
+// assistants.remove(resident);
+// }
public void setSpawn(Location spawn) throws TownyException {
@@ -548,7 +557,7 @@ public void clear() throws EmptyNationException {
removeAllResidents();
mayor = null;
residents.clear();
- assistants.clear();
+ //assistants.clear();
homeBlock = null;
outpostSpawns.clear();
@@ -802,7 +811,7 @@ public boolean isOpen() {
public void withdrawFromBank(Resident resident, int amount) throws EconomyException, TownyException {
- if (!isMayor(resident) && !hasAssistant(resident))
+ if (!isMayor(resident))// && !hasAssistant(resident))
throw new TownyException("You don't have access to the town's bank.");
if (TownySettings.isUsingEconomy()) {
@@ -827,8 +836,11 @@ public void withdrawFromBank(Resident resident, int amount) throws EconomyExcept
* (
* )
*/);
- if (getAssistants().size() > 0)
- out.add(getTreeDepth(depth + 1) + "Assistants (" + getAssistants().size() + "): " + Arrays.toString(getAssistants().toArray(new Resident[0])));
+ List<Resident> assistants = getAssistants();
+
+ if (assistants.size() > 0)
+ out.add(getTreeDepth(depth + 1) + "Assistants (" + assistants.size() + "): " + Arrays.toString(assistants.toArray(new Resident[0])));
+
out.add(getTreeDepth(depth + 1) + "Residents (" + getResidents().size() + "):");
for (Resident resident : getResidents())
out.addAll(resident.getTreeString(depth + 2));
2  src/com/palmergames/bukkit/towny/object/TownyUniverse.java
View
@@ -11,6 +11,7 @@
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.exceptions.TownyException;
import com.palmergames.bukkit.towny.permissions.TownyPermissionSource;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.towny.regen.TownyRegenAPI;
import com.palmergames.bukkit.towny.tasks.OnPlayerLogin;
import com.palmergames.bukkit.towny.tasks.TeleportWarmupTimerTask;
@@ -249,6 +250,7 @@ public boolean loadSettings() {
TownySettings.loadConfig(getRootFolder() + FileMgmt.fileSeparator() + "settings" + FileMgmt.fileSeparator() + "config.yml", plugin.getVersion());
TownySettings.loadLanguage(getRootFolder() + FileMgmt.fileSeparator() + "settings", "english.yml");
+ TownyPerms.loadPerms(getRootFolder() + FileMgmt.fileSeparator() + "settings", "townyperms.yml");
} catch (FileNotFoundException e) {
e.printStackTrace();
519 src/com/palmergames/bukkit/towny/permissions/TownyPerms.java
View
@@ -0,0 +1,519 @@
+/**
+ *
+ */
+package com.palmergames.bukkit.towny.permissions;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.bukkit.configuration.MemorySection;
+import org.bukkit.entity.Player;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionAttachment;
+
+import com.palmergames.bukkit.config.CommentedConfiguration;
+import com.palmergames.bukkit.towny.Towny;
+import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
+import com.palmergames.bukkit.towny.object.Nation;
+import com.palmergames.bukkit.towny.object.Resident;
+import com.palmergames.bukkit.towny.object.Town;
+import com.palmergames.bukkit.towny.object.TownyUniverse;
+import com.palmergames.bukkit.towny.object.TownyWorld;
+import com.palmergames.bukkit.util.BukkitTools;
+import com.palmergames.util.FileMgmt;
+import com.palmergames.util.StringMgmt;
+
+/**
+ * @author ElgarL
+ *
+ */
+public class TownyPerms {
+
+ protected static LinkedHashMap<String, Permission> registeredPermissions = new LinkedHashMap<String, Permission>();
+ protected static HashMap<String, PermissionAttachment> attachments = new HashMap<String, PermissionAttachment>();
+ private static CommentedConfiguration perms;
+ private static Towny plugin;
+
+ public static void initialize(Towny plugin) {
+ TownyPerms.plugin = plugin;
+ }
+
+ private static Field permissions;
+
+ // Setup reflection (Thanks to Codename_B for the reflection source)
+ static {
+ try {
+ permissions = PermissionAttachment.class.getDeclaredField("permissions");
+ permissions.setAccessible(true);
+ } catch (SecurityException e) {
+ e.printStackTrace();
+ } catch (NoSuchFieldException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Load the townyperms.yml file.
+ * If it doesn't exist create it from the resource file in the jar.
+ *
+ * @param filepath
+ * @param defaultRes
+ * @throws IOException
+ */
+ public static void loadPerms(String filepath, String defaultRes) throws IOException {
+
+ String fullPath = filepath + FileMgmt.fileSeparator() + defaultRes;
+
+ File file = FileMgmt.unpackResourceFile(fullPath, defaultRes, defaultRes);
+ if (file != null) {
+ // read the (language).yml into memory
+ perms = new CommentedConfiguration(file);
+ perms.load();
+ }
+
+ /*
+ * Only do this once as we are really only interested in Towny perms.
+ */
+ collectPermissions();
+
+ System.out.println(StringMgmt.join(getTownRanks(),","));
+ }
+
+ /**
+ * Register a specific residents permissions with Bukkit.
+ *
+ * @param resident
+ */
+ public static void assignPermissions(Resident resident, Player player) {
+
+ PermissionAttachment playersAttachment= null;
+
+ if (resident == null) {
+ try {
+ resident = TownyUniverse.getDataSource().getResident(player.getName());
+ } catch (NotRegisteredException e) {
+ // failed to get resident
+ e.printStackTrace();
+ return;
+ }
+ } else {
+ player = BukkitTools.getPlayer(resident.getName());
+ }
+
+ /*
+ * Find the current attachment
+ * or create a new one (if the player is online)
+ */
+
+ if ((player == null) || !player.isOnline()) {
+ attachments.remove(resident.getName());
+ return;
+ }
+
+ TownyWorld World = null;
+
+ try {
+ World = TownyUniverse.getDataSource().getWorld(player.getLocation().getWorld().getName());
+ } catch (NotRegisteredException e) {
+ // World not registered with Towny.
+ e.printStackTrace();
+ return;
+ }
+
+ if (attachments.containsKey(resident.getName())) {
+ playersAttachment = attachments.get(resident.getName());
+ } else
+ playersAttachment = BukkitTools.getPlayer(resident.getName()).addAttachment(plugin);
+
+ /*
+ * Set all our Towny default permissions using reflection else
+ * bukkit will perform a recalculation of perms for each addition.
+ */
+
+ try {
+ @SuppressWarnings("unchecked")
+ Map<String, Boolean> orig = (Map<String, Boolean>) permissions.get(playersAttachment);
+ /*
+ * Clear the map (faster than removing the attachment and recalculating)
+ */
+ orig.clear();
+
+ if (World.isUsingTowny()) {
+ /*
+ * Fill with the fresh perm nodes
+ */
+ orig.putAll(TownyPerms.getResidentPerms(resident));
+
+ //System.out.print("Perms set for: " + resident.getName());
+ }
+ /*
+ * Tell bukkit to update it's permissions
+ */
+ playersAttachment.getPermissible().recalculatePermissions();
+ } catch (IllegalArgumentException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+
+ /*
+ * Store the attachment for future reference
+ */
+ attachments.put(resident.getName(), playersAttachment);
+
+ }
+
+ /**
+ * Should only be called when a player leaves the server.
+ *
+ * @param name
+ */
+ public static void removeAttachment(String name) {
+
+ if (attachments.containsKey(name))
+ attachments.remove(name);
+
+ }
+
+ /**
+ * Update the permissions for all residents of a town (if online)
+ *
+ * @param town
+ */
+ public static void updateTownPerms(Town town) {
+
+ for (Resident resident: town.getResidents())
+ assignPermissions(resident, null);
+
+ }
+
+ /**
+ * Update the permissions for all residents of a nation (if online)
+ *
+ * @param nation
+ */
+ public static void updateNationPerms(Nation nation) {
+
+ for (Town town: nation.getTowns())
+ updateTownPerms(town);
+
+ }
+
+ /**
+ * Fetch a list of permission nodes
+ *
+ * @param path
+ * @return a List of permission nodes.
+ */
+ private static List<String> getList(String path) {
+
+ if (perms.contains(path)) {
+ return perms.getStringList(path);
+ }
+ return null;
+ }
+
+ /**
+ * Returns a sorted map of this residents current permissions.
+ *
+ * @param resident
+ * @return a sorted Map of permission nodes
+ */
+ public static LinkedHashMap<String, Boolean> getResidentPerms(Resident resident) {
+
+ Set<String> permList = new HashSet<String>();
+
+ // Start by adding the default perms everyone gets
+ permList.addAll(getDefault());
+
+ //Check for town membership
+ if (resident.hasTown()) {
+ permList.addAll(getTownDefault());
+ // Is Mayor?
+ if (resident.isMayor()) permList.addAll(getTownMayor());
+
+ //Add town ranks here
+ for (String rank: resident.getTownRanks()) {
+ permList.addAll(getTownRank(rank));
+ }
+
+ //Check for nation membership
+ if (resident.hasNation()) {
+ permList.addAll(getNationDefault());
+ // Is King?
+ if (resident.isKing()) permList.addAll(getNationKing());
+
+ //Add nation ranks here
+ for (String rank: resident.getNationRanks()) {
+ permList.addAll(getNationRank(rank));
+ }
+ }
+ }
+
+ List<String> playerPermArray = sort(new ArrayList<String>(permList));
+ LinkedHashMap<String, Boolean> newPerms = new LinkedHashMap<String, Boolean>();
+
+ Boolean value = false;
+ for (String permission : playerPermArray) {
+ value = (!permission.startsWith("-"));
+ newPerms.put((value ? permission : permission.substring(1)), value);
+ }
+
+
+
+ return newPerms;
+
+ }
+
+ /*
+ * Getter/Setters for TownyPerms
+ */
+
+ /**
+ * Default permissions everyone gets
+ *
+ * @return a List of permissions
+ */
+ public static List<String> getDefault() {
+
+ return getList("nomad");
+ }
+
+ /*
+ * Town permission section
+ */
+
+ /**
+ * Fetch a list of all available town ranks
+ *
+ * @return a list of rank names.
+ */
+ public static List<String> getTownRanks() {
+
+ return new ArrayList<String>(((MemorySection) perms.get("towns.ranks")).getKeys(false));
+ }
+
+ /**
+ * Default permissions everyone in a town gets
+ *
+ * @return a list of permissions
+ */
+ public static List<String> getTownDefault() {
+
+ return getList("towns.default");
+ }
+
+ /**
+ * A town mayors permissions
+ *
+ * @return a list of permissions
+ */
+ public static List<String> getTownMayor() {
+
+ return getList("towns.mayor");
+ }
+
+ /**
+ * Get a specific ranks permissions
+ *
+ * @param rank
+ * @return a List of permissions
+ */
+ public static List<String> getTownRank(String rank) {
+
+ return getList("towns.ranks." + rank.toLowerCase());
+ }
+
+ /*
+ * Nation permission section
+ */
+
+ /**
+ * Fetch a list of all available nation ranks
+ *
+ * @return a list of rank names.
+ */
+ public static List<String> getNationRanks() {
+
+ return new ArrayList<String>(((MemorySection) perms.get("nations.ranks")).getKeys(false));
+ }
+
+ /**
+ * Default permissions everyone in a nation gets
+ *
+ * @return a List of permissions
+ */
+ public static List<String> getNationDefault() {
+
+ return getList("nations.default");
+ }
+
+ /**
+ * A nations kings permissions
+ *
+ * @return a List of permissions
+ */
+ public static List<String> getNationKing() {
+
+ return getList("nations.king");
+ }
+
+ /**
+ * Get a specific ranks permissions
+ *
+ * @param rank
+ * @return a List of Permissions
+ */
+ public static List<String> getNationRank(String rank) {
+
+ return getList("nations.ranks." + rank.toLowerCase());
+ }
+
+ /*
+ * Permission utility functions taken from GroupManager (which I wrote anyway).
+ */
+
+ /**
+ * Update the list of permissions registered with bukkit
+ */
+ public static void collectPermissions() {
+
+ registeredPermissions.clear();
+
+ for (Permission perm : BukkitTools.getPluginManager().getPermissions()) {
+ registeredPermissions.put(perm.getName().toLowerCase(), perm);
+ }
+
+ }
+
+ /**
+ * Sort a permission node list by parent/child
+ *
+ * @param permList
+ * @return List sorted for priority
+ */
+ private static List<String> sort(List<String> permList) {
+
+ List<String> result = new ArrayList<String>();
+
+ for (String key : permList) {
+ String a = key.charAt(0) == '-' ? key.substring(1) : key;
+ Map<String, Boolean> allchildren = getAllChildren(a, new HashSet<String>());
+ if (allchildren != null) {
+
+ ListIterator<String> itr = result.listIterator();
+
+ while (itr.hasNext()) {
+ String node = (String) itr.next();
+ String b = node.charAt(0) == '-' ? node.substring(1) : node;
+
+ // Insert the parent node before the child
+ if (allchildren.containsKey(b)) {
+ itr.set(key);
+ itr.add(node);
+ break;
+ }
+ }
+ }
+ if (!result.contains(key))
+ result.add(key);
+ }
+
+ return result;
+ }
+
+ /**
+ * Fetch all permissions which are registered with superperms.
+ * {can include child nodes)
+ *
+ * @param includeChildren
+ * @return List of all permission nodes
+ */
+ public List<String> getAllRegisteredPermissions(boolean includeChildren) {
+
+ List<String> perms = new ArrayList<String>();
+
+ for (String key : registeredPermissions.keySet()) {
+ if (!perms.contains(key)) {
+ perms.add(key);
+
+ if (includeChildren) {
+ Map<String, Boolean> children = getAllChildren(key, new HashSet<String>());
+ if (children != null) {
+ for (String node : children.keySet())
+ if (!perms.contains(node))
+ perms.add(node);
+ }
+ }
+ }
+
+ }
+ return perms;
+ }
+
+ /**
+ * Returns a map of ALL child permissions registered with bukkit
+ * null is empty
+ *
+ * @param node
+ * @param playerPermArray current list of perms to check against for
+ * negations
+ * @return Map of child permissions
+ */
+ public static Map<String, Boolean> getAllChildren(String node, Set<String> playerPermArray) {
+
+ LinkedList<String> stack = new LinkedList<String>();
+ Map<String, Boolean> alreadyVisited = new HashMap<String, Boolean>();
+ stack.push(node);
+ alreadyVisited.put(node, true);
+
+ while (!stack.isEmpty()) {
+ String now = stack.pop();
+
+ Map<String, Boolean> children = getChildren(now);
+
+ if ((children != null) && (!playerPermArray.contains("-" + now))) {
+ for (String childName : children.keySet()) {
+ if (!alreadyVisited.containsKey(childName)) {
+ stack.push(childName);
+ alreadyVisited.put(childName, children.get(childName));
+ }
+ }
+ }
+ }
+ alreadyVisited.remove(node);
+ if (!alreadyVisited.isEmpty())
+ return alreadyVisited;
+
+ return null;
+ }
+
+ /**
+ * Returns a map of the child permissions (1 node deep) as registered with
+ * Bukkit.
+ * null is empty
+ *
+ * @param node
+ * @return Map of child permissions
+ */
+ public static Map<String, Boolean> getChildren(String node) {
+
+ Permission perm = registeredPermissions.get(node.toLowerCase());
+ if (perm == null)
+ return null;
+
+ return perm.getChildren();
+
+ }
+
+}
5 src/com/palmergames/bukkit/towny/tasks/OnPlayerLogin.java
View
@@ -18,6 +18,7 @@
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownyUniverse;
+import com.palmergames.bukkit.towny.permissions.TownyPerms;
import com.palmergames.bukkit.util.BukkitTools;
@@ -94,6 +95,10 @@ public void run() {
}
if (resident != null)
+
+ TownyPerms.assignPermissions(resident, null);
+
+
try {
TownyMessaging.sendTownBoard(player, resident.getTown());
} catch (NotRegisteredException ex) {
2  src/com/palmergames/util/FileMgmt.java
View
@@ -86,7 +86,7 @@ public static File CheckYMLExists(File file) {
return file;
}
- public static File unpackLanguageFile(String filePath, String resource, String defaultRes) {
+ public static File unpackResourceFile(String filePath, String resource, String defaultRes) {
// open a handle to yml file
File file = new File(filePath);
79 src/townyperms.yml
View
@@ -0,0 +1,79 @@
+# This file contains custom permission sets which will be assigned to your players
+# depending on their current status.
+#
+# This is all managed by towny and pushed directly to CraftBukkits SuperPerms.
+# These will be in addition to any you manually assign in your specific permission plugin.
+#
+# You may assign any Permission nodes here, including those from other plugins.
+# You may also create any custom ranks you require.
+
+
+# The 'nomad' permission set covers players not in any town
+nomad:
+ - towny.town.new
+ - towny.town.resident
+ - towny.town.spawn.public
+ - towny.town.plot.perm
+ - towny.chat.general
+
+# This section of permissions covers players who are members of a town.
+towns:
+ default:
+ # 'default' is the permission set which is auto assigned to any normal town member
+ - towny.town.plot.claim
+ - towny.town.plot.unclaim
+ - towny.town.plot.forsale
+ - towny.town.plot.notforsale
+ - towny.town.plot.perm
+ - towny.town.plot.toggle
+ - towny.town.plot.set
+ - towny.town.spawn.town
+ - towny.town.spawn.public
+ - towny.chat.general
+ - towny.chat.town
+ mayor:
+ # Mayors get these permissions in addition to the default set.
+ - towny.top
+ - towny.town.delete
+ - towny.town.rename
+ - towny.town.claim
+ - towny.town.plot
+ - towny.town.plottype
+ - towny.town.toggle.*
+ - towny.claimed.owntown.*
+ - towny.nation.new
+ - towny.town.grant-rank.*
+ ranks:
+ # Ranks contain additional permissions residents will be
+ # granted if they are assigned that specific rank.
+ assistant:
+ - towny.town.claim
+ - towny.town.plot
+ - towny.town.plottype
+ - towny.town.toggle.public
+ - towny.claimed.owntown.switch.*
+ - towny.town.grant-rank.vip
+ donator:
+ # Currently only a rank holder with no extra permissions
+ vip:
+ - towny.cheat.bypass
+
+# This section of permissions covers players who are members of any town in a nation.
+nations:
+ default:
+ # All nation members get these permissions.
+ - towny.town.spawn.nation
+ - towny.town.spawn.ally
+ - towny.chat.nation
+ king:
+ # Kings get these permissions in addition to the default set.
+ - towny.nation.delete
+ - towny.nation.rename
+ - towny.nation.grant-titles
+ - towny.nation.grant-rank.*
+ ranks:
+ assistant:
+ - towny.nation.grant-titles
+ - towny.nation.grant-rank.helper
+ helper:
+ # Currently only a rank holder with no extra permissions
Please sign in to comment.
Something went wrong with that request. Please try again.